blob: 5c98ebf39ab7d1fc23d1fffae393b5e02f147712 [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000025#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000026#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000027
28namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000029 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000055 TDF_TopLevelParameterTypeList = 0x10,
56 /// \brief Within template argument deduction from overload resolution per
57 /// C++ [over.over] allow matching function types that are compatible in
58 /// terms of noreturn and default calling convention adjustments.
59 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000060 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000061}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062
Douglas Gregor55ca8f62009-06-04 00:03:07 +000063using namespace clang;
64
Douglas Gregor0a29a052010-03-26 05:50:28 +000065/// \brief Compare two APSInts, extending and switching the sign as
66/// necessary to compare their values regardless of underlying type.
67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000069 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000070 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000071 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000072
73 // If there is a signedness mismatch, correct it.
74 if (X.isSigned() != Y.isSigned()) {
75 // If the signed value is negative, then the values cannot be the same.
76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77 return false;
78
79 Y.setIsSigned(true);
80 X.setIsSigned(true);
81 }
82
83 return X == Y;
84}
85
Douglas Gregor181aa4a2009-06-12 18:26:56 +000086static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000087DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000088 TemplateParameterList *TemplateParams,
89 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000090 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000091 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000092 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000093
Douglas Gregor7baabef2010-12-22 18:17:10 +000094static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000095DeduceTemplateArgumentsByTypeMatch(Sema &S,
96 TemplateParameterList *TemplateParams,
97 QualType Param,
98 QualType Arg,
99 TemplateDeductionInfo &Info,
100 SmallVectorImpl<DeducedTemplateArgument> &
101 Deduced,
102 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000103 bool PartialOrdering = false,
104 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000105
106static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000107DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000108 ArrayRef<TemplateArgument> Params,
109 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000110 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
112 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000113
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000114/// \brief If the given expression is of a form that permits the deduction
115/// of a non-type template parameter, return the declaration of that
116/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000117static NonTypeTemplateParmDecl *
118getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000119 // If we are within an alias template, the expression may have undergone
120 // any number of parameter substitutions already.
121 while (1) {
122 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
123 E = IC->getSubExpr();
124 else if (SubstNonTypeTemplateParmExpr *Subst =
125 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
126 E = Subst->getReplacement();
127 else
128 break;
129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000131 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000132 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
133 if (NTTP->getDepth() == Info.getDeducedDepth())
134 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000135
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000137}
138
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000139/// \brief Determine whether two declaration pointers refer to the same
140/// declaration.
141static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000142 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
143 X = NX->getUnderlyingDecl();
144 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
145 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000146
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000147 return X->getCanonicalDecl() == Y->getCanonicalDecl();
148}
149
150/// \brief Verify that the given, deduced template arguments are compatible.
151///
152/// \returns The deduced template argument, or a NULL template argument if
153/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000154static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000155checkDeducedTemplateArguments(ASTContext &Context,
156 const DeducedTemplateArgument &X,
157 const DeducedTemplateArgument &Y) {
158 // We have no deduction for one or both of the arguments; they're compatible.
159 if (X.isNull())
160 return Y;
161 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000162 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000163
Richard Smith593d6a12016-12-23 01:30:39 +0000164 // If we have two non-type template argument values deduced for the same
165 // parameter, they must both match the type of the parameter, and thus must
166 // match each other's type. As we're only keeping one of them, we must check
167 // for that now. The exception is that if either was deduced from an array
168 // bound, the type is permitted to differ.
169 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
170 QualType XType = X.getNonTypeTemplateArgumentType();
171 if (!XType.isNull()) {
172 QualType YType = Y.getNonTypeTemplateArgumentType();
173 if (YType.isNull() || !Context.hasSameType(XType, YType))
174 return DeducedTemplateArgument();
175 }
176 }
177
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000178 switch (X.getKind()) {
179 case TemplateArgument::Null:
180 llvm_unreachable("Non-deduced template arguments handled above");
181
182 case TemplateArgument::Type:
183 // If two template type arguments have the same type, they're compatible.
184 if (Y.getKind() == TemplateArgument::Type &&
185 Context.hasSameType(X.getAsType(), Y.getAsType()))
186 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
Richard Smith5f274382016-09-28 23:55:27 +0000188 // If one of the two arguments was deduced from an array bound, the other
189 // supersedes it.
190 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
191 return X.wasDeducedFromArrayBound() ? Y : X;
192
193 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000194 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000196 case TemplateArgument::Integral:
197 // If we deduced a constant in one case and either a dependent expression or
198 // declaration in another case, keep the integral constant.
199 // If both are integral constants with the same value, keep that value.
200 if (Y.getKind() == TemplateArgument::Expression ||
201 Y.getKind() == TemplateArgument::Declaration ||
202 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000203 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000204 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000205
206 // All other combinations are incompatible.
207 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000208
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000209 case TemplateArgument::Template:
210 if (Y.getKind() == TemplateArgument::Template &&
211 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
212 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000213
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000214 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000215 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000216
217 case TemplateArgument::TemplateExpansion:
218 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220 Y.getAsTemplateOrTemplatePattern()))
221 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000222
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000223 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000225
Richard Smith593d6a12016-12-23 01:30:39 +0000226 case TemplateArgument::Expression: {
227 if (Y.getKind() != TemplateArgument::Expression)
228 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000229
Richard Smith593d6a12016-12-23 01:30:39 +0000230 // Compare the expressions for equality
231 llvm::FoldingSetNodeID ID1, ID2;
232 X.getAsExpr()->Profile(ID1, Context, true);
233 Y.getAsExpr()->Profile(ID2, Context, true);
234 if (ID1 == ID2)
235 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Richard Smith593d6a12016-12-23 01:30:39 +0000237 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000241 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000242 assert(!X.wasDeducedFromArrayBound());
243
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000244 // If we deduced a declaration and a dependent expression, keep the
245 // declaration.
246 if (Y.getKind() == TemplateArgument::Expression)
247 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000248
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000249 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000250 // integral constant and whichever type did not come from an array
251 // bound.
252 if (Y.getKind() == TemplateArgument::Integral) {
253 if (Y.wasDeducedFromArrayBound())
254 return TemplateArgument(Context, Y.getAsIntegral(),
255 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000256 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000258
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 // If we deduced two declarations, make sure they they refer to the
260 // same declaration.
261 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000262 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000263 return X;
264
265 // All other combinations are incompatible.
266 return DeducedTemplateArgument();
267
268 case TemplateArgument::NullPtr:
269 // If we deduced a null pointer and a dependent expression, keep the
270 // null pointer.
271 if (Y.getKind() == TemplateArgument::Expression)
272 return X;
273
274 // If we deduced a null pointer and an integral constant, keep the
275 // integral constant.
276 if (Y.getKind() == TemplateArgument::Integral)
277 return Y;
278
Richard Smith593d6a12016-12-23 01:30:39 +0000279 // If we deduced two null pointers, they are the same.
280 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000283 // All other combinations are incompatible.
284 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286 case TemplateArgument::Pack:
287 if (Y.getKind() != TemplateArgument::Pack ||
288 X.pack_size() != Y.pack_size())
289 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
291 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000292 XAEnd = X.pack_end(),
293 YA = Y.pack_begin();
294 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000295 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000296 if (checkDeducedTemplateArguments(Context,
297 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000298 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
299 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return DeducedTemplateArgument();
301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 return X;
304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305
David Blaikiee4d798f2012-01-20 21:50:17 +0000306 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307}
308
Mike Stump11289f42009-09-09 15:08:12 +0000309/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000310/// from the given integral constant.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000311static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000312 Sema &S, TemplateParameterList *TemplateParams,
313 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000314 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
315 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000316 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
317 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000318
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000319 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
320 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000321 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000322 Deduced[NTTP->getIndex()],
323 NewDeduced);
324 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000325 Info.Param = NTTP;
326 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000327 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000331 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000332 return S.getLangOpts().CPlusPlus1z
333 ? DeduceTemplateArgumentsByTypeMatch(
334 S, TemplateParams, NTTP->getType(), ValueType, Info, Deduced,
335 TDF_ParamWithReferenceType | TDF_SkipNonDependent,
336 /*PartialOrdering=*/false,
337 /*ArrayBound=*/DeducedFromArrayBound)
338 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000339}
340
Mike Stump11289f42009-09-09 15:08:12 +0000341/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000342/// from the given null pointer template argument type.
343static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000344 Sema &S, TemplateParameterList *TemplateParams,
345 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000346 TemplateDeductionInfo &Info,
347 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
348 Expr *Value =
349 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
350 S.Context.NullPtrTy, NTTP->getLocation()),
351 NullPtrType, CK_NullToPointer)
352 .get();
353 DeducedTemplateArgument NewDeduced(Value);
354 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
355 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
356
357 if (Result.isNull()) {
358 Info.Param = NTTP;
359 Info.FirstArg = Deduced[NTTP->getIndex()];
360 Info.SecondArg = NewDeduced;
361 return Sema::TDK_Inconsistent;
362 }
363
364 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000365 return S.getLangOpts().CPlusPlus1z
366 ? DeduceTemplateArgumentsByTypeMatch(
367 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
368 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
369 : Sema::TDK_Success;
Richard Smith38175a22016-09-28 22:08:38 +0000370}
371
372/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000373/// from the given type- or value-dependent expression.
374///
375/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000377DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000378 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000379 NonTypeTemplateParmDecl *NTTP,
380 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000381 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000383 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
384 "deducing non-type template argument with wrong depth");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000385 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
386 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000387
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000388 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
390 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000391 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000393 if (Result.isNull()) {
394 Info.Param = NTTP;
395 Info.FirstArg = Deduced[NTTP->getIndex()];
396 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000400 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000401 return S.getLangOpts().CPlusPlus1z
402 ? DeduceTemplateArgumentsByTypeMatch(
403 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
404 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
405 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000406}
407
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000408/// \brief Deduce the value of the given non-type template parameter
409/// from the given declaration.
410///
411/// \returns true if deduction succeeded, false otherwise.
412static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000413DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000414 TemplateParameterList *TemplateParams,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000415 NonTypeTemplateParmDecl *NTTP,
Richard Smith5f274382016-09-28 23:55:27 +0000416 ValueDecl *D, QualType T,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000417 TemplateDeductionInfo &Info,
418 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000419 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
420 "deducing non-type template argument with wrong depth");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000421
Craig Topperc3ec1492014-05-26 06:22:03 +0000422 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000423 TemplateArgument New(D, T);
Eli Friedmanb826a002012-09-26 02:36:12 +0000424 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000426 Deduced[NTTP->getIndex()],
427 NewDeduced);
428 if (Result.isNull()) {
429 Info.Param = NTTP;
430 Info.FirstArg = Deduced[NTTP->getIndex()];
431 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000435 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000436 return S.getLangOpts().CPlusPlus1z
437 ? DeduceTemplateArgumentsByTypeMatch(
438 S, TemplateParams, NTTP->getType(), T, Info, Deduced,
439 TDF_ParamWithReferenceType | TDF_SkipNonDependent)
440 : Sema::TDK_Success;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000441}
442
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000443static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000444DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000445 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000446 TemplateName Param,
447 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000448 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000449 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000450 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000451 if (!ParamDecl) {
452 // The parameter type is dependent and is not a template template parameter,
453 // so there is nothing that we can deduce.
454 return Sema::TDK_Success;
455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456
Douglas Gregoradee3e32009-11-11 23:06:43 +0000457 if (TemplateTemplateParmDecl *TempParam
458 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000459 // If we're not deducing at this depth, there's nothing to deduce.
460 if (TempParam->getDepth() != Info.getDeducedDepth())
461 return Sema::TDK_Success;
462
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000463 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000465 Deduced[TempParam->getIndex()],
466 NewDeduced);
467 if (Result.isNull()) {
468 Info.Param = TempParam;
469 Info.FirstArg = Deduced[TempParam->getIndex()];
470 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000471 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000473
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000474 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477
Douglas Gregoradee3e32009-11-11 23:06:43 +0000478 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000479 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000480 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481
Douglas Gregoradee3e32009-11-11 23:06:43 +0000482 // Mismatch of non-dependent template parameter to argument.
483 Info.FirstArg = TemplateArgument(Param);
484 Info.SecondArg = TemplateArgument(Arg);
485 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000486}
487
Mike Stump11289f42009-09-09 15:08:12 +0000488/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000489/// type (which is a template-id) with the template argument type.
490///
Chandler Carruthc1263112010-02-07 21:33:28 +0000491/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000492///
493/// \param TemplateParams the template parameters that we are deducing
494///
495/// \param Param the parameter type
496///
497/// \param Arg the argument type
498///
499/// \param Info information about the template argument deduction itself
500///
501/// \param Deduced the deduced template arguments
502///
503/// \returns the result of template argument deduction so far. Note that a
504/// "success" result means that template argument deduction has not yet failed,
505/// but it may still fail, later, for other reasons.
506static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000507DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000508 TemplateParameterList *TemplateParams,
509 const TemplateSpecializationType *Param,
510 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000511 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000512 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000513 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregore81f3e72009-07-07 23:09:34 +0000515 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000516 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000517 = dyn_cast<TemplateSpecializationType>(Arg)) {
518 // Perform template argument deduction for the template name.
519 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000520 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000521 Param->getTemplateName(),
522 SpecArg->getTemplateName(),
523 Info, Deduced))
524 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Mike Stump11289f42009-09-09 15:08:12 +0000526
Douglas Gregore81f3e72009-07-07 23:09:34 +0000527 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000528 // argument. Ignore any missing/extra arguments, since they could be
529 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000530 return DeduceTemplateArguments(S, TemplateParams,
531 Param->template_arguments(),
532 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000533 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000534 }
Mike Stump11289f42009-09-09 15:08:12 +0000535
Douglas Gregore81f3e72009-07-07 23:09:34 +0000536 // If the argument type is a class template specialization, we
537 // perform template argument deduction using its template
538 // arguments.
539 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000540 if (!RecordArg) {
541 Info.FirstArg = TemplateArgument(QualType(Param, 0));
542 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000543 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000544 }
Mike Stump11289f42009-09-09 15:08:12 +0000545
546 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000547 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000548 if (!SpecArg) {
549 Info.FirstArg = TemplateArgument(QualType(Param, 0));
550 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000551 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000552 }
Mike Stump11289f42009-09-09 15:08:12 +0000553
Douglas Gregore81f3e72009-07-07 23:09:34 +0000554 // Perform template argument deduction for the template name.
555 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000556 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000557 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000558 Param->getTemplateName(),
559 TemplateName(SpecArg->getSpecializedTemplate()),
560 Info, Deduced))
561 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000562
Douglas Gregor7baabef2010-12-22 18:17:10 +0000563 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000564 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
565 SpecArg->getTemplateArgs().asArray(), Info,
566 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000567}
568
John McCall08569062010-08-28 22:14:41 +0000569/// \brief Determines whether the given type is an opaque type that
570/// might be more qualified when instantiated.
571static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
572 switch (T->getTypeClass()) {
573 case Type::TypeOfExpr:
574 case Type::TypeOf:
575 case Type::DependentName:
576 case Type::Decltype:
577 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000578 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000579 return true;
580
581 case Type::ConstantArray:
582 case Type::IncompleteArray:
583 case Type::VariableArray:
584 case Type::DependentSizedArray:
585 return IsPossiblyOpaquelyQualifiedType(
586 cast<ArrayType>(T)->getElementType());
587
588 default:
589 return false;
590 }
591}
592
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000593/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000595getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000596 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
597 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregor5499af42011-01-05 23:12:31 +0000599 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
600 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor5499af42011-01-05 23:12:31 +0000602 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
603 return std::make_pair(TTP->getDepth(), TTP->getIndex());
604}
605
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000606/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000608getDepthAndIndex(UnexpandedParameterPack UPP) {
609 if (const TemplateTypeParmType *TTP
610 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
611 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000613 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
614}
615
Douglas Gregor5499af42011-01-05 23:12:31 +0000616/// \brief Helper function to build a TemplateParameter when we don't
617/// know its type statically.
618static TemplateParameter makeTemplateParameter(Decl *D) {
619 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
620 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000621 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000622 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor5499af42011-01-05 23:12:31 +0000624 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
625}
626
Richard Smith0a80d572014-05-29 01:12:14 +0000627/// A pack that we're currently deducing.
628struct clang::DeducedPack {
629 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000630
Richard Smith0a80d572014-05-29 01:12:14 +0000631 // The index of the pack.
632 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
Richard Smith0a80d572014-05-29 01:12:14 +0000634 // The old value of the pack before we started deducing it.
635 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000636
Richard Smith0a80d572014-05-29 01:12:14 +0000637 // A deferred value of this pack from an inner deduction, that couldn't be
638 // deduced because this deduction hadn't happened yet.
639 DeducedTemplateArgument DeferredDeduction;
640
641 // The new value of the pack.
642 SmallVector<DeducedTemplateArgument, 4> New;
643
644 // The outer deduction for this pack, if any.
645 DeducedPack *Outer;
646};
647
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000648namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000649/// A scope in which we're performing pack deduction.
650class PackDeductionScope {
651public:
652 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
653 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
654 TemplateDeductionInfo &Info, TemplateArgument Pattern)
655 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
656 // Compute the set of template parameter indices that correspond to
657 // parameter packs expanded by the pack expansion.
658 {
659 llvm::SmallBitVector SawIndices(TemplateParams->size());
660 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
661 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
662 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
663 unsigned Depth, Index;
664 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000665 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000666 SawIndices[Index] = true;
667
668 // Save the deduced template argument for the parameter pack expanded
669 // by this pack expansion, then clear out the deduction.
670 DeducedPack Pack(Index);
671 Pack.Saved = Deduced[Index];
672 Deduced[Index] = TemplateArgument();
673
674 Packs.push_back(Pack);
675 }
676 }
677 }
678 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
679
680 for (auto &Pack : Packs) {
681 if (Info.PendingDeducedPacks.size() > Pack.Index)
682 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
683 else
684 Info.PendingDeducedPacks.resize(Pack.Index + 1);
685 Info.PendingDeducedPacks[Pack.Index] = &Pack;
686
687 if (S.CurrentInstantiationScope) {
688 // If the template argument pack was explicitly specified, add that to
689 // the set of deduced arguments.
690 const TemplateArgument *ExplicitArgs;
691 unsigned NumExplicitArgs;
692 NamedDecl *PartiallySubstitutedPack =
693 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
694 &ExplicitArgs, &NumExplicitArgs);
695 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000696 getDepthAndIndex(PartiallySubstitutedPack) ==
697 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000698 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
699 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000700 }
701 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000702
Richard Smith0a80d572014-05-29 01:12:14 +0000703 ~PackDeductionScope() {
704 for (auto &Pack : Packs)
705 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Richard Smith0a80d572014-05-29 01:12:14 +0000708 /// Move to deducing the next element in each pack that is being deduced.
709 void nextPackElement() {
710 // Capture the deduced template arguments for each parameter pack expanded
711 // by this pack expansion, add them to the list of arguments we've deduced
712 // for that pack, then clear out the deduced argument.
713 for (auto &Pack : Packs) {
714 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
715 if (!DeducedArg.isNull()) {
716 Pack.New.push_back(DeducedArg);
717 DeducedArg = DeducedTemplateArgument();
718 }
719 }
720 }
721
722 /// \brief Finish template argument deduction for a set of argument packs,
723 /// producing the argument packs and checking for consistency with prior
724 /// deductions.
725 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
726 // Build argument packs for each of the parameter packs expanded by this
727 // pack expansion.
728 for (auto &Pack : Packs) {
729 // Put back the old value for this pack.
730 Deduced[Pack.Index] = Pack.Saved;
731
732 // Build or find a new value for this pack.
733 DeducedTemplateArgument NewPack;
734 if (HasAnyArguments && Pack.New.empty()) {
735 if (Pack.DeferredDeduction.isNull()) {
736 // We were not able to deduce anything for this parameter pack
737 // (because it only appeared in non-deduced contexts), so just
738 // restore the saved argument pack.
739 continue;
740 }
741
742 NewPack = Pack.DeferredDeduction;
743 Pack.DeferredDeduction = TemplateArgument();
744 } else if (Pack.New.empty()) {
745 // If we deduced an empty argument pack, create it now.
746 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
747 } else {
748 TemplateArgument *ArgumentPack =
749 new (S.Context) TemplateArgument[Pack.New.size()];
750 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
751 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000752 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000753 Pack.New[0].wasDeducedFromArrayBound());
754 }
755
756 // Pick where we're going to put the merged pack.
757 DeducedTemplateArgument *Loc;
758 if (Pack.Outer) {
759 if (Pack.Outer->DeferredDeduction.isNull()) {
760 // Defer checking this pack until we have a complete pack to compare
761 // it against.
762 Pack.Outer->DeferredDeduction = NewPack;
763 continue;
764 }
765 Loc = &Pack.Outer->DeferredDeduction;
766 } else {
767 Loc = &Deduced[Pack.Index];
768 }
769
770 // Check the new pack matches any previous value.
771 DeducedTemplateArgument OldPack = *Loc;
772 DeducedTemplateArgument Result =
773 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
774
775 // If we deferred a deduction of this pack, check that one now too.
776 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
777 OldPack = Result;
778 NewPack = Pack.DeferredDeduction;
779 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
780 }
781
782 if (Result.isNull()) {
783 Info.Param =
784 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
785 Info.FirstArg = OldPack;
786 Info.SecondArg = NewPack;
787 return Sema::TDK_Inconsistent;
788 }
789
790 *Loc = Result;
791 }
792
793 return Sema::TDK_Success;
794 }
795
796private:
797 Sema &S;
798 TemplateParameterList *TemplateParams;
799 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
800 TemplateDeductionInfo &Info;
801
802 SmallVector<DeducedPack, 2> Packs;
803};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000804} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000805
Douglas Gregor5499af42011-01-05 23:12:31 +0000806/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807/// types to the list of argument types, as in the parameter-type-lists of
808/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000809///
810/// \param S The semantic analysis object within which we are deducing
811///
812/// \param TemplateParams The template parameters that we are deducing
813///
814/// \param Params The list of parameter types
815///
816/// \param NumParams The number of types in \c Params
817///
818/// \param Args The list of argument types
819///
820/// \param NumArgs The number of types in \c Args
821///
822/// \param Info information about the template argument deduction itself
823///
824/// \param Deduced the deduced template arguments
825///
826/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
827/// how template argument deduction is performed.
828///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000829/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000831/// (C++0x [temp.deduct.partial]).
832///
Douglas Gregor5499af42011-01-05 23:12:31 +0000833/// \returns the result of template argument deduction so far. Note that a
834/// "success" result means that template argument deduction has not yet failed,
835/// but it may still fail, later, for other reasons.
836static Sema::TemplateDeductionResult
837DeduceTemplateArguments(Sema &S,
838 TemplateParameterList *TemplateParams,
839 const QualType *Params, unsigned NumParams,
840 const QualType *Args, unsigned NumArgs,
841 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000842 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000843 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000844 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000845 // Fast-path check to see if we have too many/too few arguments.
846 if (NumParams != NumArgs &&
847 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
848 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000849 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Douglas Gregor5499af42011-01-05 23:12:31 +0000851 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000852 // Similarly, if P has a form that contains (T), then each parameter type
853 // Pi of the respective parameter-type- list of P is compared with the
854 // corresponding parameter type Ai of the corresponding parameter-type-list
855 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 unsigned ArgIdx = 0, ParamIdx = 0;
857 for (; ParamIdx != NumParams; ++ParamIdx) {
858 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000860 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
861 if (!Expansion) {
862 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 // Make sure we have an argument.
865 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000866 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000868 if (isa<PackExpansionType>(Args[ArgIdx])) {
869 // C++0x [temp.deduct.type]p22:
870 // If the original function parameter associated with A is a function
871 // parameter pack and the function parameter associated with P is not
872 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000873 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875
Douglas Gregor5499af42011-01-05 23:12:31 +0000876 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000877 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
878 Params[ParamIdx], Args[ArgIdx],
879 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000880 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000881 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882
Douglas Gregor5499af42011-01-05 23:12:31 +0000883 ++ArgIdx;
884 continue;
885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000887 // C++0x [temp.deduct.type]p5:
888 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000890 // parameter-declaration-clause.
891 if (ParamIdx + 1 < NumParams)
892 return Sema::TDK_Success;
893
Douglas Gregor5499af42011-01-05 23:12:31 +0000894 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000896 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000897 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000898 // comparison deduces template arguments for subsequent positions in the
899 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Douglas Gregor5499af42011-01-05 23:12:31 +0000901 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000902 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
Douglas Gregor5499af42011-01-05 23:12:31 +0000904 bool HasAnyArguments = false;
905 for (; ArgIdx < NumArgs; ++ArgIdx) {
906 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907
Douglas Gregor5499af42011-01-05 23:12:31 +0000908 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000910 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
911 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000912 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000913 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914
Richard Smith0a80d572014-05-29 01:12:14 +0000915 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917
Douglas Gregor5499af42011-01-05 23:12:31 +0000918 // Build argument packs for each of the parameter packs expanded by this
919 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000920 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000921 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000923
Douglas Gregor5499af42011-01-05 23:12:31 +0000924 // Make sure we don't have any extra arguments.
925 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000926 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927
Douglas Gregor5499af42011-01-05 23:12:31 +0000928 return Sema::TDK_Success;
929}
930
Douglas Gregor1d684c22011-04-28 00:56:09 +0000931/// \brief Determine whether the parameter has qualifiers that are either
932/// inconsistent with or a superset of the argument's qualifiers.
933static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
934 QualType ArgType) {
935 Qualifiers ParamQs = ParamType.getQualifiers();
936 Qualifiers ArgQs = ArgType.getQualifiers();
937
938 if (ParamQs == ArgQs)
939 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000940
Douglas Gregor1d684c22011-04-28 00:56:09 +0000941 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000942 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000943 ParamQs.hasObjCGCAttr())
944 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000945
Douglas Gregor1d684c22011-04-28 00:56:09 +0000946 // Mismatched (but not missing) address spaces.
947 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
948 ParamQs.hasAddressSpace())
949 return true;
950
John McCall31168b02011-06-15 23:02:42 +0000951 // Mismatched (but not missing) Objective-C lifetime qualifiers.
952 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
953 ParamQs.hasObjCLifetime())
954 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000955
Douglas Gregor1d684c22011-04-28 00:56:09 +0000956 // CVR qualifier superset.
957 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
958 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
959 == ParamQs.getCVRQualifiers());
960}
961
Douglas Gregor19a41f12013-04-17 08:45:07 +0000962/// \brief Compare types for equality with respect to possibly compatible
963/// function types (noreturn adjustment, implicit calling conventions). If any
964/// of parameter and argument is not a function, just perform type comparison.
965///
966/// \param Param the template parameter type.
967///
968/// \param Arg the argument type.
969bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
970 CanQualType Arg) {
971 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
972 *ArgFunction = Arg->getAs<FunctionType>();
973
974 // Just compare if not functions.
975 if (!ParamFunction || !ArgFunction)
976 return Param == Arg;
977
Richard Smith3c4f8d22016-10-16 17:54:23 +0000978 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000979 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000980 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000981 return Arg == Context.getCanonicalType(AdjustedParam);
982
983 // FIXME: Compatible calling conventions.
984
985 return Param == Arg;
986}
987
Douglas Gregorcceb9752009-06-26 18:27:22 +0000988/// \brief Deduce the template arguments by comparing the parameter type and
989/// the argument type (C++ [temp.deduct.type]).
990///
Chandler Carruthc1263112010-02-07 21:33:28 +0000991/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000992///
993/// \param TemplateParams the template parameters that we are deducing
994///
995/// \param ParamIn the parameter type
996///
997/// \param ArgIn the argument type
998///
999/// \param Info information about the template argument deduction itself
1000///
1001/// \param Deduced the deduced template arguments
1002///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001003/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001004/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001005///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001006/// \param PartialOrdering Whether we're performing template argument deduction
1007/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1008///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001009/// \returns the result of template argument deduction so far. Note that a
1010/// "success" result means that template argument deduction has not yet failed,
1011/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001012static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001013DeduceTemplateArgumentsByTypeMatch(Sema &S,
1014 TemplateParameterList *TemplateParams,
1015 QualType ParamIn, QualType ArgIn,
1016 TemplateDeductionInfo &Info,
1017 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1018 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001019 bool PartialOrdering,
1020 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001021 // We only want to look at the canonical types, since typedefs and
1022 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001023 QualType Param = S.Context.getCanonicalType(ParamIn);
1024 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001025
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001026 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001028 if (const PackExpansionType *ArgExpansion
1029 = dyn_cast<PackExpansionType>(Arg))
1030 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031
Douglas Gregorb837ea42011-01-11 17:34:58 +00001032 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001033 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034 // Before the partial ordering is done, certain transformations are
1035 // performed on the types used for partial ordering:
1036 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001037 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1038 if (ParamRef)
1039 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040
Douglas Gregorb837ea42011-01-11 17:34:58 +00001041 // - If A is a reference type, A is replaced by the type referred to.
1042 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1043 if (ArgRef)
1044 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045
Richard Smithed563c22015-02-20 04:45:22 +00001046 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1047 // C++11 [temp.deduct.partial]p9:
1048 // If, for a given type, deduction succeeds in both directions (i.e.,
1049 // the types are identical after the transformations above) and both
1050 // P and A were reference types [...]:
1051 // - if [one type] was an lvalue reference and [the other type] was
1052 // not, [the other type] is not considered to be at least as
1053 // specialized as [the first type]
1054 // - if [one type] is more cv-qualified than [the other type],
1055 // [the other type] is not considered to be at least as specialized
1056 // as [the first type]
1057 // Objective-C ARC adds:
1058 // - [one type] has non-trivial lifetime, [the other type] has
1059 // __unsafe_unretained lifetime, and the types are otherwise
1060 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001061 //
Richard Smithed563c22015-02-20 04:45:22 +00001062 // A is "considered to be at least as specialized" as P iff deduction
1063 // succeeds, so we model this as a deduction failure. Note that
1064 // [the first type] is P and [the other type] is A here; the standard
1065 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001066 Qualifiers ParamQuals = Param.getQualifiers();
1067 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001068 if ((ParamRef->isLValueReferenceType() &&
1069 !ArgRef->isLValueReferenceType()) ||
1070 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1071 (ParamQuals.hasNonTrivialObjCLifetime() &&
1072 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1073 ParamQuals.withoutObjCLifetime() ==
1074 ArgQuals.withoutObjCLifetime())) {
1075 Info.FirstArg = TemplateArgument(ParamIn);
1076 Info.SecondArg = TemplateArgument(ArgIn);
1077 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001078 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Richard Smithed563c22015-02-20 04:45:22 +00001081 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001082 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001084 // version of P.
1085 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001087 // version of A.
1088 Arg = Arg.getUnqualifiedType();
1089 } else {
1090 // C++0x [temp.deduct.call]p4 bullet 1:
1091 // - If the original P is a reference type, the deduced A (i.e., the type
1092 // referred to by the reference) can be more cv-qualified than the
1093 // transformed A.
1094 if (TDF & TDF_ParamWithReferenceType) {
1095 Qualifiers Quals;
1096 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1097 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001098 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001099 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101
Douglas Gregor85f240c2011-01-25 17:19:08 +00001102 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1103 // C++0x [temp.deduct.type]p10:
1104 // If P and A are function types that originated from deduction when
1105 // taking the address of a function template (14.8.2.2) or when deducing
1106 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107 // Ai are parameters of the top-level parameter-type-list of P and A,
1108 // respectively, Pi is adjusted if it is an rvalue reference to a
1109 // cv-unqualified template parameter and Ai is an lvalue reference, in
1110 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001111 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1112 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001113 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001114 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001115
Douglas Gregor85f240c2011-01-25 17:19:08 +00001116 if (const RValueReferenceType *ParamRef
1117 = Param->getAs<RValueReferenceType>()) {
1118 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1119 !ParamRef->getPointeeType().getQualifiers())
1120 if (Arg->isLValueReferenceType())
1121 Param = ParamRef->getPointeeType();
1122 }
1123 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001125
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001126 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001127 // A template type argument T, a template template argument TT or a
1128 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001129 // the following forms:
1130 //
1131 // T
1132 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001133 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001134 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001135 // Just skip any attempts to deduce from a placeholder type or a parameter
1136 // at a different depth.
1137 if (Arg->isPlaceholderType() ||
1138 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001139 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001140
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001141 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001142 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregor60454822009-07-22 20:02:25 +00001144 // If the argument type is an array type, move the qualifiers up to the
1145 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001146 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001147 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001148 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001149 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001150 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001151 RecanonicalizeArg = true;
1152 }
1153 }
Mike Stump11289f42009-09-09 15:08:12 +00001154
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001155 // The argument type can not be less qualified than the parameter
1156 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001157 if (!(TDF & TDF_IgnoreQualifiers) &&
1158 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001159 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001160 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001161 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001162 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001163 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001164
Richard Smith87d263e2016-12-25 08:05:23 +00001165 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1166 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001167 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001168 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001169
Douglas Gregor1d684c22011-04-28 00:56:09 +00001170 // Remove any qualifiers on the parameter from the deduced type.
1171 // We checked the qualifiers for consistency above.
1172 Qualifiers DeducedQs = DeducedType.getQualifiers();
1173 Qualifiers ParamQs = Param.getQualifiers();
1174 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1175 if (ParamQs.hasObjCGCAttr())
1176 DeducedQs.removeObjCGCAttr();
1177 if (ParamQs.hasAddressSpace())
1178 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001179 if (ParamQs.hasObjCLifetime())
1180 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001181
Douglas Gregore46db902011-06-17 22:11:49 +00001182 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001183 // If template deduction would produce a lifetime qualifier on a type
1184 // that is not a lifetime type, template argument deduction fails.
1185 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1186 !DeducedType->isDependentType()) {
1187 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1188 Info.FirstArg = TemplateArgument(Param);
1189 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001190 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001191 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001192
Douglas Gregora4f2b432011-07-26 14:53:44 +00001193 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001194 // If template deduction would produce an argument type with lifetime type
1195 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001196 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001197 DeducedType->isObjCLifetimeType() &&
1198 !DeducedQs.hasObjCLifetime())
1199 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001200
Douglas Gregor1d684c22011-04-28 00:56:09 +00001201 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1202 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001203
Douglas Gregord6605db2009-07-22 21:30:48 +00001204 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001205 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001206
Richard Smith5f274382016-09-28 23:55:27 +00001207 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001209 Deduced[Index],
1210 NewDeduced);
1211 if (Result.isNull()) {
1212 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1213 Info.FirstArg = Deduced[Index];
1214 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001218 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001219 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001220 }
1221
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001222 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001223 Info.FirstArg = TemplateArgument(ParamIn);
1224 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001225
Douglas Gregorfb322d82011-01-14 05:11:40 +00001226 // If the parameter is an already-substituted template parameter
1227 // pack, do nothing: we don't know which of its arguments to look
1228 // at, so we have to wait until all of the parameter packs in this
1229 // expansion have arguments.
1230 if (isa<SubstTemplateTypeParmPackType>(Param))
1231 return Sema::TDK_Success;
1232
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001233 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001234 CanQualType CanParam = S.Context.getCanonicalType(Param);
1235 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001236 if (!(TDF & TDF_IgnoreQualifiers)) {
1237 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001238 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001239 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001240 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001241 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001242 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001243 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001244
Douglas Gregor194ea692012-03-11 03:29:50 +00001245 // If the parameter type is not dependent, there is nothing to deduce.
1246 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001247 if (!(TDF & TDF_SkipNonDependent)) {
1248 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1249 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1250 Param != Arg;
1251 if (NonDeduced) {
1252 return Sema::TDK_NonDeducedMismatch;
1253 }
1254 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001255 return Sema::TDK_Success;
1256 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001257 } else if (!Param->isDependentType()) {
1258 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1259 ArgUnqualType = CanArg.getUnqualifiedType();
1260 bool Success = (TDF & TDF_InOverloadResolution)?
1261 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1262 ArgUnqualType) :
1263 ParamUnqualType == ArgUnqualType;
1264 if (Success)
1265 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001266 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001267
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001268 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001269 // Non-canonical types cannot appear here.
1270#define NON_CANONICAL_TYPE(Class, Base) \
1271 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1272#define TYPE(Class, Base)
1273#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001274
Douglas Gregor39c02722011-06-15 16:02:29 +00001275 case Type::TemplateTypeParm:
1276 case Type::SubstTemplateTypeParmPack:
1277 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001278
1279 // These types cannot be dependent, so simply check whether the types are
1280 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001281 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001282 case Type::VariableArray:
1283 case Type::Vector:
1284 case Type::FunctionNoProto:
1285 case Type::Record:
1286 case Type::Enum:
1287 case Type::ObjCObject:
1288 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001289 case Type::ObjCObjectPointer: {
1290 if (TDF & TDF_SkipNonDependent)
1291 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001292
Douglas Gregor194ea692012-03-11 03:29:50 +00001293 if (TDF & TDF_IgnoreQualifiers) {
1294 Param = Param.getUnqualifiedType();
1295 Arg = Arg.getUnqualifiedType();
1296 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001297
Douglas Gregor194ea692012-03-11 03:29:50 +00001298 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1299 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001300
1301 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001302 case Type::Complex:
1303 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001304 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1305 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001306 ComplexArg->getElementType(),
1307 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001308
1309 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001310
1311 // _Atomic T [extension]
1312 case Type::Atomic:
1313 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001314 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001315 cast<AtomicType>(Param)->getValueType(),
1316 AtomicArg->getValueType(),
1317 Info, Deduced, TDF);
1318
1319 return Sema::TDK_NonDeducedMismatch;
1320
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001321 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001322 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001323 QualType PointeeType;
1324 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1325 PointeeType = PointerArg->getPointeeType();
1326 } else if (const ObjCObjectPointerType *PointerArg
1327 = Arg->getAs<ObjCObjectPointerType>()) {
1328 PointeeType = PointerArg->getPointeeType();
1329 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001330 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001331 }
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregorfc516c92009-06-26 23:27:24 +00001333 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001334 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1335 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001336 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001337 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001338 }
Mike Stump11289f42009-09-09 15:08:12 +00001339
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001340 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001341 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001342 const LValueReferenceType *ReferenceArg =
1343 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001344 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001345 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001346
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001347 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001348 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001349 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001350 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001351
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001352 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001353 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001354 const RValueReferenceType *ReferenceArg =
1355 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001356 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001357 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001358
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001359 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1360 cast<RValueReferenceType>(Param)->getPointeeType(),
1361 ReferenceArg->getPointeeType(),
1362 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001365 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001366 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001367 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001368 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001369 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001370 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001371
John McCallf7332682010-08-19 00:20:19 +00001372 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001373 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1374 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1375 IncompleteArrayArg->getElementType(),
1376 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001377 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001378
1379 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001380 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001381 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001382 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001383 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001384 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001385
1386 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001387 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001388 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001389 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001390
John McCallf7332682010-08-19 00:20:19 +00001391 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001392 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1393 ConstantArrayParm->getElementType(),
1394 ConstantArrayArg->getElementType(),
1395 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001396 }
1397
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001398 // type [i]
1399 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001400 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001401 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001402 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001403
John McCallf7332682010-08-19 00:20:19 +00001404 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1405
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001406 // Check the element type of the arrays
1407 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001408 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001409 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001410 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1411 DependentArrayParm->getElementType(),
1412 ArrayArg->getElementType(),
1413 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001414 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001415
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001416 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001417 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001418 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001419 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001420 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001421
1422 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001423 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001424 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1425 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001426 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001427 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1428 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001429 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001430 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001431 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001432 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001433 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001434 if (const DependentSizedArrayType *DependentArrayArg
1435 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001436 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001437 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001438 DependentArrayArg->getSizeExpr(),
1439 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001440
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001441 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001442 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001443 }
Mike Stump11289f42009-09-09 15:08:12 +00001444
1445 // type(*)(T)
1446 // T(*)()
1447 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001448 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001449 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001450 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001451 dyn_cast<FunctionProtoType>(Arg);
1452 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001453 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001454
1455 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001456 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001457
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001458 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001459 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001460 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001461 != FunctionProtoArg->getRefQualifier() ||
1462 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001463 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001464
Anders Carlsson2128ec72009-06-08 15:19:08 +00001465 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001466 if (Sema::TemplateDeductionResult Result =
1467 DeduceTemplateArgumentsByTypeMatch(
1468 S, TemplateParams, FunctionProtoParam->getReturnType(),
1469 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001470 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001471
Alp Toker9cacbab2014-01-20 20:26:09 +00001472 return DeduceTemplateArguments(
1473 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1474 FunctionProtoParam->getNumParams(),
1475 FunctionProtoArg->param_type_begin(),
1476 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
John McCalle78aac42010-03-10 03:28:59 +00001479 case Type::InjectedClassName: {
1480 // Treat a template's injected-class-name as if the template
1481 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001482 Param = cast<InjectedClassNameType>(Param)
1483 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001484 assert(isa<TemplateSpecializationType>(Param) &&
1485 "injected class name is not a template specialization type");
1486 // fall through
1487 }
1488
Douglas Gregor705c9002009-06-26 20:57:09 +00001489 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001490 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001491 // TT<T>
1492 // TT<i>
1493 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001494 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001495 const TemplateSpecializationType *SpecParam =
1496 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001497
Richard Smith9b296e32016-04-25 19:09:05 +00001498 // When Arg cannot be a derived class, we can just try to deduce template
1499 // arguments from the template-id.
1500 const RecordType *RecordT = Arg->getAs<RecordType>();
1501 if (!(TDF & TDF_DerivedClass) || !RecordT)
1502 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1503 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001504
Richard Smith9b296e32016-04-25 19:09:05 +00001505 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1506 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001507
Richard Smith9b296e32016-04-25 19:09:05 +00001508 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1509 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001510
Richard Smith9b296e32016-04-25 19:09:05 +00001511 if (Result == Sema::TDK_Success)
1512 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001513
Richard Smith9b296e32016-04-25 19:09:05 +00001514 // We cannot inspect base classes as part of deduction when the type
1515 // is incomplete, so either instantiate any templates necessary to
1516 // complete the type, or skip over it if it cannot be completed.
1517 if (!S.isCompleteType(Info.getLocation(), Arg))
1518 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Richard Smith9b296e32016-04-25 19:09:05 +00001520 // C++14 [temp.deduct.call] p4b3:
1521 // If P is a class and P has the form simple-template-id, then the
1522 // transformed A can be a derived class of the deduced A. Likewise if
1523 // P is a pointer to a class of the form simple-template-id, the
1524 // transformed A can be a pointer to a derived class pointed to by the
1525 // deduced A.
1526 //
1527 // These alternatives are considered only if type deduction would
1528 // otherwise fail. If they yield more than one possible deduced A, the
1529 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001530
Faisal Vali683b0742016-05-19 02:28:21 +00001531 // Reset the incorrectly deduced argument from above.
1532 Deduced = DeducedOrig;
1533
1534 // Use data recursion to crawl through the list of base classes.
1535 // Visited contains the set of nodes we have already visited, while
1536 // ToVisit is our stack of records that we still need to visit.
1537 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1538 SmallVector<const RecordType *, 8> ToVisit;
1539 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001540 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001541 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001542 while (!ToVisit.empty()) {
1543 // Retrieve the next class in the inheritance hierarchy.
1544 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001545
Faisal Vali683b0742016-05-19 02:28:21 +00001546 // If we have already seen this type, skip it.
1547 if (!Visited.insert(NextT).second)
1548 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001549
Faisal Vali683b0742016-05-19 02:28:21 +00001550 // If this is a base class, try to perform template argument
1551 // deduction from it.
1552 if (NextT != RecordT) {
1553 TemplateDeductionInfo BaseInfo(Info.getLocation());
1554 Sema::TemplateDeductionResult BaseResult =
1555 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1556 QualType(NextT, 0), BaseInfo, Deduced);
1557
1558 // If template argument deduction for this base was successful,
1559 // note that we had some success. Otherwise, ignore any deductions
1560 // from this base class.
1561 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001562 // If we've already seen some success, then deduction fails due to
1563 // an ambiguity (temp.deduct.call p5).
1564 if (Successful)
1565 return Sema::TDK_MiscellaneousDeductionFailure;
1566
Faisal Vali683b0742016-05-19 02:28:21 +00001567 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001568 std::swap(SuccessfulDeduced, Deduced);
1569
Faisal Vali683b0742016-05-19 02:28:21 +00001570 Info.Param = BaseInfo.Param;
1571 Info.FirstArg = BaseInfo.FirstArg;
1572 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001573 }
1574
1575 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
Faisal Vali683b0742016-05-19 02:28:21 +00001578 // Visit base classes
1579 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1580 for (const auto &Base : Next->bases()) {
1581 assert(Base.getType()->isRecordType() &&
1582 "Base class that isn't a record?");
1583 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1584 }
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001587 if (Successful) {
1588 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001589 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001590 }
Richard Smith9b296e32016-04-25 19:09:05 +00001591
Douglas Gregore81f3e72009-07-07 23:09:34 +00001592 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001593 }
1594
Douglas Gregor637d9982009-06-10 23:47:09 +00001595 // T type::*
1596 // T T::*
1597 // T (type::*)()
1598 // type (T::*)()
1599 // type (type::*)(T)
1600 // type (T::*)(T)
1601 // T (type::*)(T)
1602 // T (T::*)()
1603 // T (T::*)(T)
1604 case Type::MemberPointer: {
1605 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1606 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1607 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001608 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001609
David Majnemera381cda2015-11-30 20:34:28 +00001610 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1611 if (ParamPointeeType->isFunctionType())
1612 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1613 /*IsCtorOrDtor=*/false, Info.getLocation());
1614 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1615 if (ArgPointeeType->isFunctionType())
1616 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1617 /*IsCtorOrDtor=*/false, Info.getLocation());
1618
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001619 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001620 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001621 ParamPointeeType,
1622 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001623 Info, Deduced,
1624 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001625 return Result;
1626
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001627 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628 QualType(MemPtrParam->getClass(), 0),
1629 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001630 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001631 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001632 }
1633
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001634 // (clang extension)
1635 //
Mike Stump11289f42009-09-09 15:08:12 +00001636 // type(^)(T)
1637 // T(^)()
1638 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001639 case Type::BlockPointer: {
1640 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1641 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001642
Anders Carlssona767eee2009-06-12 16:23:10 +00001643 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001644 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001645
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001646 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1647 BlockPtrParam->getPointeeType(),
1648 BlockPtrArg->getPointeeType(),
1649 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001650 }
1651
Douglas Gregor39c02722011-06-15 16:02:29 +00001652 // (clang extension)
1653 //
1654 // T __attribute__(((ext_vector_type(<integral constant>))))
1655 case Type::ExtVector: {
1656 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1657 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1658 // Make sure that the vectors have the same number of elements.
1659 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1660 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001661
Douglas Gregor39c02722011-06-15 16:02:29 +00001662 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001663 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1664 VectorParam->getElementType(),
1665 VectorArg->getElementType(),
1666 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001667 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001668
1669 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001670 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1671 // We can't check the number of elements, since the argument has a
1672 // dependent number of elements. This can only occur during partial
1673 // ordering.
1674
1675 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001676 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1677 VectorParam->getElementType(),
1678 VectorArg->getElementType(),
1679 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001680 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001681
Douglas Gregor39c02722011-06-15 16:02:29 +00001682 return Sema::TDK_NonDeducedMismatch;
1683 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001684
Douglas Gregor39c02722011-06-15 16:02:29 +00001685 // (clang extension)
1686 //
1687 // T __attribute__(((ext_vector_type(N))))
1688 case Type::DependentSizedExtVector: {
1689 const DependentSizedExtVectorType *VectorParam
1690 = cast<DependentSizedExtVectorType>(Param);
1691
1692 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(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
Richard Smith87d263e2016-12-25 08:05:23 +00001703 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001704 if (!NTTP)
1705 return Sema::TDK_Success;
1706
1707 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1708 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001709 // Note that we use the "array bound" rules here; just like in that
1710 // case, we don't have any particular type for the vector size, but
1711 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001712 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001713 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001714 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001715 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001716
1717 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001718 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1719 // Perform deduction on the element types.
1720 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001721 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1722 VectorParam->getElementType(),
1723 VectorArg->getElementType(),
1724 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001725 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001726
Douglas Gregor39c02722011-06-15 16:02:29 +00001727 // Perform deduction on the vector size, if we can.
1728 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001729 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001730 if (!NTTP)
1731 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001732
Richard Smith5f274382016-09-28 23:55:27 +00001733 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1734 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001735 Info, Deduced);
1736 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001737
Douglas Gregor39c02722011-06-15 16:02:29 +00001738 return Sema::TDK_NonDeducedMismatch;
1739 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001740
Douglas Gregor637d9982009-06-10 23:47:09 +00001741 case Type::TypeOfExpr:
1742 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001743 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001744 case Type::UnresolvedUsing:
1745 case Type::Decltype:
1746 case Type::UnaryTransform:
1747 case Type::Auto:
1748 case Type::DependentTemplateSpecialization:
1749 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001750 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001751 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001752 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001753 }
1754
David Blaikiee4d798f2012-01-20 21:50:17 +00001755 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001756}
1757
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001758static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001759DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001760 TemplateParameterList *TemplateParams,
1761 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001762 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001763 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001764 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001765 // If the template argument is a pack expansion, perform template argument
1766 // deduction against the pattern of that expansion. This only occurs during
1767 // partial ordering.
1768 if (Arg.isPackExpansion())
1769 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001771 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001772 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001773 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001774
1775 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001776 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001777 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1778 Param.getAsType(),
1779 Arg.getAsType(),
1780 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001781 Info.FirstArg = Param;
1782 Info.SecondArg = Arg;
1783 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001784
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001785 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001786 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001788 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001789 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001790 Info.FirstArg = Param;
1791 Info.SecondArg = Arg;
1792 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001793
1794 case TemplateArgument::TemplateExpansion:
1795 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001797 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001798 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001799 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001800 return Sema::TDK_Success;
1801
1802 Info.FirstArg = Param;
1803 Info.SecondArg = Arg;
1804 return Sema::TDK_NonDeducedMismatch;
1805
1806 case TemplateArgument::NullPtr:
1807 if (Arg.getKind() == TemplateArgument::NullPtr &&
1808 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001809 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001811 Info.FirstArg = Param;
1812 Info.SecondArg = Arg;
1813 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001814
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001815 case TemplateArgument::Integral:
1816 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001817 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001818 return Sema::TDK_Success;
1819
1820 Info.FirstArg = Param;
1821 Info.SecondArg = Arg;
1822 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001823 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001824
1825 if (Arg.getKind() == TemplateArgument::Expression) {
1826 Info.FirstArg = Param;
1827 Info.SecondArg = Arg;
1828 return Sema::TDK_NonDeducedMismatch;
1829 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001830
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001831 Info.FirstArg = Param;
1832 Info.SecondArg = Arg;
1833 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001835 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001836 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001837 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001838 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001839 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001840 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001841 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001842 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001843 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001844 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001845 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1846 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001847 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001848 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001849 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1850 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001851 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001852 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1853 Arg.getAsDecl(),
1854 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001855 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001857 Info.FirstArg = Param;
1858 Info.SecondArg = Arg;
1859 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001862 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001863 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001864 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001865 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001866 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001867 }
Mike Stump11289f42009-09-09 15:08:12 +00001868
David Blaikiee4d798f2012-01-20 21:50:17 +00001869 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001870}
1871
Douglas Gregor7baabef2010-12-22 18:17:10 +00001872/// \brief Determine whether there is a template argument to be used for
1873/// deduction.
1874///
1875/// This routine "expands" argument packs in-place, overriding its input
1876/// parameters so that \c Args[ArgIdx] will be the available template argument.
1877///
1878/// \returns true if there is another template argument (which will be at
1879/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001880static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1881 unsigned &ArgIdx) {
1882 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001883 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001884
Douglas Gregor7baabef2010-12-22 18:17:10 +00001885 const TemplateArgument &Arg = Args[ArgIdx];
1886 if (Arg.getKind() != TemplateArgument::Pack)
1887 return true;
1888
Richard Smith0bda5b52016-12-23 23:46:56 +00001889 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1890 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001891 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001892 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001893}
1894
Douglas Gregord0ad2942010-12-23 01:24:45 +00001895/// \brief Determine whether the given set of template arguments has a pack
1896/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001897static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1898 bool FoundPackExpansion = false;
1899 for (const auto &A : Args) {
1900 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001901 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001902
1903 if (A.getKind() == TemplateArgument::Pack)
1904 return hasPackExpansionBeforeEnd(A.pack_elements());
1905
1906 if (A.isPackExpansion())
1907 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909
Douglas Gregord0ad2942010-12-23 01:24:45 +00001910 return false;
1911}
1912
Douglas Gregor7baabef2010-12-22 18:17:10 +00001913static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001914DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001915 ArrayRef<TemplateArgument> Params,
1916 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001917 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001918 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1919 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921 // If the template argument list of P contains a pack expansion that is not
1922 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001923 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001924 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001925 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928 // If P has a form that contains <T> or <i>, then each argument Pi of the
1929 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001930 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001931 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001932 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001933 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001934 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935
Douglas Gregor7baabef2010-12-22 18:17:10 +00001936 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001937 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001938 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1939 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001941 if (Args[ArgIdx].isPackExpansion()) {
1942 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1943 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001944 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001947 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001948 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001949 = DeduceTemplateArguments(S, TemplateParams,
1950 Params[ParamIdx], Args[ArgIdx],
1951 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952 return Result;
1953
Douglas Gregor7baabef2010-12-22 18:17:10 +00001954 // Move to the next argument.
1955 ++ArgIdx;
1956 continue;
1957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001959 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001961 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // If Pi is a pack expansion, then the pattern of Pi is compared with
1963 // each remaining argument in the template argument list of A. Each
1964 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001965 // template parameter packs expanded by Pi.
1966 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001968 // FIXME: If there are no remaining arguments, we can bail out early
1969 // and set any deduced parameter packs to an empty argument pack.
1970 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971
Richard Smith0a80d572014-05-29 01:12:14 +00001972 // Prepare to deduce the packs within the pattern.
1973 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001974
1975 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001977 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001978 bool HasAnyArguments = false;
Richard Smith0bda5b52016-12-23 23:46:56 +00001979 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001980 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001982 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001984 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1985 Info, Deduced))
1986 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Richard Smith0a80d572014-05-29 01:12:14 +00001988 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001991 // Build argument packs for each of the parameter packs expanded by this
1992 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001993 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996
Douglas Gregor7baabef2010-12-22 18:17:10 +00001997 return Sema::TDK_Success;
1998}
1999
Mike Stump11289f42009-09-09 15:08:12 +00002000static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002001DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002002 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002003 const TemplateArgumentList &ParamList,
2004 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002005 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002006 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002007 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2008 ArgList.asArray(), Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002009}
2010
Douglas Gregor705c9002009-06-26 20:57:09 +00002011/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002012static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00002013 const TemplateArgument &X,
2014 const TemplateArgument &Y) {
2015 if (X.getKind() != Y.getKind())
2016 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor705c9002009-06-26 20:57:09 +00002018 switch (X.getKind()) {
2019 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002020 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor705c9002009-06-26 20:57:09 +00002022 case TemplateArgument::Type:
2023 return Context.getCanonicalType(X.getAsType()) ==
2024 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002025
Douglas Gregor705c9002009-06-26 20:57:09 +00002026 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002027 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002028
2029 case TemplateArgument::NullPtr:
2030 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002031
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002032 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002033 case TemplateArgument::TemplateExpansion:
2034 return Context.getCanonicalTemplateName(
2035 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2036 Context.getCanonicalTemplateName(
2037 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregor705c9002009-06-26 20:57:09 +00002039 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002040 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00002041
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002042 case TemplateArgument::Expression: {
2043 llvm::FoldingSetNodeID XID, YID;
2044 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002046 return XID == YID;
2047 }
Mike Stump11289f42009-09-09 15:08:12 +00002048
Douglas Gregor705c9002009-06-26 20:57:09 +00002049 case TemplateArgument::Pack:
2050 if (X.pack_size() != Y.pack_size())
2051 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002052
2053 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2054 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002055 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002056 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002057 if (!isSameTemplateArg(Context, *XP, *YP))
2058 return false;
2059
2060 return true;
2061 }
2062
David Blaikiee4d798f2012-01-20 21:50:17 +00002063 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002064}
2065
Douglas Gregorca4686d2011-01-04 23:35:54 +00002066/// \brief Allocate a TemplateArgumentLoc where all locations have
2067/// been initialized to the given location.
2068///
James Dennett634962f2012-06-14 21:40:34 +00002069/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002070/// location information for.
2071///
2072/// \param NTTPType For a declaration template argument, the type of
2073/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002074/// argument. Can be null if no type sugar is available to add to the
2075/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002076///
2077/// \param Loc The source location to use for the resulting template
2078/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002079TemplateArgumentLoc
2080Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2081 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002082 switch (Arg.getKind()) {
2083 case TemplateArgument::Null:
2084 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
Douglas Gregorca4686d2011-01-04 23:35:54 +00002086 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002087 return TemplateArgumentLoc(
2088 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089
Douglas Gregorca4686d2011-01-04 23:35:54 +00002090 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002091 if (NTTPType.isNull())
2092 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002093 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2094 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002095 return TemplateArgumentLoc(TemplateArgument(E), E);
2096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Eli Friedmanb826a002012-09-26 02:36:12 +00002098 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002099 if (NTTPType.isNull())
2100 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002101 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2102 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002103 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2104 E);
2105 }
2106
Douglas Gregorca4686d2011-01-04 23:35:54 +00002107 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002108 Expr *E =
2109 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002110 return TemplateArgumentLoc(TemplateArgument(E), E);
2111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregor9d802122011-03-02 17:09:35 +00002113 case TemplateArgument::Template:
2114 case TemplateArgument::TemplateExpansion: {
2115 NestedNameSpecifierLocBuilder Builder;
2116 TemplateName Template = Arg.getAsTemplate();
2117 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002118 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002119 else if (QualifiedTemplateName *QTN =
2120 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002121 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002122
Douglas Gregor9d802122011-03-02 17:09:35 +00002123 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002124 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002125 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002126
2127 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002128 Loc, Loc);
2129 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002130
Douglas Gregorca4686d2011-01-04 23:35:54 +00002131 case TemplateArgument::Expression:
2132 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133
Douglas Gregorca4686d2011-01-04 23:35:54 +00002134 case TemplateArgument::Pack:
2135 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
David Blaikiee4d798f2012-01-20 21:50:17 +00002138 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002139}
2140
2141
2142/// \brief Convert the given deduced template argument and add it to the set of
2143/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002144static bool
2145ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2146 DeducedTemplateArgument Arg,
2147 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002148 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002149 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002150 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002151 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2152 unsigned ArgumentPackIndex) {
2153 // Convert the deduced template argument into a template
2154 // argument that we can check, almost as if the user had written
2155 // the template argument explicitly.
2156 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002157 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002158
2159 // Check the template argument, converting it as necessary.
2160 return S.CheckTemplateArgument(
2161 Param, ArgLoc, Template, Template->getLocation(),
2162 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002163 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002164 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2165 : Sema::CTAK_Deduced)
2166 : Sema::CTAK_Specified);
2167 };
2168
Douglas Gregorca4686d2011-01-04 23:35:54 +00002169 if (Arg.getKind() == TemplateArgument::Pack) {
2170 // This is a template argument pack, so check each of its arguments against
2171 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002172 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002173 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002174 // When converting the deduced template argument, append it to the
2175 // general output list. We need to do this so that the template argument
2176 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002177 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002178 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002179 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2180 "deduced nested pack");
2181 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002182 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183
Douglas Gregor51bc5712011-01-05 20:52:18 +00002184 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002185 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002187
Richard Smithdf18ee92016-02-03 20:40:30 +00002188 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002189 // itself, in case that substitution fails.
2190 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002191 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002192 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002193 MultiLevelTemplateArgumentList Args(TemplateArgs);
2194
2195 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2196 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2197 NTTP, Output,
2198 Template->getSourceRange());
2199 if (Inst.isInvalid() ||
2200 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2201 NTTP->getDeclName()).isNull())
2202 return true;
2203 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2204 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2205 TTP, Output,
2206 Template->getSourceRange());
2207 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2208 return true;
2209 }
2210 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002211 }
Richard Smith37acb792016-02-03 20:15:01 +00002212
Douglas Gregorca4686d2011-01-04 23:35:54 +00002213 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002214 Output.push_back(
2215 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002216 return false;
2217 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002218
Richard Smith37acb792016-02-03 20:15:01 +00002219 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002220}
2221
Richard Smith1f5be4d2016-12-21 01:10:31 +00002222// FIXME: This should not be a template, but
2223// ClassTemplatePartialSpecializationDecl sadly does not derive from
2224// TemplateDecl.
2225template<typename TemplateDeclT>
2226static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002227 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002228 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2229 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2230 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2231 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2232 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2233
2234 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2235 NamedDecl *Param = TemplateParams->getParam(I);
2236
2237 if (!Deduced[I].isNull()) {
2238 if (I < NumAlreadyConverted) {
2239 // We have already fully type-checked and converted this
2240 // argument, because it was explicitly-specified. Just record the
2241 // presence of this argument.
2242 Builder.push_back(Deduced[I]);
2243 // We may have had explicitly-specified template arguments for a
2244 // template parameter pack (that may or may not have been extended
2245 // via additional deduced arguments).
2246 if (Param->isParameterPack() && CurrentInstantiationScope) {
2247 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2248 Param) {
2249 // Forget the partially-substituted pack; its substitution is now
2250 // complete.
2251 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2252 }
2253 }
2254 continue;
2255 }
2256
2257 // We have deduced this argument, so it still needs to be
2258 // checked and converted.
2259 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002260 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002261 Info.Param = makeTemplateParameter(Param);
2262 // FIXME: These template arguments are temporary. Free them!
2263 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2264 return Sema::TDK_SubstitutionFailure;
2265 }
2266
2267 continue;
2268 }
2269
2270 // C++0x [temp.arg.explicit]p3:
2271 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2272 // be deduced to an empty sequence of template arguments.
2273 // FIXME: Where did the word "trailing" come from?
2274 if (Param->isTemplateParameterPack()) {
2275 // We may have had explicitly-specified template arguments for this
2276 // template parameter pack. If so, our empty deduction extends the
2277 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2278 const TemplateArgument *ExplicitArgs;
2279 unsigned NumExplicitArgs;
2280 if (CurrentInstantiationScope &&
2281 CurrentInstantiationScope->getPartiallySubstitutedPack(
2282 &ExplicitArgs, &NumExplicitArgs) == Param) {
2283 Builder.push_back(TemplateArgument(
2284 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2285
2286 // Forget the partially-substituted pack; its substitution is now
2287 // complete.
2288 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2289 } else {
2290 // Go through the motions of checking the empty argument pack against
2291 // the parameter pack.
2292 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002293 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2294 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002295 Info.Param = makeTemplateParameter(Param);
2296 // FIXME: These template arguments are temporary. Free them!
2297 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2298 return Sema::TDK_SubstitutionFailure;
2299 }
2300 }
2301 continue;
2302 }
2303
2304 // Substitute into the default template argument, if available.
2305 bool HasDefaultArg = false;
2306 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2307 if (!TD) {
2308 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2309 return Sema::TDK_Incomplete;
2310 }
2311
2312 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2313 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2314 HasDefaultArg);
2315
2316 // If there was no default argument, deduction is incomplete.
2317 if (DefArg.getArgument().isNull()) {
2318 Info.Param = makeTemplateParameter(
2319 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2320 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2321 if (PartialOverloading) break;
2322
2323 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2324 : Sema::TDK_Incomplete;
2325 }
2326
2327 // Check whether we can actually use the default argument.
2328 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2329 TD->getSourceRange().getEnd(), 0, Builder,
2330 Sema::CTAK_Specified)) {
2331 Info.Param = makeTemplateParameter(
2332 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2333 // FIXME: These template arguments are temporary. Free them!
2334 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2335 return Sema::TDK_SubstitutionFailure;
2336 }
2337
2338 // If we get here, we successfully used the default template argument.
2339 }
2340
2341 return Sema::TDK_Success;
2342}
2343
Richard Smith0da6dc42016-12-24 16:40:51 +00002344DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2345 if (auto *DC = dyn_cast<DeclContext>(D))
2346 return DC;
2347 return D->getDeclContext();
2348}
2349
2350template<typename T> struct IsPartialSpecialization {
2351 static constexpr bool value = false;
2352};
2353template<>
2354struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2355 static constexpr bool value = true;
2356};
2357template<>
2358struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2359 static constexpr bool value = true;
2360};
2361
2362/// Complete template argument deduction for a partial specialization.
2363template <typename T>
2364static typename std::enable_if<IsPartialSpecialization<T>::value,
2365 Sema::TemplateDeductionResult>::type
2366FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002367 Sema &S, T *Partial, bool IsPartialOrdering,
2368 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002369 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2370 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002371 // Unevaluated SFINAE context.
2372 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002373 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374
Richard Smith0da6dc42016-12-24 16:40:51 +00002375 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002376
2377 // C++ [temp.deduct.type]p2:
2378 // [...] or if any template argument remains neither deduced nor
2379 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002380 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002381 if (auto Result = ConvertDeducedTemplateArguments(
2382 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002383 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002384
Douglas Gregor684268d2010-04-29 06:21:43 +00002385 // Form the template argument list from the deduced template arguments.
2386 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002387 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002388
Douglas Gregor684268d2010-04-29 06:21:43 +00002389 Info.reset(DeducedArgumentList);
2390
2391 // Substitute the deduced template arguments into the template
2392 // arguments of the class template partial specialization, and
2393 // verify that the instantiated template arguments are both valid
2394 // and are equivalent to the template arguments originally provided
2395 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002396 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002397 auto *Template = Partial->getSpecializedTemplate();
2398 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2399 Partial->getTemplateArgsAsWritten();
2400 const TemplateArgumentLoc *PartialTemplateArgs =
2401 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002402
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002403 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2404 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002405
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002406 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002407 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2408 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2409 if (ParamIdx >= Partial->getTemplateParameters()->size())
2410 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2411
Richard Smith0da6dc42016-12-24 16:40:51 +00002412 Decl *Param = const_cast<NamedDecl *>(
2413 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002414 Info.Param = makeTemplateParameter(Param);
2415 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2416 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002417 }
2418
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002419 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002420 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2421 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002422 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002423
Richard Smith0da6dc42016-12-24 16:40:51 +00002424 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002425 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002426 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002427 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002428 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002429 Info.FirstArg = TemplateArgs[I];
2430 Info.SecondArg = InstArg;
2431 return Sema::TDK_NonDeducedMismatch;
2432 }
2433 }
2434
2435 if (Trap.hasErrorOccurred())
2436 return Sema::TDK_SubstitutionFailure;
2437
2438 return Sema::TDK_Success;
2439}
2440
Douglas Gregor170bc422009-06-12 22:31:52 +00002441/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002442/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002443/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002444Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002445Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002446 const TemplateArgumentList &TemplateArgs,
2447 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002448 if (Partial->isInvalidDecl())
2449 return TDK_Invalid;
2450
Douglas Gregor170bc422009-06-12 22:31:52 +00002451 // C++ [temp.class.spec.match]p2:
2452 // A partial specialization matches a given actual template
2453 // argument list if the template arguments of the partial
2454 // specialization can be deduced from the actual template argument
2455 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002456
2457 // Unevaluated SFINAE context.
2458 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002459 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002460
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002461 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002462 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002463 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002464 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002465 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002466 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002467 TemplateArgs, Info, Deduced))
2468 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002469
Richard Smith80934652012-07-16 01:09:10 +00002470 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002471 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2472 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002473 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002474 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002475
Douglas Gregore1416332009-06-14 08:02:22 +00002476 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002477 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002478
Richard Smith87d263e2016-12-25 08:05:23 +00002479 return ::FinishTemplateArgumentDeduction(
2480 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002481}
Douglas Gregor91772d12009-06-13 00:26:55 +00002482
Larisse Voufo39a1e502013-08-06 01:03:05 +00002483/// \brief Perform template argument deduction to determine whether
2484/// the given template arguments match the given variable template
2485/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002486Sema::TemplateDeductionResult
2487Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2488 const TemplateArgumentList &TemplateArgs,
2489 TemplateDeductionInfo &Info) {
2490 if (Partial->isInvalidDecl())
2491 return TDK_Invalid;
2492
2493 // C++ [temp.class.spec.match]p2:
2494 // A partial specialization matches a given actual template
2495 // argument list if the template arguments of the partial
2496 // specialization can be deduced from the actual template argument
2497 // list (14.8.2).
2498
2499 // Unevaluated SFINAE context.
2500 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2501 SFINAETrap Trap(*this);
2502
2503 SmallVector<DeducedTemplateArgument, 4> Deduced;
2504 Deduced.resize(Partial->getTemplateParameters()->size());
2505 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2506 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2507 TemplateArgs, Info, Deduced))
2508 return Result;
2509
2510 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002511 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2512 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002513 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002514 return TDK_InstantiationDepth;
2515
2516 if (Trap.hasErrorOccurred())
2517 return Sema::TDK_SubstitutionFailure;
2518
Richard Smith87d263e2016-12-25 08:05:23 +00002519 return ::FinishTemplateArgumentDeduction(
2520 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002521}
2522
Douglas Gregorfc516c92009-06-26 23:27:24 +00002523/// \brief Determine whether the given type T is a simple-template-id type.
2524static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002525 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002526 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002527 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002528
Douglas Gregorfc516c92009-06-26 23:27:24 +00002529 return false;
2530}
Douglas Gregor9b146582009-07-08 20:55:45 +00002531
2532/// \brief Substitute the explicitly-provided template arguments into the
2533/// given function template according to C++ [temp.arg.explicit].
2534///
2535/// \param FunctionTemplate the function template into which the explicit
2536/// template arguments will be substituted.
2537///
James Dennett634962f2012-06-14 21:40:34 +00002538/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002539/// arguments.
2540///
Mike Stump11289f42009-09-09 15:08:12 +00002541/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002542/// with the converted and checked explicit template arguments.
2543///
Mike Stump11289f42009-09-09 15:08:12 +00002544/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002545/// parameters.
2546///
2547/// \param FunctionType if non-NULL, the result type of the function template
2548/// will also be instantiated and the pointed-to value will be updated with
2549/// the instantiated function type.
2550///
2551/// \param Info if substitution fails for any reason, this object will be
2552/// populated with more information about the failure.
2553///
2554/// \returns TDK_Success if substitution was successful, or some failure
2555/// condition.
2556Sema::TemplateDeductionResult
2557Sema::SubstituteExplicitTemplateArguments(
2558 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002559 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002560 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2561 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002562 QualType *FunctionType,
2563 TemplateDeductionInfo &Info) {
2564 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2565 TemplateParameterList *TemplateParams
2566 = FunctionTemplate->getTemplateParameters();
2567
John McCall6b51f282009-11-23 01:53:49 +00002568 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002569 // No arguments to substitute; just copy over the parameter types and
2570 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002571 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002572 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002573
Douglas Gregor9b146582009-07-08 20:55:45 +00002574 if (FunctionType)
2575 *FunctionType = Function->getType();
2576 return TDK_Success;
2577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578
Eli Friedman77dcc722012-02-08 03:07:05 +00002579 // Unevaluated SFINAE context.
2580 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002581 SFINAETrap Trap(*this);
2582
Douglas Gregor9b146582009-07-08 20:55:45 +00002583 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002584 // Template arguments that are present shall be specified in the
2585 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002586 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002587 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002588 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002589
2590 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002591 // explicitly-specified template arguments against this function template,
2592 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002593 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002594 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2595 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002596 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2597 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002598 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002599 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002600
Douglas Gregor9b146582009-07-08 20:55:45 +00002601 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002602 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002603 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002604 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002605 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002606 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002607 if (Index >= TemplateParams->size())
2608 Index = TemplateParams->size() - 1;
2609 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002610 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002611 }
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregor9b146582009-07-08 20:55:45 +00002613 // Form the template argument list from the explicitly-specified
2614 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002615 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002616 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002617 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618
John McCall036855a2010-10-12 19:40:14 +00002619 // Template argument deduction and the final substitution should be
2620 // done in the context of the templated declaration. Explicit
2621 // argument substitution, on the other hand, needs to happen in the
2622 // calling context.
2623 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2624
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002625 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002626 // note that the template argument pack is partially substituted and record
2627 // the explicit template arguments. They'll be used as part of deduction
2628 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002629 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2630 const TemplateArgument &Arg = Builder[I];
2631 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002632 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002633 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002634 Arg.pack_begin(),
2635 Arg.pack_size());
2636 break;
2637 }
2638 }
2639
Richard Smith5e580292012-02-10 09:58:53 +00002640 const FunctionProtoType *Proto
2641 = Function->getType()->getAs<FunctionProtoType>();
2642 assert(Proto && "Function template does not have a prototype?");
2643
Richard Smith70b13042015-01-09 01:19:56 +00002644 // Isolate our substituted parameters from our caller.
2645 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2646
John McCallc8e321d2016-03-01 02:09:25 +00002647 ExtParameterInfoBuilder ExtParamInfos;
2648
Douglas Gregor9b146582009-07-08 20:55:45 +00002649 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002650 // explicitly-specified template arguments. If the function has a trailing
2651 // return type, substitute it after the arguments to ensure we substitute
2652 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002653 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002654 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002655 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002656 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002657 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002658 return TDK_SubstitutionFailure;
2659 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002660
Richard Smith5e580292012-02-10 09:58:53 +00002661 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002662 QualType ResultType;
2663 {
2664 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002665 // If a declaration declares a member function or member function
2666 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002667 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002668 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002669 // declarator.
2670 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002671 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002672 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2673 ThisContext = Method->getParent();
2674 ThisTypeQuals = Method->getTypeQualifiers();
2675 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002676
Douglas Gregor3024f072012-04-16 07:05:22 +00002677 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002678 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002679
2680 ResultType =
2681 SubstType(Proto->getReturnType(),
2682 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2683 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002684 if (ResultType.isNull() || Trap.hasErrorOccurred())
2685 return TDK_SubstitutionFailure;
2686 }
John McCallc8e321d2016-03-01 02:09:25 +00002687
Richard Smith5e580292012-02-10 09:58:53 +00002688 // Instantiate the types of each of the function parameters given the
2689 // explicitly-specified template arguments if we didn't do so earlier.
2690 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002691 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002692 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002693 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002694 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002695 return TDK_SubstitutionFailure;
2696
Douglas Gregor9b146582009-07-08 20:55:45 +00002697 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002698 auto EPI = Proto->getExtProtoInfo();
2699 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002700 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002701 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002702 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002703 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002704 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2705 return TDK_SubstitutionFailure;
2706 }
Mike Stump11289f42009-09-09 15:08:12 +00002707
Douglas Gregor9b146582009-07-08 20:55:45 +00002708 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002709 // Trailing template arguments that can be deduced (14.8.2) may be
2710 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002711 // template arguments can be deduced, they may all be omitted; in this
2712 // case, the empty template argument list <> itself may also be omitted.
2713 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002714 // Take all of the explicitly-specified arguments and put them into
2715 // the set of deduced template arguments. Explicitly-specified
2716 // parameter packs, however, will be set to NULL since the deduction
2717 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002718 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002719 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2720 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2721 if (Arg.getKind() == TemplateArgument::Pack)
2722 Deduced.push_back(DeducedTemplateArgument());
2723 else
2724 Deduced.push_back(Arg);
2725 }
Mike Stump11289f42009-09-09 15:08:12 +00002726
Douglas Gregor9b146582009-07-08 20:55:45 +00002727 return TDK_Success;
2728}
2729
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002730/// \brief Check whether the deduced argument type for a call to a function
2731/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002732static bool
2733CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002734 QualType DeducedA) {
2735 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002736
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002737 QualType A = OriginalArg.OriginalArgType;
2738 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002739
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002740 // Check for type equality (top-level cv-qualifiers are ignored).
2741 if (Context.hasSameUnqualifiedType(A, DeducedA))
2742 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002743
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002744 // Strip off references on the argument types; they aren't needed for
2745 // the following checks.
2746 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2747 DeducedA = DeducedARef->getPointeeType();
2748 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2749 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002750
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002751 // C++ [temp.deduct.call]p4:
2752 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002753 // - If the original P is a reference type, the deduced A (i.e., the
2754 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002755 // the transformed A.
2756 if (const ReferenceType *OriginalParamRef
2757 = OriginalParamType->getAs<ReferenceType>()) {
2758 // We don't want to keep the reference around any more.
2759 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002760
Richard Smith1be59c52016-10-22 01:32:19 +00002761 // FIXME: Resolve core issue (no number yet): if the original P is a
2762 // reference type and the transformed A is function type "noexcept F",
2763 // the deduced A can be F.
2764 QualType Tmp;
2765 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2766 return false;
2767
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002768 Qualifiers AQuals = A.getQualifiers();
2769 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002770
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002771 // Under Objective-C++ ARC, the deduced type may have implicitly
2772 // been given strong or (when dealing with a const reference)
2773 // unsafe_unretained lifetime. If so, update the original
2774 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002775 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002776 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2777 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2778 (DeducedAQuals.hasConst() &&
2779 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2780 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002781 }
2782
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002783 if (AQuals == DeducedAQuals) {
2784 // Qualifiers match; there's nothing to do.
2785 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002786 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002787 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002788 // Qualifiers are compatible, so have the argument type adopt the
2789 // deduced argument type's qualifiers as if we had performed the
2790 // qualification conversion.
2791 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2792 }
2793 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002794
2795 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002796 // type that can be converted to the deduced A via a function pointer
2797 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002798 //
Richard Smith1be59c52016-10-22 01:32:19 +00002799 // Also allow conversions which merely strip __attribute__((noreturn)) from
2800 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002801 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002802 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002803 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002804 (S.IsQualificationConversion(A, DeducedA, false,
2805 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002806 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002807 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002808
Simon Pilgrim728134c2016-08-12 11:43:57 +00002809 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002810 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002811 // [...] Likewise, if P is a pointer to a class of the form
2812 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002813 // derived class pointed to by the deduced A.
2814 if (const PointerType *OriginalParamPtr
2815 = OriginalParamType->getAs<PointerType>()) {
2816 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2817 if (const PointerType *APtr = A->getAs<PointerType>()) {
2818 if (A->getPointeeType()->isRecordType()) {
2819 OriginalParamType = OriginalParamPtr->getPointeeType();
2820 DeducedA = DeducedAPtr->getPointeeType();
2821 A = APtr->getPointeeType();
2822 }
2823 }
2824 }
2825 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002826
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002827 if (Context.hasSameUnqualifiedType(A, DeducedA))
2828 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002829
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002830 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002831 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002832 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002833
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002834 return true;
2835}
2836
Mike Stump11289f42009-09-09 15:08:12 +00002837/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002838/// checking the deduced template arguments for completeness and forming
2839/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002840///
2841/// \param OriginalCallArgs If non-NULL, the original call arguments against
2842/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002843Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002844Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002845 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002846 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002847 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002848 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002849 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2850 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002851 // Unevaluated SFINAE context.
2852 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002853 SFINAETrap Trap(*this);
2854
Douglas Gregor9b146582009-07-08 20:55:45 +00002855 // Enter a new template instantiation context while we instantiate the
2856 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002857 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002858 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2859 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002860 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2861 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002862 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002863 return TDK_InstantiationDepth;
2864
John McCalle23b8712010-04-29 01:18:58 +00002865 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002866
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002867 // C++ [temp.deduct.type]p2:
2868 // [...] or if any template argument remains neither deduced nor
2869 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002870 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002871 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002872 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002873 CurrentInstantiationScope, NumExplicitlySpecified,
2874 PartialOverloading))
2875 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002876
2877 // Form the template argument list from the deduced template arguments.
2878 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002879 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002880 Info.reset(DeducedArgumentList);
2881
Mike Stump11289f42009-09-09 15:08:12 +00002882 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002883 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002884 DeclContext *Owner = FunctionTemplate->getDeclContext();
2885 if (FunctionTemplate->getFriendObjectKind())
2886 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002887 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002888 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002889 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002890 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002891 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002894 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002895
Mike Stump11289f42009-09-09 15:08:12 +00002896 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002897 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002898 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2899 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002900 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002901
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002902 // There may have been an error that did not prevent us from constructing a
2903 // declaration. Mark the declaration invalid and return with a substitution
2904 // failure.
2905 if (Trap.hasErrorOccurred()) {
2906 Specialization->setInvalidDecl(true);
2907 return TDK_SubstitutionFailure;
2908 }
2909
Douglas Gregore65aacb2011-06-16 16:50:48 +00002910 if (OriginalCallArgs) {
2911 // C++ [temp.deduct.call]p4:
2912 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002913 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002914 // is transformed as described above). [...]
2915 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2916 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002917 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002918
Douglas Gregore65aacb2011-06-16 16:50:48 +00002919 if (ParamIdx >= Specialization->getNumParams())
2920 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002921
Douglas Gregore65aacb2011-06-16 16:50:48 +00002922 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002923 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2924 Info.FirstArg = TemplateArgument(DeducedA);
2925 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2926 Info.CallArgIndex = OriginalArg.ArgIdx;
2927 return TDK_DeducedMismatch;
2928 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002929 }
2930 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002931
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002932 // If we suppressed any diagnostics while performing template argument
2933 // deduction, and if we haven't already instantiated this declaration,
2934 // keep track of these diagnostics. They'll be emitted if this specialization
2935 // is actually used.
2936 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002937 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002938 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2939 if (Pos == SuppressedDiagnostics.end())
2940 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2941 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002943
Mike Stump11289f42009-09-09 15:08:12 +00002944 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002945}
2946
John McCall8d08b9b2010-08-27 09:08:28 +00002947/// Gets the type of a function for template-argument-deducton
2948/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002949static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002950 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002951 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002952 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002953 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002954 return QualType();
2955
John McCallc1f69982010-02-02 02:21:27 +00002956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002957 if (Method->isInstance()) {
2958 // An instance method that's referenced in a form that doesn't
2959 // look like a member pointer is just invalid.
2960 if (!R.HasFormOfMemberPointer) return QualType();
2961
Richard Smith2a7d4812013-05-04 07:00:32 +00002962 return S.Context.getMemberPointerType(Fn->getType(),
2963 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002964 }
2965
2966 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002967 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002968}
2969
2970/// Apply the deduction rules for overload sets.
2971///
2972/// \return the null type if this argument should be treated as an
2973/// undeduced context
2974static QualType
2975ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002976 Expr *Arg, QualType ParamType,
2977 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978
John McCall8d08b9b2010-08-27 09:08:28 +00002979 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002980
John McCall8d08b9b2010-08-27 09:08:28 +00002981 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002982
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002983 // C++0x [temp.deduct.call]p4
2984 unsigned TDF = 0;
2985 if (ParamWasReference)
2986 TDF |= TDF_ParamWithReferenceType;
2987 if (R.IsAddressOfOperand)
2988 TDF |= TDF_IgnoreQualifiers;
2989
John McCallc1f69982010-02-02 02:21:27 +00002990 // C++0x [temp.deduct.call]p6:
2991 // When P is a function type, pointer to function type, or pointer
2992 // to member function type:
2993
2994 if (!ParamType->isFunctionType() &&
2995 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002996 !ParamType->isMemberFunctionPointerType()) {
2997 if (Ovl->hasExplicitTemplateArgs()) {
2998 // But we can still look for an explicit specialization.
2999 if (FunctionDecl *ExplicitSpec
3000 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003001 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003002 }
John McCallc1f69982010-02-02 02:21:27 +00003003
George Burgess IVcc2f3552016-03-19 21:51:45 +00003004 DeclAccessPair DAP;
3005 if (FunctionDecl *Viable =
3006 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3007 return GetTypeOfFunction(S, R, Viable);
3008
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003009 return QualType();
3010 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003011
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003012 // Gather the explicit template arguments, if any.
3013 TemplateArgumentListInfo ExplicitTemplateArgs;
3014 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003015 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003016 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003017 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3018 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003019 NamedDecl *D = (*I)->getUnderlyingDecl();
3020
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003021 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3022 // - If the argument is an overload set containing one or more
3023 // function templates, the parameter is treated as a
3024 // non-deduced context.
3025 if (!Ovl->hasExplicitTemplateArgs())
3026 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003027
3028 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003029 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003030 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003031 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3032 Specialization, Info))
3033 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003034
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003035 D = Specialization;
3036 }
John McCallc1f69982010-02-02 02:21:27 +00003037
3038 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003039 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003040 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003041
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003042 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003044 ArgType->isFunctionType())
3045 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046
John McCallc1f69982010-02-02 02:21:27 +00003047 // - If the argument is an overload set (not containing function
3048 // templates), trial argument deduction is attempted using each
3049 // of the members of the set. If deduction succeeds for only one
3050 // of the overload set members, that member is used as the
3051 // argument value for the deduction. If deduction succeeds for
3052 // more than one member of the overload set the parameter is
3053 // treated as a non-deduced context.
3054
3055 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3056 // Type deduction is done independently for each P/A pair, and
3057 // the deduced template argument values are then combined.
3058 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003059 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003060 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003061 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003062 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003063 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3064 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003065 if (Result) continue;
3066 if (!Match.isNull()) return QualType();
3067 Match = ArgType;
3068 }
3069
3070 return Match;
3071}
3072
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003073/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003074/// described in C++ [temp.deduct.call].
3075///
3076/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003077/// argument deduction based on this P/A pair because the argument is an
3078/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003079static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3080 TemplateParameterList *TemplateParams,
3081 QualType &ParamType,
3082 QualType &ArgType,
3083 Expr *Arg,
3084 unsigned &TDF) {
3085 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003086 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003087 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003088 if (ParamType.hasQualifiers())
3089 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003090
3091 // [...] If P is a reference type, the type referred to by P is
3092 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003093 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003094 if (ParamRefType)
3095 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003096
Nathan Sidwell96090022015-01-16 15:20:14 +00003097 // Overload sets usually make this parameter an undeduced context,
3098 // but there are sometimes special circumstances. Typically
3099 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003100 if (ArgType == S.Context.OverloadTy) {
3101 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3102 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003103 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003104 if (ArgType.isNull())
3105 return true;
3106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107
Douglas Gregor7825bf32011-01-06 22:09:01 +00003108 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003109 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003110 if (ArgType->isIncompleteArrayType()) {
3111 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003112 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003113 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003114
Douglas Gregor7825bf32011-01-06 22:09:01 +00003115 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003116 // If P is an rvalue reference to a cv-unqualified template
3117 // parameter and the argument is an lvalue, the type "lvalue
3118 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003119 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003120 !ParamType.getQualifiers() &&
3121 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003122 Arg->isLValue())
3123 ArgType = S.Context.getLValueReferenceType(ArgType);
3124 } else {
3125 // C++ [temp.deduct.call]p2:
3126 // If P is not a reference type:
3127 // - If A is an array type, the pointer type produced by the
3128 // array-to-pointer standard conversion (4.2) is used in place of
3129 // A for type deduction; otherwise,
3130 if (ArgType->isArrayType())
3131 ArgType = S.Context.getArrayDecayedType(ArgType);
3132 // - If A is a function type, the pointer type produced by the
3133 // function-to-pointer standard conversion (4.3) is used in place
3134 // of A for type deduction; otherwise,
3135 else if (ArgType->isFunctionType())
3136 ArgType = S.Context.getPointerType(ArgType);
3137 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003138 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003139 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003140 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003141 }
3142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143
Douglas Gregor7825bf32011-01-06 22:09:01 +00003144 // C++0x [temp.deduct.call]p4:
3145 // In general, the deduction process attempts to find template argument
3146 // values that will make the deduced A identical to A (after the type A
3147 // is transformed as described above). [...]
3148 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149
Douglas Gregor7825bf32011-01-06 22:09:01 +00003150 // - If the original P is a reference type, the deduced A (i.e., the
3151 // type referred to by the reference) can be more cv-qualified than
3152 // the transformed A.
3153 if (ParamRefType)
3154 TDF |= TDF_ParamWithReferenceType;
3155 // - The transformed A can be another pointer or pointer to member
3156 // type that can be converted to the deduced A via a qualification
3157 // conversion (4.4).
3158 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3159 ArgType->isObjCObjectPointerType())
3160 TDF |= TDF_IgnoreQualifiers;
3161 // - If P is a class and P has the form simple-template-id, then the
3162 // transformed A can be a derived class of the deduced A. Likewise,
3163 // if P is a pointer to a class of the form simple-template-id, the
3164 // transformed A can be a pointer to a derived class pointed to by
3165 // the deduced A.
3166 if (isSimpleTemplateIdType(ParamType) ||
3167 (isa<PointerType>(ParamType) &&
3168 isSimpleTemplateIdType(
3169 ParamType->getAs<PointerType>()->getPointeeType())))
3170 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor7825bf32011-01-06 22:09:01 +00003172 return false;
3173}
3174
Nico Weberc153d242014-07-28 00:02:09 +00003175static bool
3176hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3177 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003178
Hubert Tong3280b332015-06-25 00:25:49 +00003179static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3180 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3181 Expr *Arg, TemplateDeductionInfo &Info,
3182 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3183
3184/// \brief Attempt template argument deduction from an initializer list
3185/// deemed to be an argument in a function call.
3186static bool
3187DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3188 QualType AdjustedParamType, InitListExpr *ILE,
3189 TemplateDeductionInfo &Info,
3190 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3191 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003192
3193 // [temp.deduct.call] p1 (post CWG-1591)
3194 // If removing references and cv-qualifiers from P gives
3195 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3196 // non-empty initializer list (8.5.4), then deduction is performed instead for
3197 // each element of the initializer list, taking P0 as a function template
3198 // parameter type and the initializer element as its argument, and in the
3199 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3200 // length of the initializer list. Otherwise, an initializer list argument
3201 // causes the parameter to be considered a non-deduced context
3202
3203 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3204
3205 const bool IsDependentSizedArray =
3206 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3207
Faisal Validd76cc12015-12-10 12:29:11 +00003208 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003209
3210 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3211 S.isStdInitializerList(AdjustedParamType, &ElTy);
3212
3213 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003214 return false;
3215
3216 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003217 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3218 // deduce against the 'T' in T[N].
3219 if (ElTy.isNull()) {
3220 assert(!IsSTDList);
3221 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003222 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003223 // Deduction only needs to be done for dependent types.
3224 if (ElTy->isDependentType()) {
3225 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003226 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3227 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003228 return true;
3229 }
3230 }
3231 if (IsDependentSizedArray) {
3232 const DependentSizedArrayType *ArrTy =
3233 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3234 // Determine the array bound is something we can deduce.
3235 if (NonTypeTemplateParmDecl *NTTP =
Richard Smith87d263e2016-12-25 08:05:23 +00003236 getDeducedParameterFromExpr(Info, ArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003237 // We can perform template argument deduction for the given non-type
3238 // template parameter.
3239 assert(NTTP->getDepth() == 0 &&
3240 "Cannot deduce non-type template argument at depth > 0");
3241 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3242 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003243
Faisal Valif6dfdb32015-12-10 05:36:39 +00003244 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003245 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003246 /*ArrayBound=*/true, Info, Deduced);
3247 }
3248 }
Hubert Tong3280b332015-06-25 00:25:49 +00003249 return true;
3250}
3251
Sebastian Redl19181662012-03-15 21:40:51 +00003252/// \brief Perform template argument deduction by matching a parameter type
3253/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003254/// an initializer list that was originally matched against a parameter
3255/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003256static Sema::TemplateDeductionResult
3257DeduceTemplateArgumentByListElement(Sema &S,
3258 TemplateParameterList *TemplateParams,
3259 QualType ParamType, Expr *Arg,
3260 TemplateDeductionInfo &Info,
3261 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3262 unsigned TDF) {
3263 // Handle the case where an init list contains another init list as the
3264 // element.
3265 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003266 Sema::TemplateDeductionResult Result;
3267 if (!DeduceFromInitializerList(S, TemplateParams,
3268 ParamType.getNonReferenceType(), ILE, Info,
3269 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003270 return Sema::TDK_Success; // Just ignore this expression.
3271
Hubert Tong3280b332015-06-25 00:25:49 +00003272 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003273 }
3274
3275 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003276 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003277 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003278 ArgType, Arg, TDF)) {
3279 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003280 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003281 }
Sebastian Redl19181662012-03-15 21:40:51 +00003282 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003283 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003284}
3285
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003286/// \brief Perform template argument deduction from a function call
3287/// (C++ [temp.deduct.call]).
3288///
3289/// \param FunctionTemplate the function template for which we are performing
3290/// template argument deduction.
3291///
James Dennett18348b62012-06-22 08:52:37 +00003292/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003293/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003294///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003295/// \param Args the function call arguments
3296///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003297/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003298/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003299/// template argument deduction.
3300///
3301/// \param Info the argument will be updated to provide additional information
3302/// about template argument deduction.
3303///
3304/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003305Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3306 FunctionTemplateDecl *FunctionTemplate,
3307 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003308 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3309 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003310 if (FunctionTemplate->isInvalidDecl())
3311 return TDK_Invalid;
3312
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003313 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003314 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003315
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003316 // C++ [temp.deduct.call]p1:
3317 // Template argument deduction is done by comparing each function template
3318 // parameter type (call it P) with the type of the corresponding argument
3319 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003320 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003321 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003322 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003323 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003324 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003325 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003326 if (Proto->isTemplateVariadic())
3327 /* Do nothing */;
3328 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003329 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003331 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003332 }
Mike Stump11289f42009-09-09 15:08:12 +00003333
Douglas Gregor89026b52009-06-30 23:57:56 +00003334 // The types of the parameters from which we will perform template argument
3335 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003336 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003337 TemplateParameterList *TemplateParams
3338 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003339 SmallVector<DeducedTemplateArgument, 4> Deduced;
3340 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003341 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003342 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003343 TemplateDeductionResult Result =
3344 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003345 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003346 Deduced,
3347 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003348 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003349 Info);
3350 if (Result)
3351 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003352
3353 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003354 } else {
3355 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003356 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003357 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3358 }
Mike Stump11289f42009-09-09 15:08:12 +00003359
Douglas Gregor89026b52009-06-30 23:57:56 +00003360 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003361 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003362 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003363 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003364 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3365 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003366 QualType OrigParamType = ParamTypes[ParamIdx];
3367 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003368
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003370 = dyn_cast<PackExpansionType>(ParamType);
3371 if (!ParamExpansion) {
3372 // Simple case: matching a function parameter to a function argument.
3373 if (ArgIdx >= CheckArgs)
3374 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregor7825bf32011-01-06 22:09:01 +00003376 Expr *Arg = Args[ArgIdx++];
3377 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003378
Douglas Gregor7825bf32011-01-06 22:09:01 +00003379 unsigned TDF = 0;
3380 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3381 ParamType, ArgType, Arg,
3382 TDF))
3383 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Douglas Gregor0c83c812011-10-09 22:06:46 +00003385 // If we have nothing to deduce, we're done.
3386 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3387 continue;
3388
Sebastian Redl43144e72012-01-17 22:49:58 +00003389 // If the argument is an initializer list ...
3390 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003391 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003392 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003393 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3394 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003395 continue;
3396
Hubert Tong3280b332015-06-25 00:25:49 +00003397 if (Result)
3398 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003399 // Don't track the argument type, since an initializer list has none.
3400 continue;
3401 }
3402
Douglas Gregore65aacb2011-06-16 16:50:48 +00003403 // Keep track of the argument type and corresponding parameter index,
3404 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003405 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003406 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003407
Douglas Gregor7825bf32011-01-06 22:09:01 +00003408 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003409 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3410 ParamType, ArgType,
3411 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003412 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003413
Douglas Gregor7825bf32011-01-06 22:09:01 +00003414 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Douglas Gregor7825bf32011-01-06 22:09:01 +00003417 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418 // For a function parameter pack that occurs at the end of the
3419 // parameter-declaration-list, the type A of each remaining argument of
3420 // the call is compared with the type P of the declarator-id of the
3421 // function parameter pack. Each comparison deduces template arguments
3422 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003423 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003425 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003426 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
Douglas Gregor7825bf32011-01-06 22:09:01 +00003429 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003430 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3431 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Douglas Gregor7825bf32011-01-06 22:09:01 +00003433 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003434 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003435 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436
Douglas Gregore65aacb2011-06-16 16:50:48 +00003437 QualType OrigParamType = ParamPattern;
3438 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003439 Expr *Arg = Args[ArgIdx];
3440 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003441
Douglas Gregor7825bf32011-01-06 22:09:01 +00003442 unsigned TDF = 0;
3443 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3444 ParamType, ArgType, Arg,
3445 TDF)) {
3446 // We can't actually perform any deduction for this argument, so stop
3447 // deduction at this point.
3448 ++ArgIdx;
3449 break;
3450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Sebastian Redl43144e72012-01-17 22:49:58 +00003452 // As above, initializer lists need special handling.
3453 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003454 TemplateDeductionResult Result;
3455 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3456 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003457 ++ArgIdx;
3458 break;
3459 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003460
Hubert Tong3280b332015-06-25 00:25:49 +00003461 if (Result)
3462 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003463 } else {
3464
3465 // Keep track of the argument type and corresponding argument index,
3466 // so we can check for compatibility between the deduced A and A.
3467 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003468 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003469 ArgType));
3470
3471 if (TemplateDeductionResult Result
3472 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3473 ParamType, ArgType, Info,
3474 Deduced, TDF))
3475 return Result;
3476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477
Richard Smith0a80d572014-05-29 01:12:14 +00003478 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
Douglas Gregor7825bf32011-01-06 22:09:01 +00003481 // Build argument packs for each of the parameter packs expanded by this
3482 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003483 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003485
Douglas Gregor7825bf32011-01-06 22:09:01 +00003486 // After we've matching against a parameter pack, we're done.
3487 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003488 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003489
Mike Stump11289f42009-09-09 15:08:12 +00003490 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003491 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003492 Info, &OriginalCallArgs,
3493 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003494}
3495
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003496QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003497 QualType FunctionType,
3498 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003499 if (ArgFunctionType.isNull())
3500 return ArgFunctionType;
3501
3502 const FunctionProtoType *FunctionTypeP =
3503 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003504 const FunctionProtoType *ArgFunctionTypeP =
3505 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003506
3507 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3508 bool Rebuild = false;
3509
3510 CallingConv CC = FunctionTypeP->getCallConv();
3511 if (EPI.ExtInfo.getCC() != CC) {
3512 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3513 Rebuild = true;
3514 }
3515
3516 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3517 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3518 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3519 Rebuild = true;
3520 }
3521
3522 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3523 ArgFunctionTypeP->hasExceptionSpec())) {
3524 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3525 Rebuild = true;
3526 }
3527
3528 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003529 return ArgFunctionType;
3530
Richard Smithbaa47832016-12-01 02:11:49 +00003531 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3532 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003533}
3534
Douglas Gregor9b146582009-07-08 20:55:45 +00003535/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003536/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3537/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003538///
3539/// \param FunctionTemplate the function template for which we are performing
3540/// template argument deduction.
3541///
James Dennett18348b62012-06-22 08:52:37 +00003542/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003543/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003544///
3545/// \param ArgFunctionType the function type that will be used as the
3546/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003547/// function template's function type. This type may be NULL, if there is no
3548/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003549///
3550/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003551/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003552/// template argument deduction.
3553///
3554/// \param Info the argument will be updated to provide additional information
3555/// about template argument deduction.
3556///
Richard Smithbaa47832016-12-01 02:11:49 +00003557/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3558/// the address of a function template per [temp.deduct.funcaddr] and
3559/// [over.over]. If \c false, we are looking up a function template
3560/// specialization based on its signature, per [temp.deduct.decl].
3561///
Douglas Gregor9b146582009-07-08 20:55:45 +00003562/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003563Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3564 FunctionTemplateDecl *FunctionTemplate,
3565 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3566 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3567 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003568 if (FunctionTemplate->isInvalidDecl())
3569 return TDK_Invalid;
3570
Douglas Gregor9b146582009-07-08 20:55:45 +00003571 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3572 TemplateParameterList *TemplateParams
3573 = FunctionTemplate->getTemplateParameters();
3574 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003575
3576 // When taking the address of a function, we require convertibility of
3577 // the resulting function type. Otherwise, we allow arbitrary mismatches
3578 // of calling convention, noreturn, and noexcept.
3579 if (!IsAddressOfFunction)
3580 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3581 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Douglas Gregor9b146582009-07-08 20:55:45 +00003583 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003584 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003585 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003586 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003587 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003588 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003589 if (TemplateDeductionResult Result
3590 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003591 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003592 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003593 &FunctionType, Info))
3594 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003595
3596 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003597 }
3598
Eli Friedman77dcc722012-02-08 03:07:05 +00003599 // Unevaluated SFINAE context.
3600 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003601 SFINAETrap Trap(*this);
3602
John McCallc1f69982010-02-02 02:21:27 +00003603 Deduced.resize(TemplateParams->size());
3604
Richard Smith2a7d4812013-05-04 07:00:32 +00003605 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003606 // type so that we treat it as a non-deduced context in what follows. If we
3607 // are looking up by signature, the signature type should also have a deduced
3608 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003609 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003610 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003611 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003612 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003613 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003614 }
3615
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003616 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003617 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003618 if (IsAddressOfFunction)
3619 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003620 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003621 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003622 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003623 FunctionType, ArgFunctionType,
3624 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003625 return Result;
3626 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003627
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003629 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3630 NumExplicitlySpecified,
3631 Specialization, Info))
3632 return Result;
3633
Richard Smith2a7d4812013-05-04 07:00:32 +00003634 // If the function has a deduced return type, deduce it now, so we can check
3635 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003636 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003637 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003638 DeduceReturnType(Specialization, Info.getLocation(), false))
3639 return TDK_MiscellaneousDeductionFailure;
3640
Richard Smith9095e5b2016-11-01 01:31:23 +00003641 // If the function has a dependent exception specification, resolve it now,
3642 // so we can check that the exception specification matches.
3643 auto *SpecializationFPT =
3644 Specialization->getType()->castAs<FunctionProtoType>();
3645 if (getLangOpts().CPlusPlus1z &&
3646 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3647 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3648 return TDK_MiscellaneousDeductionFailure;
3649
Richard Smithbaa47832016-12-01 02:11:49 +00003650 // Adjust the exception specification of the argument again to match the
3651 // substituted and resolved type we just formed. (Calling convention and
3652 // noreturn can't be dependent, so we don't actually need this for them
3653 // right now.)
3654 QualType SpecializationType = Specialization->getType();
3655 if (!IsAddressOfFunction)
3656 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3657 /*AdjustExceptionSpec*/true);
3658
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003659 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003660 // specialization with respect to arguments of compatible pointer to function
3661 // types, template argument deduction fails.
3662 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003663 if (IsAddressOfFunction &&
3664 !isSameOrCompatibleFunctionType(
3665 Context.getCanonicalType(SpecializationType),
3666 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003667 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003668
3669 if (!IsAddressOfFunction &&
3670 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003671 return TDK_MiscellaneousDeductionFailure;
3672 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003673
3674 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003675}
3676
Simon Pilgrim728134c2016-08-12 11:43:57 +00003677/// \brief Given a function declaration (e.g. a generic lambda conversion
3678/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003679/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3680/// to replace 'auto' with and not the actual result type you want
3681/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003682static inline void
3683SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003684 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003685 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003686 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003687 assert(AutoResultType->getContainedAutoType());
3688 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003689 TypeToReplaceAutoWith);
3690 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3691}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003692
Simon Pilgrim728134c2016-08-12 11:43:57 +00003693/// \brief Given a specialized conversion operator of a generic lambda
3694/// create the corresponding specializations of the call operator and
3695/// the static-invoker. If the return type of the call operator is auto,
3696/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003697/// return type of the destination function ptr.
3698
Simon Pilgrim728134c2016-08-12 11:43:57 +00003699static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003700SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3701 CXXConversionDecl *ConversionSpecialized,
3702 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3703 QualType ReturnTypeOfDestFunctionPtr,
3704 TemplateDeductionInfo &TDInfo,
3705 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003706
Faisal Vali2b3a3012013-10-24 23:40:02 +00003707 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003708 assert(LambdaClass && LambdaClass->isGenericLambda());
3709
Faisal Vali2b3a3012013-10-24 23:40:02 +00003710 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003711 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003712 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003713 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003714
3715 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003716 CallOpGeneric->getDescribedFunctionTemplate();
3717
Craig Topperc3ec1492014-05-26 06:22:03 +00003718 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003719 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003720 // generic lambda's call operator.
3721 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003722 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3723 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003724 0, CallOpSpecialized, TDInfo))
3725 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003726
Faisal Vali2b3a3012013-10-24 23:40:02 +00003727 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003728 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3729 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003730 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003731 CallOpSpecialized->getPointOfInstantiation(),
3732 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003733
Faisal Vali2b3a3012013-10-24 23:40:02 +00003734 // Check to see if the return type of the destination ptr-to-function
3735 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003736 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003737 ReturnTypeOfDestFunctionPtr))
3738 return Sema::TDK_NonDeducedMismatch;
3739 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003740 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003741 // specialized our corresponding call operator, we are ready to
3742 // specialize the static invoker with the deduced arguments of our
3743 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003744 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003745 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3746 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3747
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003748#ifndef NDEBUG
3749 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3750#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003751 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003752 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003753 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003754 "If the call operator succeeded so should the invoker!");
3755 // Set the result type to match the corresponding call operator
3756 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003757 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3758 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003759 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003760 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003761 // to substitute into the 'auto' of the invoker and conversion
3762 // function.
3763 // For e.g.
3764 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3765 // We don't want to subst 'int*' into 'auto' to get int**.
3766
Alp Toker314cc812014-01-25 16:55:45 +00003767 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3768 ->getContainedAutoType()
3769 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003770 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3771 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003772 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003773 TypeToReplaceAutoWith, S);
3774 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003775
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003777 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003778 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003779 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003780 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3781 getType().getTypePtr()->castAs<FunctionProtoType>();
3782 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3783 EPI.TypeQuals = 0;
3784 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003785 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003786 return Sema::TDK_Success;
3787}
Douglas Gregor05155d82009-08-21 23:19:43 +00003788/// \brief Deduce template arguments for a templated conversion
3789/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3790/// conversion function template specialization.
3791Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003792Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003793 QualType ToType,
3794 CXXConversionDecl *&Specialization,
3795 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003796 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003797 return TDK_Invalid;
3798
Faisal Vali2b3a3012013-10-24 23:40:02 +00003799 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003800 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3801
Faisal Vali2b3a3012013-10-24 23:40:02 +00003802 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003803
3804 // Canonicalize the types for deduction.
3805 QualType P = Context.getCanonicalType(FromType);
3806 QualType A = Context.getCanonicalType(ToType);
3807
Douglas Gregord99609a2011-03-06 09:03:20 +00003808 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003809 // If P is a reference type, the type referred to by P is used for
3810 // type deduction.
3811 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3812 P = PRef->getPointeeType();
3813
Douglas Gregord99609a2011-03-06 09:03:20 +00003814 // C++0x [temp.deduct.conv]p4:
3815 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003816 // for type deduction.
3817 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003818 A = ARef->getPointeeType().getUnqualifiedType();
3819 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003820 //
Mike Stump11289f42009-09-09 15:08:12 +00003821 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003822 else {
3823 assert(!A->isReferenceType() && "Reference types were handled above");
3824
3825 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003826 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003827 // of P for type deduction; otherwise,
3828 if (P->isArrayType())
3829 P = Context.getArrayDecayedType(P);
3830 // - If P is a function type, the pointer type produced by the
3831 // function-to-pointer standard conversion (4.3) is used in
3832 // place of P for type deduction; otherwise,
3833 else if (P->isFunctionType())
3834 P = Context.getPointerType(P);
3835 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003836 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003837 else
3838 P = P.getUnqualifiedType();
3839
Douglas Gregord99609a2011-03-06 09:03:20 +00003840 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003841 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003842 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003843 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 A = A.getUnqualifiedType();
3845 }
3846
Eli Friedman77dcc722012-02-08 03:07:05 +00003847 // Unevaluated SFINAE context.
3848 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003849 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003850
3851 // C++ [temp.deduct.conv]p1:
3852 // Template argument deduction is done by comparing the return
3853 // type of the template conversion function (call it P) with the
3854 // type that is required as the result of the conversion (call it
3855 // A) as described in 14.8.2.4.
3856 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003857 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003858 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003859 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003860
3861 // C++0x [temp.deduct.conv]p4:
3862 // In general, the deduction process attempts to find template
3863 // argument values that will make the deduced A identical to
3864 // A. However, there are two cases that allow a difference:
3865 unsigned TDF = 0;
3866 // - If the original A is a reference type, A can be more
3867 // cv-qualified than the deduced A (i.e., the type referred to
3868 // by the reference)
3869 if (ToType->isReferenceType())
3870 TDF |= TDF_ParamWithReferenceType;
3871 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003872 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003873 // conversion.
3874 //
3875 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3876 // both P and A are pointers or member pointers. In this case, we
3877 // just ignore cv-qualifiers completely).
3878 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003879 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003880 TDF |= TDF_IgnoreQualifiers;
3881 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003882 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3883 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003884 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003885
3886 // Create an Instantiation Scope for finalizing the operator.
3887 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003888 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003889 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003890 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003891 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003892 ConversionSpecialized, Info);
3893 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3894
3895 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003896 // to a ptr-to-function, use the deduced arguments from the conversion
3897 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003898 // e.g., int (*fp)(int) = [](auto a) { return a; };
3899 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003900
Faisal Vali2b3a3012013-10-24 23:40:02 +00003901 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003902 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003903 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003904 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003905 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003906 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003907 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003908 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3909
Simon Pilgrim728134c2016-08-12 11:43:57 +00003910 // Create the corresponding specializations of the call operator and
3911 // the static-invoker; and if the return type is auto,
3912 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003913 // DestFunctionPtrReturnType.
3914 // For instance:
3915 // auto L = [](auto a) { return f(a); };
3916 // int (*fp)(int) = L;
3917 // char (*fp2)(int) = L; <-- Not OK.
3918
3919 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003920 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003921 Info, *this);
3922 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003923 return Result;
3924}
3925
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003926/// \brief Deduce template arguments for a function template when there is
3927/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3928///
3929/// \param FunctionTemplate the function template for which we are performing
3930/// template argument deduction.
3931///
James Dennett18348b62012-06-22 08:52:37 +00003932/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003933/// arguments.
3934///
3935/// \param Specialization if template argument deduction was successful,
3936/// this will be set to the function template specialization produced by
3937/// template argument deduction.
3938///
3939/// \param Info the argument will be updated to provide additional information
3940/// about template argument deduction.
3941///
Richard Smithbaa47832016-12-01 02:11:49 +00003942/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3943/// the address of a function template in a context where we do not have a
3944/// target type, per [over.over]. If \c false, we are looking up a function
3945/// template specialization based on its signature, which only happens when
3946/// deducing a function parameter type from an argument that is a template-id
3947/// naming a function template specialization.
3948///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003949/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003950Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3951 FunctionTemplateDecl *FunctionTemplate,
3952 TemplateArgumentListInfo *ExplicitTemplateArgs,
3953 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3954 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003955 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003956 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003957 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003958}
3959
Richard Smith30482bc2011-02-20 03:19:35 +00003960namespace {
3961 /// Substitute the 'auto' type specifier within a type for a given replacement
3962 /// type.
3963 class SubstituteAutoTransform :
3964 public TreeTransform<SubstituteAutoTransform> {
3965 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003966 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003967 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003968 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3969 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003970 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003971 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003972
Richard Smith30482bc2011-02-20 03:19:35 +00003973 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3974 // If we're building the type pattern to deduce against, don't wrap the
3975 // substituted type in an AutoType. Certain template deduction rules
3976 // apply only when a template type parameter appears directly (and not if
3977 // the parameter is found through desugaring). For instance:
3978 // auto &&lref = lvalue;
3979 // must transform into "rvalue reference to T" not "rvalue reference to
3980 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003981 if (!UseAutoSugar) {
3982 assert(isa<TemplateTypeParmType>(Replacement) &&
3983 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00003984 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003985 TemplateTypeParmTypeLoc NewTL =
3986 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003987 NewTL.setNameLoc(TL.getNameLoc());
3988 return Result;
3989 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00003990 QualType Result = SemaRef.Context.getAutoType(
3991 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00003992 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3993 NewTL.setNameLoc(TL.getNameLoc());
3994 return Result;
3995 }
3996 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003997
3998 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3999 // Lambdas never need to be transformed.
4000 return E;
4001 }
Richard Smith061f1e22013-04-30 21:23:01 +00004002
Richard Smith2a7d4812013-05-04 07:00:32 +00004003 QualType Apply(TypeLoc TL) {
4004 // Create some scratch storage for the transformed type locations.
4005 // FIXME: We're just going to throw this information away. Don't build it.
4006 TypeLocBuilder TLB;
4007 TLB.reserve(TL.getFullDataSize());
4008 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004009 }
Richard Smith30482bc2011-02-20 03:19:35 +00004010 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004011}
Richard Smith30482bc2011-02-20 03:19:35 +00004012
Richard Smith2a7d4812013-05-04 07:00:32 +00004013Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004014Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4015 Optional<unsigned> DependentDeductionDepth) {
4016 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4017 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004018}
4019
Richard Smith061f1e22013-04-30 21:23:01 +00004020/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004021///
Richard Smith87d263e2016-12-25 08:05:23 +00004022/// Note that this is done even if the initializer is dependent. (This is
4023/// necessary to support partial ordering of templates using 'auto'.)
4024/// A dependent type will be produced when deducing from a dependent type.
4025///
Richard Smith30482bc2011-02-20 03:19:35 +00004026/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004027/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004028/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004029/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004030/// \param DependentDeductionDepth Set if we should permit deduction in
4031/// dependent cases. This is necessary for template partial ordering with
4032/// 'auto' template parameters. The value specified is the template
4033/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004034Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004035Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4036 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004037 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004038 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4039 if (NonPlaceholder.isInvalid())
4040 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004041 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004042 }
4043
Richard Smith87d263e2016-12-25 08:05:23 +00004044 if (!DependentDeductionDepth &&
4045 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4046 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004047 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004048 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004049 }
4050
Richard Smith87d263e2016-12-25 08:05:23 +00004051 // Find the depth of template parameter to synthesize.
4052 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4053
Richard Smith74aeef52013-04-26 16:15:35 +00004054 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4055 // Since 'decltype(auto)' can only occur at the top of the type, we
4056 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004057 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004058 if (AT->isDecltypeAuto()) {
4059 if (isa<InitListExpr>(Init)) {
4060 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4061 return DAR_FailedAlreadyDiagnosed;
4062 }
4063
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004064 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004065 if (Deduced.isNull())
4066 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004067 // FIXME: Support a non-canonical deduced type for 'auto'.
4068 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004069 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004070 if (Result.isNull())
4071 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004072 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004073 } else if (!getLangOpts().CPlusPlus) {
4074 if (isa<InitListExpr>(Init)) {
4075 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4076 return DAR_FailedAlreadyDiagnosed;
4077 }
Richard Smith74aeef52013-04-26 16:15:35 +00004078 }
4079 }
4080
Richard Smith30482bc2011-02-20 03:19:35 +00004081 SourceLocation Loc = Init->getExprLoc();
4082
4083 LocalInstantiationScope InstScope(*this);
4084
4085 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004086 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4087 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004088 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4089 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004090 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4091 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004092
Richard Smith87d263e2016-12-25 08:05:23 +00004093 QualType FuncParam =
4094 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4095 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004096 assert(!FuncParam.isNull() &&
4097 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004098
4099 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004100 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004101 Deduced.resize(1);
4102 QualType InitType = Init->getType();
4103 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004104
Richard Smith87d263e2016-12-25 08:05:23 +00004105 TemplateDeductionInfo Info(Loc, Depth);
4106
4107 // If deduction failed, don't diagnose if the initializer is dependent; it
4108 // might acquire a matching type in the instantiation.
4109 auto DeductionFailed = [&]() -> DeduceAutoResult {
4110 if (Init->isTypeDependent()) {
4111 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4112 assert(!Result.isNull() && "substituting DependentTy can't fail");
4113 return DAR_Succeeded;
4114 }
4115 return DAR_Failed;
4116 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004117
Richard Smith74801c82012-07-08 04:13:07 +00004118 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004119 if (InitList) {
4120 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004121 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4122 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004123 Info, Deduced, TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004124 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004125 }
4126 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004127 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4128 Diag(Loc, diag::err_auto_bitfield);
4129 return DAR_FailedAlreadyDiagnosed;
4130 }
4131
James Y Knight7a22b242015-08-06 20:26:32 +00004132 if (AdjustFunctionParmAndArgTypesForDeduction(
4133 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004134 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004135
James Y Knight7a22b242015-08-06 20:26:32 +00004136 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4137 FuncParam, InitType, Info, Deduced,
4138 TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004139 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004140 }
Richard Smith30482bc2011-02-20 03:19:35 +00004141
Richard Smith87d263e2016-12-25 08:05:23 +00004142 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004143 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004144 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004145
Eli Friedmane4310952012-11-06 23:56:42 +00004146 QualType DeducedType = Deduced[0].getAsType();
4147
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004148 if (InitList) {
4149 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4150 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004151 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004152 }
4153
Richard Smith061f1e22013-04-30 21:23:01 +00004154 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004155 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004156 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004157
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004158 // Check that the deduced argument type is compatible with the original
4159 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004160 if (!InitList && !Result.isNull() &&
4161 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004162 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004163 Result)) {
4164 Result = QualType();
Richard Smith87d263e2016-12-25 08:05:23 +00004165 return DeductionFailed();
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004166 }
4167
Sebastian Redl09edce02012-01-23 22:09:39 +00004168 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004169}
4170
Simon Pilgrim728134c2016-08-12 11:43:57 +00004171QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004172 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004173 if (TypeToReplaceAuto->isDependentType())
4174 TypeToReplaceAuto = QualType();
4175 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4176 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004177}
4178
Simon Pilgrim728134c2016-08-12 11:43:57 +00004179TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004180 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004181 if (TypeToReplaceAuto->isDependentType())
4182 TypeToReplaceAuto = QualType();
4183 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4184 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004185}
4186
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004187void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4188 if (isa<InitListExpr>(Init))
4189 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004190 VDecl->isInitCapture()
4191 ? diag::err_init_capture_deduction_failure_from_init_list
4192 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004193 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4194 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004195 Diag(VDecl->getLocation(),
4196 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4197 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004198 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4199 << Init->getSourceRange();
4200}
4201
Richard Smith2a7d4812013-05-04 07:00:32 +00004202bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4203 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004204 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004205
4206 if (FD->getTemplateInstantiationPattern())
4207 InstantiateFunctionDefinition(Loc, FD);
4208
Alp Toker314cc812014-01-25 16:55:45 +00004209 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004210 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4211 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4212 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4213 }
4214
4215 return StillUndeduced;
4216}
4217
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004218static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004219MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004220 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004221 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004222 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223
4224/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004225static void
4226AddImplicitObjectParameterType(ASTContext &Context,
4227 CXXMethodDecl *Method,
4228 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004229 // C++11 [temp.func.order]p3:
4230 // [...] The new parameter is of type "reference to cv A," where cv are
4231 // the cv-qualifiers of the function template (if any) and A is
4232 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004233 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004234 // The standard doesn't say explicitly, but we pick the appropriate kind of
4235 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004236 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4237 ArgTy = Context.getQualifiedType(ArgTy,
4238 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004239 if (Method->getRefQualifier() == RQ_RValue)
4240 ArgTy = Context.getRValueReferenceType(ArgTy);
4241 else
4242 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004243 ArgTypes.push_back(ArgTy);
4244}
4245
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004246/// \brief Determine whether the function template \p FT1 is at least as
4247/// specialized as \p FT2.
4248static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004249 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004250 FunctionTemplateDecl *FT1,
4251 FunctionTemplateDecl *FT2,
4252 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004253 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004254 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004256 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4257 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004259 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4260 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004261 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004262 Deduced.resize(TemplateParams->size());
4263
4264 // C++0x [temp.deduct.partial]p3:
4265 // The types used to determine the ordering depend on the context in which
4266 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004267 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004268 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004269 switch (TPOC) {
4270 case TPOC_Call: {
4271 // - In the context of a function call, the function parameter types are
4272 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004273 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4274 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004275
Eli Friedman3b5774a2012-09-19 23:27:04 +00004276 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004277 // [...] If only one of the function templates is a non-static
4278 // member, that function template is considered to have a new
4279 // first parameter inserted in its function parameter list. The
4280 // new parameter is of type "reference to cv A," where cv are
4281 // the cv-qualifiers of the function template (if any) and A is
4282 // the class of which the function template is a member.
4283 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004284 // Note that we interpret this to mean "if one of the function
4285 // templates is a non-static member and the other is a non-member";
4286 // otherwise, the ordering rules for static functions against non-static
4287 // functions don't make any sense.
4288 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004289 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4290 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004291 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004292
Richard Smithe5b52202013-09-11 00:52:39 +00004293 unsigned NumComparedArguments = NumCallArguments1;
4294
4295 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004296 // Compare 'this' from Method1 against first parameter from Method2.
4297 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4298 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004299 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004300 // Compare 'this' from Method2 against first parameter from Method1.
4301 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004302 }
4303
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004304 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004305 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004306 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004307 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregorb837ea42011-01-11 17:34:58 +00004309 // C++ [temp.func.order]p5:
4310 // The presence of unused ellipsis and default arguments has no effect on
4311 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004312 if (Args1.size() > NumComparedArguments)
4313 Args1.resize(NumComparedArguments);
4314 if (Args2.size() > NumComparedArguments)
4315 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004316 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4317 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004318 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004319 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004321 break;
4322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004324 case TPOC_Conversion:
4325 // - In the context of a call to a conversion operator, the return types
4326 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004327 if (DeduceTemplateArgumentsByTypeMatch(
4328 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4329 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004330 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004331 return false;
4332 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004334 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004335 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004336 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004337 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4338 FD2->getType(), FD1->getType(),
4339 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004340 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004341 return false;
4342 break;
4343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004345 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 // In most cases, all template parameters must have values in order for
4347 // deduction to succeed, but for partial ordering purposes a template
4348 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004349 // types being used for partial ordering. [ Note: a template parameter used
4350 // in a non-deduced context is considered used. -end note]
4351 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4352 for (; ArgIdx != NumArgs; ++ArgIdx)
4353 if (Deduced[ArgIdx].isNull())
4354 break;
4355
4356 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 // as FT2.
4359 return true;
4360 }
4361
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004362 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004363 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004364 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004365 case TPOC_Call:
4366 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4367 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004368 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004369 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004372 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004373 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4374 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004375 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004376
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004377 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004378 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004379 TemplateParams->getDepth(),
4380 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004381 break;
4382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004384 for (; ArgIdx != NumArgs; ++ArgIdx)
4385 // If this argument had no value deduced but was used in one of the types
4386 // used for partial ordering, then deduction fails.
4387 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4388 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004390 return true;
4391}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392
Douglas Gregorcef1a032011-01-16 16:03:23 +00004393/// \brief Determine whether this a function template whose parameter-type-list
4394/// ends with a function parameter pack.
4395static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4396 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4397 unsigned NumParams = Function->getNumParams();
4398 if (NumParams == 0)
4399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400
Douglas Gregorcef1a032011-01-16 16:03:23 +00004401 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4402 if (!Last->isParameterPack())
4403 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregorcef1a032011-01-16 16:03:23 +00004405 // Make sure that no previous parameter is a parameter pack.
4406 while (--NumParams > 0) {
4407 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4408 return false;
4409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregorcef1a032011-01-16 16:03:23 +00004411 return true;
4412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregorbe999392009-09-15 16:23:51 +00004414/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004415/// to the rules of function template partial ordering (C++ [temp.func.order]).
4416///
4417/// \param FT1 the first function template
4418///
4419/// \param FT2 the second function template
4420///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004421/// \param TPOC the context in which we are performing partial ordering of
4422/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004423///
Richard Smithe5b52202013-09-11 00:52:39 +00004424/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4425/// only when \c TPOC is \c TPOC_Call.
4426///
4427/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4428/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004429///
Douglas Gregorbe999392009-09-15 16:23:51 +00004430/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004431/// template is more specialized, returns NULL.
4432FunctionTemplateDecl *
4433Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4434 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004435 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004436 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004437 unsigned NumCallArguments1,
4438 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004440 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004442 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004444 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004445 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004447 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004448 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004449
Douglas Gregorcef1a032011-01-16 16:03:23 +00004450 // FIXME: This mimics what GCC implements, but doesn't match up with the
4451 // proposed resolution for core issue 692. This area needs to be sorted out,
4452 // but for now we attempt to maintain compatibility.
4453 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4454 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4455 if (Variadic1 != Variadic2)
4456 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Craig Topperc3ec1492014-05-26 06:22:03 +00004458 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004459}
Douglas Gregor9b146582009-07-08 20:55:45 +00004460
Douglas Gregor450f00842009-09-25 18:43:00 +00004461/// \brief Determine if the two templates are equivalent.
4462static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4463 if (T1 == T2)
4464 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465
Douglas Gregor450f00842009-09-25 18:43:00 +00004466 if (!T1 || !T2)
4467 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregor450f00842009-09-25 18:43:00 +00004469 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4470}
4471
4472/// \brief Retrieve the most specialized of the given function template
4473/// specializations.
4474///
John McCall58cc69d2010-01-27 01:50:18 +00004475/// \param SpecBegin the start iterator of the function template
4476/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004477///
John McCall58cc69d2010-01-27 01:50:18 +00004478/// \param SpecEnd the end iterator of the function template
4479/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004480///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004482/// diagnostic should occur.
4483///
4484/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4485/// no matching candidates.
4486///
4487/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4488/// occurs.
4489///
4490/// \param CandidateDiag partial diagnostic used for each function template
4491/// specialization that is a candidate in the ambiguous ordering. One parameter
4492/// in this diagnostic should be unbound, which will correspond to the string
4493/// describing the template arguments for the function template specialization.
4494///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004495/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004496/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004497UnresolvedSetIterator Sema::getMostSpecialized(
4498 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4499 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004500 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4501 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4502 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004503 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004504 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004505 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004506 FailedCandidates.NoteCandidates(*this, Loc);
4507 }
John McCall58cc69d2010-01-27 01:50:18 +00004508 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
4511 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004512 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513
Douglas Gregor450f00842009-09-25 18:43:00 +00004514 // Find the function template that is better than all of the templates it
4515 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004516 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004518 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004519 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004520 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4521 FunctionTemplateDecl *Challenger
4522 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004523 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004524 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004525 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004526 Challenger)) {
4527 Best = I;
4528 BestTemplate = Challenger;
4529 }
4530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531
Douglas Gregor450f00842009-09-25 18:43:00 +00004532 // Make sure that the "best" function template is more specialized than all
4533 // of the others.
4534 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004535 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4536 FunctionTemplateDecl *Challenger
4537 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004538 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004540 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004541 BestTemplate)) {
4542 Ambiguous = true;
4543 break;
4544 }
4545 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
Douglas Gregor450f00842009-09-25 18:43:00 +00004547 if (!Ambiguous) {
4548 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004549 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
Douglas Gregor450f00842009-09-25 18:43:00 +00004552 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004553 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004554 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555
Richard Smithb875c432013-05-04 01:51:08 +00004556 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004557 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4558 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004559 const auto *FD = cast<FunctionDecl>(*I);
4560 PD << FD << getTemplateArgumentBindingsText(
4561 FD->getPrimaryTemplate()->getTemplateParameters(),
4562 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004563 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004564 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004565 Diag((*I)->getLocation(), PD);
4566 }
Richard Smithb875c432013-05-04 01:51:08 +00004567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
John McCall58cc69d2010-01-27 01:50:18 +00004569 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004570}
4571
Richard Smith0da6dc42016-12-24 16:40:51 +00004572/// Determine whether one partial specialization, P1, is at least as
4573/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004574///
Richard Smith0da6dc42016-12-24 16:40:51 +00004575/// \param PartialSpecializationDecl The kind of P2, which must be a
4576/// {Class,Var}TemplatePartialSpecializationDecl.
4577/// \param T1 The injected-class-name of P1 (faked for a variable template).
4578/// \param T2 The injected-class-name of P2 (faked for a variable template).
4579/// \param Loc The location at which the comparison is required.
4580template<typename PartialSpecializationDecl>
4581static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
4582 PartialSpecializationDecl *P2,
4583 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004584 // C++ [temp.class.order]p1:
4585 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004586 // specialized as the second if, given the following rewrite to two
4587 // function templates, the first function template is at least as
4588 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004589 // templates (14.6.6.2):
4590 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591 // first partial specialization and has a single function parameter
4592 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004593 // arguments of the first partial specialization, and
4594 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595 // second partial specialization and has a single function parameter
4596 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004597 // arguments of the second partial specialization.
4598 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004599 // Rather than synthesize function templates, we merely perform the
4600 // equivalent partial ordering by performing deduction directly on
4601 // the template arguments of the class template partial
4602 // specializations. This computation is slightly simpler than the
4603 // general problem of function template partial ordering, because
4604 // class template partial specializations are more constrained. We
4605 // know that every template parameter is deducible from the class
4606 // template partial specialization's template arguments, for
4607 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004608 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004609 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004610
Richard Smith0da6dc42016-12-24 16:40:51 +00004611 // Determine whether P1 is at least as specialized as P2.
4612 Deduced.resize(P2->getTemplateParameters()->size());
4613 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4614 T2, T1, Info, Deduced, TDF_None,
4615 /*PartialOrdering=*/true))
4616 return false;
4617
4618 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4619 Deduced.end());
4620 Sema::InstantiatingTemplate Inst(S, Loc, P2, DeducedArgs, Info);
4621 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4622 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004623 S, P2, /*PartialOrdering=*/true,
4624 TemplateArgumentList(TemplateArgumentList::OnStack,
4625 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004626 Deduced, Info))
4627 return false;
4628
4629 return true;
4630}
4631
4632/// \brief Returns the more specialized class template partial specialization
4633/// according to the rules of partial ordering of class template partial
4634/// specializations (C++ [temp.class.order]).
4635///
4636/// \param PS1 the first class template partial specialization
4637///
4638/// \param PS2 the second class template partial specialization
4639///
4640/// \returns the more specialized class template partial specialization. If
4641/// neither partial specialization is more specialized, returns NULL.
4642ClassTemplatePartialSpecializationDecl *
4643Sema::getMoreSpecializedPartialSpecialization(
4644 ClassTemplatePartialSpecializationDecl *PS1,
4645 ClassTemplatePartialSpecializationDecl *PS2,
4646 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004647 QualType PT1 = PS1->getInjectedSpecializationType();
4648 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Richard Smith0da6dc42016-12-24 16:40:51 +00004650 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4651 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004652
4653 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004654 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004655
4656 return Better1 ? PS1 : PS2;
4657}
4658
Larisse Voufo39a1e502013-08-06 01:03:05 +00004659VarTemplatePartialSpecializationDecl *
4660Sema::getMoreSpecializedPartialSpecialization(
4661 VarTemplatePartialSpecializationDecl *PS1,
4662 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004663 // Pretend the variable template specializations are class template
4664 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004665 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004666 "the partial specializations being compared should specialize"
4667 " the same template.");
4668 TemplateName Name(PS1->getSpecializedTemplate());
4669 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4670 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004671 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004672 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004673 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004674
Richard Smith0da6dc42016-12-24 16:40:51 +00004675 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4676 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677
Douglas Gregorbe999392009-09-15 16:23:51 +00004678 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004679 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
Richard Smith0da6dc42016-12-24 16:40:51 +00004681 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004682}
4683
Mike Stump11289f42009-09-09 15:08:12 +00004684static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004685MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004686 const TemplateArgument &TemplateArg,
4687 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004688 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004689 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004690
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004691/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004692/// expression.
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 Expr *E,
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 Gregore8e9dd62011-01-03 17:17:50 +00004699 // We can deduce from a pack expansion.
4700 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4701 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Richard Smith34349002012-07-09 03:07:20 +00004703 // Skip through any implicit casts we added while type-checking, and any
4704 // substitutions performed by template alias expansion.
4705 while (1) {
4706 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4707 E = ICE->getSubExpr();
4708 else if (const SubstNonTypeTemplateParmExpr *Subst =
4709 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4710 E = Subst->getReplacement();
4711 else
4712 break;
4713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004714
4715 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004716 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004717 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004718 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004719 return;
4720
Mike Stump11289f42009-09-09 15:08:12 +00004721 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004722 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4723 if (!NTTP)
4724 return;
4725
Douglas Gregor21610382009-10-29 00:04:11 +00004726 if (NTTP->getDepth() == Depth)
4727 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004728
4729 // In C++1z mode, additional arguments may be deduced from the type of a
4730 // non-type argument.
4731 if (Ctx.getLangOpts().CPlusPlus1z)
4732 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004733}
4734
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004735/// \brief Mark the template parameters that are used by the given
4736/// nested name specifier.
4737static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004738MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004739 NestedNameSpecifier *NNS,
4740 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004741 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004742 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004743 if (!NNS)
4744 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004746 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004747 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004748 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004749 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004750}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752/// \brief Mark the template parameters that are used by the given
4753/// template name.
4754static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004755MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004756 TemplateName Name,
4757 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004758 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004759 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004760 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4761 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004762 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4763 if (TTP->getDepth() == Depth)
4764 Used[TTP->getIndex()] = true;
4765 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004766 return;
4767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004769 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004770 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004771 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004772 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004773 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004774 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004775}
4776
4777/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004778/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004779static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004780MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004781 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004782 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004783 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004784 if (T.isNull())
4785 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786
Douglas Gregor91772d12009-06-13 00:26:55 +00004787 // Non-dependent types have nothing deducible
4788 if (!T->isDependentType())
4789 return;
4790
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004791 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004792 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004793 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004794 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004795 cast<PointerType>(T)->getPointeeType(),
4796 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004797 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004798 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004799 break;
4800
4801 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004802 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004803 cast<BlockPointerType>(T)->getPointeeType(),
4804 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004805 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004807 break;
4808
4809 case Type::LValueReference:
4810 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004811 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004812 cast<ReferenceType>(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::MemberPointer: {
4819 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004820 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004821 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004822 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004823 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004824 break;
4825 }
4826
4827 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004828 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004829 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004830 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004831 // Fall through to check the element type
4832
4833 case Type::ConstantArray:
4834 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004835 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004836 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004837 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004838 break;
4839
4840 case Type::Vector:
4841 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004842 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004843 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004844 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004845 break;
4846
Douglas Gregor758a8692009-06-17 21:51:59 +00004847 case Type::DependentSizedExtVector: {
4848 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004849 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004850 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004851 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004852 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004853 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004854 break;
4855 }
4856
Douglas Gregor91772d12009-06-13 00:26:55 +00004857 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004858 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004859 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4860 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004861 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4862 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004863 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004864 break;
4865 }
4866
Douglas Gregor21610382009-10-29 00:04:11 +00004867 case Type::TemplateTypeParm: {
4868 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4869 if (TTP->getDepth() == Depth)
4870 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004871 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004872 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004873
Douglas Gregorfb322d82011-01-14 05:11:40 +00004874 case Type::SubstTemplateTypeParmPack: {
4875 const SubstTemplateTypeParmPackType *Subst
4876 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004877 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004878 QualType(Subst->getReplacedParameter(), 0),
4879 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004880 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004881 OnlyDeduced, Depth, Used);
4882 break;
4883 }
4884
John McCall2408e322010-04-27 00:57:59 +00004885 case Type::InjectedClassName:
4886 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4887 // fall through
4888
Douglas Gregor91772d12009-06-13 00:26:55 +00004889 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004890 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004891 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004892 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004893 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894
Douglas Gregord0ad2942010-12-23 01:24:45 +00004895 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004896 // If the template argument list of P contains a pack expansion that is
4897 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004898 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004900 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004901 break;
4902
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004903 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004904 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004905 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004906 break;
4907 }
4908
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004909 case Type::Complex:
4910 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004911 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004912 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004913 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004914 break;
4915
Eli Friedman0dfb8892011-10-06 23:00:33 +00004916 case Type::Atomic:
4917 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004918 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004919 cast<AtomicType>(T)->getValueType(),
4920 OnlyDeduced, Depth, Used);
4921 break;
4922
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004923 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004924 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004925 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004926 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004927 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004928 break;
4929
John McCallc392f372010-06-11 00:33:02 +00004930 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004931 // C++14 [temp.deduct.type]p5:
4932 // The non-deduced contexts are:
4933 // -- The nested-name-specifier of a type that was specified using a
4934 // qualified-id
4935 //
4936 // C++14 [temp.deduct.type]p6:
4937 // When a type name is specified in a way that includes a non-deduced
4938 // context, all of the types that comprise that type name are also
4939 // non-deduced.
4940 if (OnlyDeduced)
4941 break;
4942
John McCallc392f372010-06-11 00:33:02 +00004943 const DependentTemplateSpecializationType *Spec
4944 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945
Richard Smith50d5b972015-12-30 20:56:05 +00004946 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4947 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004948
John McCallc392f372010-06-11 00:33:02 +00004949 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004950 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004951 Used);
4952 break;
4953 }
4954
John McCallbd8d9bd2010-03-01 23:49:17 +00004955 case Type::TypeOf:
4956 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004957 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004958 cast<TypeOfType>(T)->getUnderlyingType(),
4959 OnlyDeduced, Depth, Used);
4960 break;
4961
4962 case Type::TypeOfExpr:
4963 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004964 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004965 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4966 OnlyDeduced, Depth, Used);
4967 break;
4968
4969 case Type::Decltype:
4970 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004971 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004972 cast<DecltypeType>(T)->getUnderlyingExpr(),
4973 OnlyDeduced, Depth, Used);
4974 break;
4975
Alexis Hunte852b102011-05-24 22:41:36 +00004976 case Type::UnaryTransform:
4977 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004978 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00004979 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00004980 OnlyDeduced, Depth, Used);
4981 break;
4982
Douglas Gregord2fa7662010-12-20 02:24:11 +00004983 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004984 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004985 cast<PackExpansionType>(T)->getPattern(),
4986 OnlyDeduced, Depth, Used);
4987 break;
4988
Richard Smith30482bc2011-02-20 03:19:35 +00004989 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004990 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004991 cast<AutoType>(T)->getDeducedType(),
4992 OnlyDeduced, Depth, Used);
4993
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004994 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004995 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004996 case Type::VariableArray:
4997 case Type::FunctionNoProto:
4998 case Type::Record:
4999 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005000 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005001 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005002 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005003 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005004 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005005#define TYPE(Class, Base)
5006#define ABSTRACT_TYPE(Class, Base)
5007#define DEPENDENT_TYPE(Class, Base)
5008#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5009#include "clang/AST/TypeNodes.def"
5010 break;
5011 }
5012}
5013
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005014/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005015/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005016static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005017MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005018 const TemplateArgument &TemplateArg,
5019 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005020 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005021 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005022 switch (TemplateArg.getKind()) {
5023 case TemplateArgument::Null:
5024 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005025 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005026 break;
Mike Stump11289f42009-09-09 15:08:12 +00005027
Eli Friedmanb826a002012-09-26 02:36:12 +00005028 case TemplateArgument::NullPtr:
5029 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5030 Depth, Used);
5031 break;
5032
Douglas Gregor91772d12009-06-13 00:26:55 +00005033 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005034 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005035 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005036 break;
5037
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005038 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005039 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005040 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005042 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005043 break;
5044
5045 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005046 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005047 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005048 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005049
Anders Carlssonbc343912009-06-15 17:04:53 +00005050 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005051 for (const auto &P : TemplateArg.pack_elements())
5052 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005053 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005054 }
5055}
5056
James Dennett41725122012-06-22 10:16:05 +00005057/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005058/// template argument list.
5059///
5060/// \param TemplateArgs the template argument list from which template
5061/// parameters will be deduced.
5062///
James Dennett41725122012-06-22 10:16:05 +00005063/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005064/// to indicate when the corresponding template parameter will be
5065/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005066void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005067Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005068 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005069 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005070 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071 // If the template argument list of P contains a pack expansion that is not
5072 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005073 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005074 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005075 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005076 return;
5077
Douglas Gregor91772d12009-06-13 00:26:55 +00005078 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005079 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005080 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005081}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005082
5083/// \brief Marks all of the template parameters that will be deduced by a
5084/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005085void Sema::MarkDeducedTemplateParameters(
5086 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5087 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005089 = FunctionTemplate->getTemplateParameters();
5090 Deduced.clear();
5091 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregorce23bae2009-09-18 23:21:38 +00005093 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5094 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005095 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005096 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005097}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005098
5099bool hasDeducibleTemplateParameters(Sema &S,
5100 FunctionTemplateDecl *FunctionTemplate,
5101 QualType T) {
5102 if (!T->isDependentType())
5103 return false;
5104
5105 TemplateParameterList *TemplateParams
5106 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005107 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005108 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005109 Deduced);
5110
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005111 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005112}