blob: 6c90b5c2266de77a38d1330dada571fb5cc91ecc [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
Richard Smith539e8e32017-01-04 01:48:55 +0000291 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000293 XAEnd = X.pack_end(),
294 YA = Y.pack_begin();
295 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000296 TemplateArgument Merged = checkDeducedTemplateArguments(
297 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
298 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
299 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000301 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000303
Richard Smith539e8e32017-01-04 01:48:55 +0000304 return DeducedTemplateArgument(
305 TemplateArgument::CreatePackCopy(Context, NewPack),
306 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308
David Blaikiee4d798f2012-01-20 21:50:17 +0000309 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000310}
311
Mike Stump11289f42009-09-09 15:08:12 +0000312/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000313/// as the given deduced template argument. All non-type template parameter
314/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000315static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000316 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000317 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
318 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000319 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000320 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
321 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000322
Richard Smith5d102892016-12-27 03:59:58 +0000323 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
324 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000325 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000326 Info.Param = NTTP;
327 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000328 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000329 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000332 Deduced[NTTP->getIndex()] = Result;
Richard Smithd92eddf2016-12-27 06:14:37 +0000333 if (!S.getLangOpts().CPlusPlus1z)
334 return Sema::TDK_Success;
335
336 // FIXME: It's not clear how deduction of a parameter of reference
337 // type from an argument (of non-reference type) should be performed.
338 // For now, we just remove reference types from both sides and let
339 // the final check for matching types sort out the mess.
340 return DeduceTemplateArgumentsByTypeMatch(
341 S, TemplateParams, NTTP->getType().getNonReferenceType(),
342 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
343 /*PartialOrdering=*/false,
344 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000345}
346
Mike Stump11289f42009-09-09 15:08:12 +0000347/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000348/// from the given integral constant.
349static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
350 Sema &S, TemplateParameterList *TemplateParams,
351 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
352 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
353 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
354 return DeduceNonTypeTemplateArgument(
355 S, TemplateParams, NTTP,
356 DeducedTemplateArgument(S.Context, Value, ValueType,
357 DeducedFromArrayBound),
358 ValueType, Info, Deduced);
359}
360
361/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000362/// from the given null pointer template argument type.
363static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000364 Sema &S, TemplateParameterList *TemplateParams,
365 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000366 TemplateDeductionInfo &Info,
367 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
368 Expr *Value =
369 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
370 S.Context.NullPtrTy, NTTP->getLocation()),
371 NullPtrType, CK_NullToPointer)
372 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000373 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
374 DeducedTemplateArgument(Value),
375 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000376}
377
378/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000379/// from the given type- or value-dependent expression.
380///
381/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000382static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
383 Sema &S, TemplateParameterList *TemplateParams,
384 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
385 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000386 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
387 DeducedTemplateArgument(Value),
388 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000389}
390
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000391/// \brief Deduce the value of the given non-type template parameter
392/// from the given declaration.
393///
394/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000395static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
396 Sema &S, TemplateParameterList *TemplateParams,
397 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
398 TemplateDeductionInfo &Info,
399 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000400 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000401 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000402 return DeduceNonTypeTemplateArgument(
403 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000404}
405
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000406static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000407DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000408 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000409 TemplateName Param,
410 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000411 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000412 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000413 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000414 if (!ParamDecl) {
415 // The parameter type is dependent and is not a template template parameter,
416 // so there is nothing that we can deduce.
417 return Sema::TDK_Success;
418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419
Douglas Gregoradee3e32009-11-11 23:06:43 +0000420 if (TemplateTemplateParmDecl *TempParam
421 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000422 // If we're not deducing at this depth, there's nothing to deduce.
423 if (TempParam->getDepth() != Info.getDeducedDepth())
424 return Sema::TDK_Success;
425
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000426 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000428 Deduced[TempParam->getIndex()],
429 NewDeduced);
430 if (Result.isNull()) {
431 Info.Param = TempParam;
432 Info.FirstArg = Deduced[TempParam->getIndex()];
433 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000437 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000439 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
Douglas Gregoradee3e32009-11-11 23:06:43 +0000441 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000442 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000443 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000444
Douglas Gregoradee3e32009-11-11 23:06:43 +0000445 // Mismatch of non-dependent template parameter to argument.
446 Info.FirstArg = TemplateArgument(Param);
447 Info.SecondArg = TemplateArgument(Arg);
448 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000449}
450
Mike Stump11289f42009-09-09 15:08:12 +0000451/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000452/// type (which is a template-id) with the template argument type.
453///
Chandler Carruthc1263112010-02-07 21:33:28 +0000454/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000455///
456/// \param TemplateParams the template parameters that we are deducing
457///
458/// \param Param the parameter type
459///
460/// \param Arg the argument type
461///
462/// \param Info information about the template argument deduction itself
463///
464/// \param Deduced the deduced template arguments
465///
466/// \returns the result of template argument deduction so far. Note that a
467/// "success" result means that template argument deduction has not yet failed,
468/// but it may still fail, later, for other reasons.
469static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000470DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000471 TemplateParameterList *TemplateParams,
472 const TemplateSpecializationType *Param,
473 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000474 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000475 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000476 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000477
Douglas Gregore81f3e72009-07-07 23:09:34 +0000478 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000479 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000480 = dyn_cast<TemplateSpecializationType>(Arg)) {
481 // Perform template argument deduction for the template name.
482 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000483 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000484 Param->getTemplateName(),
485 SpecArg->getTemplateName(),
486 Info, Deduced))
487 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Mike Stump11289f42009-09-09 15:08:12 +0000489
Douglas Gregore81f3e72009-07-07 23:09:34 +0000490 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000491 // argument. Ignore any missing/extra arguments, since they could be
492 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000493 return DeduceTemplateArguments(S, TemplateParams,
494 Param->template_arguments(),
495 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000496 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregore81f3e72009-07-07 23:09:34 +0000499 // If the argument type is a class template specialization, we
500 // perform template argument deduction using its template
501 // arguments.
502 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000503 if (!RecordArg) {
504 Info.FirstArg = TemplateArgument(QualType(Param, 0));
505 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000507 }
Mike Stump11289f42009-09-09 15:08:12 +0000508
509 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000511 if (!SpecArg) {
512 Info.FirstArg = TemplateArgument(QualType(Param, 0));
513 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Douglas Gregore81f3e72009-07-07 23:09:34 +0000517 // Perform template argument deduction for the template name.
518 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000519 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000520 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000521 Param->getTemplateName(),
522 TemplateName(SpecArg->getSpecializedTemplate()),
523 Info, Deduced))
524 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregor7baabef2010-12-22 18:17:10 +0000526 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000527 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
528 SpecArg->getTemplateArgs().asArray(), Info,
529 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000530}
531
John McCall08569062010-08-28 22:14:41 +0000532/// \brief Determines whether the given type is an opaque type that
533/// might be more qualified when instantiated.
534static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
535 switch (T->getTypeClass()) {
536 case Type::TypeOfExpr:
537 case Type::TypeOf:
538 case Type::DependentName:
539 case Type::Decltype:
540 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000541 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000542 return true;
543
544 case Type::ConstantArray:
545 case Type::IncompleteArray:
546 case Type::VariableArray:
547 case Type::DependentSizedArray:
548 return IsPossiblyOpaquelyQualifiedType(
549 cast<ArrayType>(T)->getElementType());
550
551 default:
552 return false;
553 }
554}
555
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000556/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000558getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561
Douglas Gregor5499af42011-01-05 23:12:31 +0000562 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
563 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor5499af42011-01-05 23:12:31 +0000565 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
566 return std::make_pair(TTP->getDepth(), TTP->getIndex());
567}
568
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000569/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000571getDepthAndIndex(UnexpandedParameterPack UPP) {
572 if (const TemplateTypeParmType *TTP
573 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
574 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000576 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
577}
578
Douglas Gregor5499af42011-01-05 23:12:31 +0000579/// \brief Helper function to build a TemplateParameter when we don't
580/// know its type statically.
581static TemplateParameter makeTemplateParameter(Decl *D) {
582 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
583 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000584 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000585 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Douglas Gregor5499af42011-01-05 23:12:31 +0000587 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
588}
589
Richard Smith0a80d572014-05-29 01:12:14 +0000590/// A pack that we're currently deducing.
591struct clang::DeducedPack {
592 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000593
Richard Smith0a80d572014-05-29 01:12:14 +0000594 // The index of the pack.
595 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596
Richard Smith0a80d572014-05-29 01:12:14 +0000597 // The old value of the pack before we started deducing it.
598 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000599
Richard Smith0a80d572014-05-29 01:12:14 +0000600 // A deferred value of this pack from an inner deduction, that couldn't be
601 // deduced because this deduction hadn't happened yet.
602 DeducedTemplateArgument DeferredDeduction;
603
604 // The new value of the pack.
605 SmallVector<DeducedTemplateArgument, 4> New;
606
607 // The outer deduction for this pack, if any.
608 DeducedPack *Outer;
609};
610
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000611namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000612/// A scope in which we're performing pack deduction.
613class PackDeductionScope {
614public:
615 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
616 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
617 TemplateDeductionInfo &Info, TemplateArgument Pattern)
618 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
619 // Compute the set of template parameter indices that correspond to
620 // parameter packs expanded by the pack expansion.
621 {
622 llvm::SmallBitVector SawIndices(TemplateParams->size());
623 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
624 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
625 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
626 unsigned Depth, Index;
627 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000628 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000629 SawIndices[Index] = true;
630
631 // Save the deduced template argument for the parameter pack expanded
632 // by this pack expansion, then clear out the deduction.
633 DeducedPack Pack(Index);
634 Pack.Saved = Deduced[Index];
635 Deduced[Index] = TemplateArgument();
636
637 Packs.push_back(Pack);
638 }
639 }
640 }
641 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
642
643 for (auto &Pack : Packs) {
644 if (Info.PendingDeducedPacks.size() > Pack.Index)
645 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
646 else
647 Info.PendingDeducedPacks.resize(Pack.Index + 1);
648 Info.PendingDeducedPacks[Pack.Index] = &Pack;
649
650 if (S.CurrentInstantiationScope) {
651 // If the template argument pack was explicitly specified, add that to
652 // the set of deduced arguments.
653 const TemplateArgument *ExplicitArgs;
654 unsigned NumExplicitArgs;
655 NamedDecl *PartiallySubstitutedPack =
656 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
657 &ExplicitArgs, &NumExplicitArgs);
658 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000659 getDepthAndIndex(PartiallySubstitutedPack) ==
660 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000661 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
662 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000663 }
664 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000665
Richard Smith0a80d572014-05-29 01:12:14 +0000666 ~PackDeductionScope() {
667 for (auto &Pack : Packs)
668 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
Richard Smith0a80d572014-05-29 01:12:14 +0000671 /// Move to deducing the next element in each pack that is being deduced.
672 void nextPackElement() {
673 // Capture the deduced template arguments for each parameter pack expanded
674 // by this pack expansion, add them to the list of arguments we've deduced
675 // for that pack, then clear out the deduced argument.
676 for (auto &Pack : Packs) {
677 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000678 if (!Pack.New.empty() || !DeducedArg.isNull()) {
679 while (Pack.New.size() < PackElements)
680 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith0a80d572014-05-29 01:12:14 +0000681 Pack.New.push_back(DeducedArg);
682 DeducedArg = DeducedTemplateArgument();
683 }
684 }
Richard Smith539e8e32017-01-04 01:48:55 +0000685 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000686 }
687
688 /// \brief Finish template argument deduction for a set of argument packs,
689 /// producing the argument packs and checking for consistency with prior
690 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000691 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000692 // Build argument packs for each of the parameter packs expanded by this
693 // pack expansion.
694 for (auto &Pack : Packs) {
695 // Put back the old value for this pack.
696 Deduced[Pack.Index] = Pack.Saved;
697
698 // Build or find a new value for this pack.
699 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000700 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000701 if (Pack.DeferredDeduction.isNull()) {
702 // We were not able to deduce anything for this parameter pack
703 // (because it only appeared in non-deduced contexts), so just
704 // restore the saved argument pack.
705 continue;
706 }
707
708 NewPack = Pack.DeferredDeduction;
709 Pack.DeferredDeduction = TemplateArgument();
710 } else if (Pack.New.empty()) {
711 // If we deduced an empty argument pack, create it now.
712 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
713 } else {
714 TemplateArgument *ArgumentPack =
715 new (S.Context) TemplateArgument[Pack.New.size()];
716 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
717 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000718 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000719 Pack.New[0].wasDeducedFromArrayBound());
720 }
721
722 // Pick where we're going to put the merged pack.
723 DeducedTemplateArgument *Loc;
724 if (Pack.Outer) {
725 if (Pack.Outer->DeferredDeduction.isNull()) {
726 // Defer checking this pack until we have a complete pack to compare
727 // it against.
728 Pack.Outer->DeferredDeduction = NewPack;
729 continue;
730 }
731 Loc = &Pack.Outer->DeferredDeduction;
732 } else {
733 Loc = &Deduced[Pack.Index];
734 }
735
736 // Check the new pack matches any previous value.
737 DeducedTemplateArgument OldPack = *Loc;
738 DeducedTemplateArgument Result =
739 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
740
741 // If we deferred a deduction of this pack, check that one now too.
742 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
743 OldPack = Result;
744 NewPack = Pack.DeferredDeduction;
745 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
746 }
747
748 if (Result.isNull()) {
749 Info.Param =
750 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
751 Info.FirstArg = OldPack;
752 Info.SecondArg = NewPack;
753 return Sema::TDK_Inconsistent;
754 }
755
756 *Loc = Result;
757 }
758
759 return Sema::TDK_Success;
760 }
761
762private:
763 Sema &S;
764 TemplateParameterList *TemplateParams;
765 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
766 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000767 unsigned PackElements = 0;
Richard Smith0a80d572014-05-29 01:12:14 +0000768
769 SmallVector<DeducedPack, 2> Packs;
770};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000771} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000772
Douglas Gregor5499af42011-01-05 23:12:31 +0000773/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774/// types to the list of argument types, as in the parameter-type-lists of
775/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000776///
777/// \param S The semantic analysis object within which we are deducing
778///
779/// \param TemplateParams The template parameters that we are deducing
780///
781/// \param Params The list of parameter types
782///
783/// \param NumParams The number of types in \c Params
784///
785/// \param Args The list of argument types
786///
787/// \param NumArgs The number of types in \c Args
788///
789/// \param Info information about the template argument deduction itself
790///
791/// \param Deduced the deduced template arguments
792///
793/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
794/// how template argument deduction is performed.
795///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000796/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000798/// (C++0x [temp.deduct.partial]).
799///
Douglas Gregor5499af42011-01-05 23:12:31 +0000800/// \returns the result of template argument deduction so far. Note that a
801/// "success" result means that template argument deduction has not yet failed,
802/// but it may still fail, later, for other reasons.
803static Sema::TemplateDeductionResult
804DeduceTemplateArguments(Sema &S,
805 TemplateParameterList *TemplateParams,
806 const QualType *Params, unsigned NumParams,
807 const QualType *Args, unsigned NumArgs,
808 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000809 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000810 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000811 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000812 // Fast-path check to see if we have too many/too few arguments.
813 if (NumParams != NumArgs &&
814 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
815 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000816 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Douglas Gregor5499af42011-01-05 23:12:31 +0000818 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 // Similarly, if P has a form that contains (T), then each parameter type
820 // Pi of the respective parameter-type- list of P is compared with the
821 // corresponding parameter type Ai of the corresponding parameter-type-list
822 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000823 unsigned ArgIdx = 0, ParamIdx = 0;
824 for (; ParamIdx != NumParams; ++ParamIdx) {
825 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000827 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
828 if (!Expansion) {
829 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
Douglas Gregor5499af42011-01-05 23:12:31 +0000831 // Make sure we have an argument.
832 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000833 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000835 if (isa<PackExpansionType>(Args[ArgIdx])) {
836 // C++0x [temp.deduct.type]p22:
837 // If the original function parameter associated with A is a function
838 // parameter pack and the function parameter associated with P is not
839 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000840 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000844 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
845 Params[ParamIdx], Args[ArgIdx],
846 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000847 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Douglas Gregor5499af42011-01-05 23:12:31 +0000850 ++ArgIdx;
851 continue;
852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000854 // C++0x [temp.deduct.type]p5:
855 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000857 // parameter-declaration-clause.
858 if (ParamIdx + 1 < NumParams)
859 return Sema::TDK_Success;
860
Douglas Gregor5499af42011-01-05 23:12:31 +0000861 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000862 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000863 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000864 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000865 // comparison deduces template arguments for subsequent positions in the
866 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000869 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870
Douglas Gregor5499af42011-01-05 23:12:31 +0000871 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000872 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000873 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000874 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
875 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000876 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000877 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Richard Smith0a80d572014-05-29 01:12:14 +0000879 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Douglas Gregor5499af42011-01-05 23:12:31 +0000882 // Build argument packs for each of the parameter packs expanded by this
883 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000884 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887
Douglas Gregor5499af42011-01-05 23:12:31 +0000888 // Make sure we don't have any extra arguments.
889 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000890 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
Douglas Gregor5499af42011-01-05 23:12:31 +0000892 return Sema::TDK_Success;
893}
894
Douglas Gregor1d684c22011-04-28 00:56:09 +0000895/// \brief Determine whether the parameter has qualifiers that are either
896/// inconsistent with or a superset of the argument's qualifiers.
897static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
898 QualType ArgType) {
899 Qualifiers ParamQs = ParamType.getQualifiers();
900 Qualifiers ArgQs = ArgType.getQualifiers();
901
902 if (ParamQs == ArgQs)
903 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000904
Douglas Gregor1d684c22011-04-28 00:56:09 +0000905 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000906 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000907 ParamQs.hasObjCGCAttr())
908 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000909
Douglas Gregor1d684c22011-04-28 00:56:09 +0000910 // Mismatched (but not missing) address spaces.
911 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
912 ParamQs.hasAddressSpace())
913 return true;
914
John McCall31168b02011-06-15 23:02:42 +0000915 // Mismatched (but not missing) Objective-C lifetime qualifiers.
916 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
917 ParamQs.hasObjCLifetime())
918 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000919
Douglas Gregor1d684c22011-04-28 00:56:09 +0000920 // CVR qualifier superset.
921 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
922 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
923 == ParamQs.getCVRQualifiers());
924}
925
Douglas Gregor19a41f12013-04-17 08:45:07 +0000926/// \brief Compare types for equality with respect to possibly compatible
927/// function types (noreturn adjustment, implicit calling conventions). If any
928/// of parameter and argument is not a function, just perform type comparison.
929///
930/// \param Param the template parameter type.
931///
932/// \param Arg the argument type.
933bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
934 CanQualType Arg) {
935 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
936 *ArgFunction = Arg->getAs<FunctionType>();
937
938 // Just compare if not functions.
939 if (!ParamFunction || !ArgFunction)
940 return Param == Arg;
941
Richard Smith3c4f8d22016-10-16 17:54:23 +0000942 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000943 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000944 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000945 return Arg == Context.getCanonicalType(AdjustedParam);
946
947 // FIXME: Compatible calling conventions.
948
949 return Param == Arg;
950}
951
Douglas Gregorcceb9752009-06-26 18:27:22 +0000952/// \brief Deduce the template arguments by comparing the parameter type and
953/// the argument type (C++ [temp.deduct.type]).
954///
Chandler Carruthc1263112010-02-07 21:33:28 +0000955/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000956///
957/// \param TemplateParams the template parameters that we are deducing
958///
959/// \param ParamIn the parameter type
960///
961/// \param ArgIn the argument type
962///
963/// \param Info information about the template argument deduction itself
964///
965/// \param Deduced the deduced template arguments
966///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000967/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000968/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000969///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000970/// \param PartialOrdering Whether we're performing template argument deduction
971/// in the context of partial ordering (C++0x [temp.deduct.partial]).
972///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000973/// \returns the result of template argument deduction so far. Note that a
974/// "success" result means that template argument deduction has not yet failed,
975/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000976static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000977DeduceTemplateArgumentsByTypeMatch(Sema &S,
978 TemplateParameterList *TemplateParams,
979 QualType ParamIn, QualType ArgIn,
980 TemplateDeductionInfo &Info,
981 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
982 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000983 bool PartialOrdering,
984 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000985 // We only want to look at the canonical types, since typedefs and
986 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000987 QualType Param = S.Context.getCanonicalType(ParamIn);
988 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000989
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000990 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000992 if (const PackExpansionType *ArgExpansion
993 = dyn_cast<PackExpansionType>(Arg))
994 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
Douglas Gregorb837ea42011-01-11 17:34:58 +0000996 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000997 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000998 // Before the partial ordering is done, certain transformations are
999 // performed on the types used for partial ordering:
1000 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001001 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1002 if (ParamRef)
1003 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001004
Douglas Gregorb837ea42011-01-11 17:34:58 +00001005 // - If A is a reference type, A is replaced by the type referred to.
1006 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1007 if (ArgRef)
1008 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
Richard Smithed563c22015-02-20 04:45:22 +00001010 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1011 // C++11 [temp.deduct.partial]p9:
1012 // If, for a given type, deduction succeeds in both directions (i.e.,
1013 // the types are identical after the transformations above) and both
1014 // P and A were reference types [...]:
1015 // - if [one type] was an lvalue reference and [the other type] was
1016 // not, [the other type] is not considered to be at least as
1017 // specialized as [the first type]
1018 // - if [one type] is more cv-qualified than [the other type],
1019 // [the other type] is not considered to be at least as specialized
1020 // as [the first type]
1021 // Objective-C ARC adds:
1022 // - [one type] has non-trivial lifetime, [the other type] has
1023 // __unsafe_unretained lifetime, and the types are otherwise
1024 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001025 //
Richard Smithed563c22015-02-20 04:45:22 +00001026 // A is "considered to be at least as specialized" as P iff deduction
1027 // succeeds, so we model this as a deduction failure. Note that
1028 // [the first type] is P and [the other type] is A here; the standard
1029 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001030 Qualifiers ParamQuals = Param.getQualifiers();
1031 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001032 if ((ParamRef->isLValueReferenceType() &&
1033 !ArgRef->isLValueReferenceType()) ||
1034 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1035 (ParamQuals.hasNonTrivialObjCLifetime() &&
1036 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1037 ParamQuals.withoutObjCLifetime() ==
1038 ArgQuals.withoutObjCLifetime())) {
1039 Info.FirstArg = TemplateArgument(ParamIn);
1040 Info.SecondArg = TemplateArgument(ArgIn);
1041 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001042 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Richard Smithed563c22015-02-20 04:45:22 +00001045 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001046 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001048 // version of P.
1049 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001051 // version of A.
1052 Arg = Arg.getUnqualifiedType();
1053 } else {
1054 // C++0x [temp.deduct.call]p4 bullet 1:
1055 // - If the original P is a reference type, the deduced A (i.e., the type
1056 // referred to by the reference) can be more cv-qualified than the
1057 // transformed A.
1058 if (TDF & TDF_ParamWithReferenceType) {
1059 Qualifiers Quals;
1060 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1061 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001062 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001063 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065
Douglas Gregor85f240c2011-01-25 17:19:08 +00001066 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1067 // C++0x [temp.deduct.type]p10:
1068 // If P and A are function types that originated from deduction when
1069 // taking the address of a function template (14.8.2.2) or when deducing
1070 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001071 // Ai are parameters of the top-level parameter-type-list of P and A,
1072 // respectively, Pi is adjusted if it is an rvalue reference to a
1073 // cv-unqualified template parameter and Ai is an lvalue reference, in
1074 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001075 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1076 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001077 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001078 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
Douglas Gregor85f240c2011-01-25 17:19:08 +00001080 if (const RValueReferenceType *ParamRef
1081 = Param->getAs<RValueReferenceType>()) {
1082 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1083 !ParamRef->getPointeeType().getQualifiers())
1084 if (Arg->isLValueReferenceType())
1085 Param = ParamRef->getPointeeType();
1086 }
1087 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001090 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001091 // A template type argument T, a template template argument TT or a
1092 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001093 // the following forms:
1094 //
1095 // T
1096 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001097 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001098 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001099 // Just skip any attempts to deduce from a placeholder type or a parameter
1100 // at a different depth.
1101 if (Arg->isPlaceholderType() ||
1102 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001103 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001104
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001105 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001106 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregor60454822009-07-22 20:02:25 +00001108 // If the argument type is an array type, move the qualifiers up to the
1109 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001110 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001111 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001112 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001113 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001114 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001115 RecanonicalizeArg = true;
1116 }
1117 }
Mike Stump11289f42009-09-09 15:08:12 +00001118
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001119 // The argument type can not be less qualified than the parameter
1120 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001121 if (!(TDF & TDF_IgnoreQualifiers) &&
1122 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001123 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001124 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001125 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001126 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001127 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001128
Richard Smith87d263e2016-12-25 08:05:23 +00001129 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1130 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001131 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001132 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001133
Douglas Gregor1d684c22011-04-28 00:56:09 +00001134 // Remove any qualifiers on the parameter from the deduced type.
1135 // We checked the qualifiers for consistency above.
1136 Qualifiers DeducedQs = DeducedType.getQualifiers();
1137 Qualifiers ParamQs = Param.getQualifiers();
1138 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1139 if (ParamQs.hasObjCGCAttr())
1140 DeducedQs.removeObjCGCAttr();
1141 if (ParamQs.hasAddressSpace())
1142 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001143 if (ParamQs.hasObjCLifetime())
1144 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001145
Douglas Gregore46db902011-06-17 22:11:49 +00001146 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001147 // If template deduction would produce a lifetime qualifier on a type
1148 // that is not a lifetime type, template argument deduction fails.
1149 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1150 !DeducedType->isDependentType()) {
1151 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1152 Info.FirstArg = TemplateArgument(Param);
1153 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001154 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001155 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001156
Douglas Gregora4f2b432011-07-26 14:53:44 +00001157 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001158 // If template deduction would produce an argument type with lifetime type
1159 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001160 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001161 DeducedType->isObjCLifetimeType() &&
1162 !DeducedQs.hasObjCLifetime())
1163 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001164
Douglas Gregor1d684c22011-04-28 00:56:09 +00001165 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1166 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001167
Douglas Gregord6605db2009-07-22 21:30:48 +00001168 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001169 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001170
Richard Smith5f274382016-09-28 23:55:27 +00001171 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001173 Deduced[Index],
1174 NewDeduced);
1175 if (Result.isNull()) {
1176 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1177 Info.FirstArg = Deduced[Index];
1178 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001182 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001184 }
1185
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001186 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001187 Info.FirstArg = TemplateArgument(ParamIn);
1188 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001189
Douglas Gregorfb322d82011-01-14 05:11:40 +00001190 // If the parameter is an already-substituted template parameter
1191 // pack, do nothing: we don't know which of its arguments to look
1192 // at, so we have to wait until all of the parameter packs in this
1193 // expansion have arguments.
1194 if (isa<SubstTemplateTypeParmPackType>(Param))
1195 return Sema::TDK_Success;
1196
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001197 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001198 CanQualType CanParam = S.Context.getCanonicalType(Param);
1199 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001200 if (!(TDF & TDF_IgnoreQualifiers)) {
1201 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001202 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001203 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001204 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001205 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001206 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001207 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001208
Douglas Gregor194ea692012-03-11 03:29:50 +00001209 // If the parameter type is not dependent, there is nothing to deduce.
1210 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001211 if (!(TDF & TDF_SkipNonDependent)) {
1212 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1213 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1214 Param != Arg;
1215 if (NonDeduced) {
1216 return Sema::TDK_NonDeducedMismatch;
1217 }
1218 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001219 return Sema::TDK_Success;
1220 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001221 } else if (!Param->isDependentType()) {
1222 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1223 ArgUnqualType = CanArg.getUnqualifiedType();
1224 bool Success = (TDF & TDF_InOverloadResolution)?
1225 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1226 ArgUnqualType) :
1227 ParamUnqualType == ArgUnqualType;
1228 if (Success)
1229 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001230 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001231
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001232 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001233 // Non-canonical types cannot appear here.
1234#define NON_CANONICAL_TYPE(Class, Base) \
1235 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1236#define TYPE(Class, Base)
1237#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001238
Douglas Gregor39c02722011-06-15 16:02:29 +00001239 case Type::TemplateTypeParm:
1240 case Type::SubstTemplateTypeParmPack:
1241 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001242
1243 // These types cannot be dependent, so simply check whether the types are
1244 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001245 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001246 case Type::VariableArray:
1247 case Type::Vector:
1248 case Type::FunctionNoProto:
1249 case Type::Record:
1250 case Type::Enum:
1251 case Type::ObjCObject:
1252 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001253 case Type::ObjCObjectPointer: {
1254 if (TDF & TDF_SkipNonDependent)
1255 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001256
Douglas Gregor194ea692012-03-11 03:29:50 +00001257 if (TDF & TDF_IgnoreQualifiers) {
1258 Param = Param.getUnqualifiedType();
1259 Arg = Arg.getUnqualifiedType();
1260 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001261
Douglas Gregor194ea692012-03-11 03:29:50 +00001262 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1263 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001264
1265 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001266 case Type::Complex:
1267 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001268 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1269 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001270 ComplexArg->getElementType(),
1271 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001272
1273 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001274
1275 // _Atomic T [extension]
1276 case Type::Atomic:
1277 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001278 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001279 cast<AtomicType>(Param)->getValueType(),
1280 AtomicArg->getValueType(),
1281 Info, Deduced, TDF);
1282
1283 return Sema::TDK_NonDeducedMismatch;
1284
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001285 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001286 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001287 QualType PointeeType;
1288 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1289 PointeeType = PointerArg->getPointeeType();
1290 } else if (const ObjCObjectPointerType *PointerArg
1291 = Arg->getAs<ObjCObjectPointerType>()) {
1292 PointeeType = PointerArg->getPointeeType();
1293 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001294 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregorfc516c92009-06-26 23:27:24 +00001297 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001298 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1299 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001300 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001301 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001304 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001305 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001306 const LValueReferenceType *ReferenceArg =
1307 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001308 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001309 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001310
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001311 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001312 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001313 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001314 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001315
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001316 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001317 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001318 const RValueReferenceType *ReferenceArg =
1319 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001320 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001321 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001322
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001323 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1324 cast<RValueReferenceType>(Param)->getPointeeType(),
1325 ReferenceArg->getPointeeType(),
1326 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001329 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001330 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001331 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001332 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001333 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001334 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001335
John McCallf7332682010-08-19 00:20:19 +00001336 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1338 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1339 IncompleteArrayArg->getElementType(),
1340 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001341 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342
1343 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001344 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001345 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001346 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001347 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001348 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001349
1350 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001351 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001352 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001353 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001354
John McCallf7332682010-08-19 00:20:19 +00001355 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001356 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1357 ConstantArrayParm->getElementType(),
1358 ConstantArrayArg->getElementType(),
1359 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001360 }
1361
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001362 // type [i]
1363 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001364 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001365 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001366 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCallf7332682010-08-19 00:20:19 +00001368 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1369
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001370 // Check the element type of the arrays
1371 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001372 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001373 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001374 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1375 DependentArrayParm->getElementType(),
1376 ArrayArg->getElementType(),
1377 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001378 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001379
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001380 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001381 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001382 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001383 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001384 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001385
1386 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001388 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1389 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001390 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001391 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1392 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001393 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001394 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001395 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001396 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001397 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001398 if (const DependentSizedArrayType *DependentArrayArg
1399 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001400 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001401 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001402 DependentArrayArg->getSizeExpr(),
1403 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001406 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
1409 // type(*)(T)
1410 // T(*)()
1411 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001412 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001413 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001414 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001415 dyn_cast<FunctionProtoType>(Arg);
1416 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001417 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001418
1419 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001420 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001421
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001423 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001424 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001425 != FunctionProtoArg->getRefQualifier() ||
1426 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001427 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001428
Anders Carlsson2128ec72009-06-08 15:19:08 +00001429 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001430 if (Sema::TemplateDeductionResult Result =
1431 DeduceTemplateArgumentsByTypeMatch(
1432 S, TemplateParams, FunctionProtoParam->getReturnType(),
1433 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001434 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001435
Alp Toker9cacbab2014-01-20 20:26:09 +00001436 return DeduceTemplateArguments(
1437 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1438 FunctionProtoParam->getNumParams(),
1439 FunctionProtoArg->param_type_begin(),
1440 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
John McCalle78aac42010-03-10 03:28:59 +00001443 case Type::InjectedClassName: {
1444 // Treat a template's injected-class-name as if the template
1445 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001446 Param = cast<InjectedClassNameType>(Param)
1447 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001448 assert(isa<TemplateSpecializationType>(Param) &&
1449 "injected class name is not a template specialization type");
1450 // fall through
1451 }
1452
Douglas Gregor705c9002009-06-26 20:57:09 +00001453 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001454 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001455 // TT<T>
1456 // TT<i>
1457 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001458 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001459 const TemplateSpecializationType *SpecParam =
1460 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Richard Smith9b296e32016-04-25 19:09:05 +00001462 // When Arg cannot be a derived class, we can just try to deduce template
1463 // arguments from the template-id.
1464 const RecordType *RecordT = Arg->getAs<RecordType>();
1465 if (!(TDF & TDF_DerivedClass) || !RecordT)
1466 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1467 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Richard Smith9b296e32016-04-25 19:09:05 +00001469 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1470 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001471
Richard Smith9b296e32016-04-25 19:09:05 +00001472 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1473 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Richard Smith9b296e32016-04-25 19:09:05 +00001475 if (Result == Sema::TDK_Success)
1476 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001477
Richard Smith9b296e32016-04-25 19:09:05 +00001478 // We cannot inspect base classes as part of deduction when the type
1479 // is incomplete, so either instantiate any templates necessary to
1480 // complete the type, or skip over it if it cannot be completed.
1481 if (!S.isCompleteType(Info.getLocation(), Arg))
1482 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001483
Richard Smith9b296e32016-04-25 19:09:05 +00001484 // C++14 [temp.deduct.call] p4b3:
1485 // If P is a class and P has the form simple-template-id, then the
1486 // transformed A can be a derived class of the deduced A. Likewise if
1487 // P is a pointer to a class of the form simple-template-id, the
1488 // transformed A can be a pointer to a derived class pointed to by the
1489 // deduced A.
1490 //
1491 // These alternatives are considered only if type deduction would
1492 // otherwise fail. If they yield more than one possible deduced A, the
1493 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001494
Faisal Vali683b0742016-05-19 02:28:21 +00001495 // Reset the incorrectly deduced argument from above.
1496 Deduced = DeducedOrig;
1497
1498 // Use data recursion to crawl through the list of base classes.
1499 // Visited contains the set of nodes we have already visited, while
1500 // ToVisit is our stack of records that we still need to visit.
1501 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1502 SmallVector<const RecordType *, 8> ToVisit;
1503 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001504 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001505 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001506 while (!ToVisit.empty()) {
1507 // Retrieve the next class in the inheritance hierarchy.
1508 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001509
Faisal Vali683b0742016-05-19 02:28:21 +00001510 // If we have already seen this type, skip it.
1511 if (!Visited.insert(NextT).second)
1512 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001513
Faisal Vali683b0742016-05-19 02:28:21 +00001514 // If this is a base class, try to perform template argument
1515 // deduction from it.
1516 if (NextT != RecordT) {
1517 TemplateDeductionInfo BaseInfo(Info.getLocation());
1518 Sema::TemplateDeductionResult BaseResult =
1519 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1520 QualType(NextT, 0), BaseInfo, Deduced);
1521
1522 // If template argument deduction for this base was successful,
1523 // note that we had some success. Otherwise, ignore any deductions
1524 // from this base class.
1525 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001526 // If we've already seen some success, then deduction fails due to
1527 // an ambiguity (temp.deduct.call p5).
1528 if (Successful)
1529 return Sema::TDK_MiscellaneousDeductionFailure;
1530
Faisal Vali683b0742016-05-19 02:28:21 +00001531 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001532 std::swap(SuccessfulDeduced, Deduced);
1533
Faisal Vali683b0742016-05-19 02:28:21 +00001534 Info.Param = BaseInfo.Param;
1535 Info.FirstArg = BaseInfo.FirstArg;
1536 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001537 }
1538
1539 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Faisal Vali683b0742016-05-19 02:28:21 +00001542 // Visit base classes
1543 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1544 for (const auto &Base : Next->bases()) {
1545 assert(Base.getType()->isRecordType() &&
1546 "Base class that isn't a record?");
1547 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1548 }
1549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001551 if (Successful) {
1552 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001553 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001554 }
Richard Smith9b296e32016-04-25 19:09:05 +00001555
Douglas Gregore81f3e72009-07-07 23:09:34 +00001556 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001557 }
1558
Douglas Gregor637d9982009-06-10 23:47:09 +00001559 // T type::*
1560 // T T::*
1561 // T (type::*)()
1562 // type (T::*)()
1563 // type (type::*)(T)
1564 // type (T::*)(T)
1565 // T (type::*)(T)
1566 // T (T::*)()
1567 // T (T::*)(T)
1568 case Type::MemberPointer: {
1569 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1570 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1571 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001572 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001573
David Majnemera381cda2015-11-30 20:34:28 +00001574 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1575 if (ParamPointeeType->isFunctionType())
1576 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1577 /*IsCtorOrDtor=*/false, Info.getLocation());
1578 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1579 if (ArgPointeeType->isFunctionType())
1580 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1581 /*IsCtorOrDtor=*/false, Info.getLocation());
1582
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001583 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001584 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001585 ParamPointeeType,
1586 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001587 Info, Deduced,
1588 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001589 return Result;
1590
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001591 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1592 QualType(MemPtrParam->getClass(), 0),
1593 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001594 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001595 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001596 }
1597
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001598 // (clang extension)
1599 //
Mike Stump11289f42009-09-09 15:08:12 +00001600 // type(^)(T)
1601 // T(^)()
1602 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001603 case Type::BlockPointer: {
1604 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1605 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001606
Anders Carlssona767eee2009-06-12 16:23:10 +00001607 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001608 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001609
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001610 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1611 BlockPtrParam->getPointeeType(),
1612 BlockPtrArg->getPointeeType(),
1613 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001614 }
1615
Douglas Gregor39c02722011-06-15 16:02:29 +00001616 // (clang extension)
1617 //
1618 // T __attribute__(((ext_vector_type(<integral constant>))))
1619 case Type::ExtVector: {
1620 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1621 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1622 // Make sure that the vectors have the same number of elements.
1623 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1624 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001625
Douglas Gregor39c02722011-06-15 16:02:29 +00001626 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001627 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628 VectorParam->getElementType(),
1629 VectorArg->getElementType(),
1630 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001631 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001632
1633 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001634 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1635 // We can't check the number of elements, since the argument has a
1636 // dependent number of elements. This can only occur during partial
1637 // ordering.
1638
1639 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001640 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1641 VectorParam->getElementType(),
1642 VectorArg->getElementType(),
1643 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001644 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001645
Douglas Gregor39c02722011-06-15 16:02:29 +00001646 return Sema::TDK_NonDeducedMismatch;
1647 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001648
Douglas Gregor39c02722011-06-15 16:02:29 +00001649 // (clang extension)
1650 //
1651 // T __attribute__(((ext_vector_type(N))))
1652 case Type::DependentSizedExtVector: {
1653 const DependentSizedExtVectorType *VectorParam
1654 = cast<DependentSizedExtVectorType>(Param);
1655
1656 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1657 // Perform deduction on the element types.
1658 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001659 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1660 VectorParam->getElementType(),
1661 VectorArg->getElementType(),
1662 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001663 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001664
Douglas Gregor39c02722011-06-15 16:02:29 +00001665 // Perform deduction on the vector size, if we can.
1666 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001667 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001668 if (!NTTP)
1669 return Sema::TDK_Success;
1670
1671 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1672 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001673 // Note that we use the "array bound" rules here; just like in that
1674 // case, we don't have any particular type for the vector size, but
1675 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001676 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001677 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001678 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001679 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001680
1681 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001682 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1683 // Perform deduction on the element types.
1684 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001685 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1686 VectorParam->getElementType(),
1687 VectorArg->getElementType(),
1688 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001689 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001690
Douglas Gregor39c02722011-06-15 16:02:29 +00001691 // Perform deduction on the vector size, if we can.
1692 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001693 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001694 if (!NTTP)
1695 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001696
Richard Smith5f274382016-09-28 23:55:27 +00001697 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1698 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001699 Info, Deduced);
1700 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001701
Douglas Gregor39c02722011-06-15 16:02:29 +00001702 return Sema::TDK_NonDeducedMismatch;
1703 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001704
Douglas Gregor637d9982009-06-10 23:47:09 +00001705 case Type::TypeOfExpr:
1706 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001707 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001708 case Type::UnresolvedUsing:
1709 case Type::Decltype:
1710 case Type::UnaryTransform:
1711 case Type::Auto:
1712 case Type::DependentTemplateSpecialization:
1713 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001714 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001715 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001716 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001717 }
1718
David Blaikiee4d798f2012-01-20 21:50:17 +00001719 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001720}
1721
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001722static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001723DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001724 TemplateParameterList *TemplateParams,
1725 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001726 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001727 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001728 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001729 // If the template argument is a pack expansion, perform template argument
1730 // deduction against the pattern of that expansion. This only occurs during
1731 // partial ordering.
1732 if (Arg.isPackExpansion())
1733 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001735 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001736 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001737 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001738
1739 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001740 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001741 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1742 Param.getAsType(),
1743 Arg.getAsType(),
1744 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001745 Info.FirstArg = Param;
1746 Info.SecondArg = Arg;
1747 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001748
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001749 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001750 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001752 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001753 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001754 Info.FirstArg = Param;
1755 Info.SecondArg = Arg;
1756 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001757
1758 case TemplateArgument::TemplateExpansion:
1759 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001761 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001762 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001763 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001764 return Sema::TDK_Success;
1765
1766 Info.FirstArg = Param;
1767 Info.SecondArg = Arg;
1768 return Sema::TDK_NonDeducedMismatch;
1769
1770 case TemplateArgument::NullPtr:
1771 if (Arg.getKind() == TemplateArgument::NullPtr &&
1772 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001773 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001775 Info.FirstArg = Param;
1776 Info.SecondArg = Arg;
1777 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001779 case TemplateArgument::Integral:
1780 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001781 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001782 return Sema::TDK_Success;
1783
1784 Info.FirstArg = Param;
1785 Info.SecondArg = Arg;
1786 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001787 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001788
1789 if (Arg.getKind() == TemplateArgument::Expression) {
1790 Info.FirstArg = Param;
1791 Info.SecondArg = Arg;
1792 return Sema::TDK_NonDeducedMismatch;
1793 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001794
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001795 Info.FirstArg = Param;
1796 Info.SecondArg = Arg;
1797 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001798
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001799 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001800 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001801 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001802 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001803 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001804 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001805 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001806 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001807 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001808 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001809 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1810 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001811 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001812 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001813 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1814 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001815 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001816 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1817 Arg.getAsDecl(),
1818 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001819 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001821 Info.FirstArg = Param;
1822 Info.SecondArg = Arg;
1823 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001826 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001827 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001828 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001829 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001830 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832
David Blaikiee4d798f2012-01-20 21:50:17 +00001833 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001834}
1835
Douglas Gregor7baabef2010-12-22 18:17:10 +00001836/// \brief Determine whether there is a template argument to be used for
1837/// deduction.
1838///
1839/// This routine "expands" argument packs in-place, overriding its input
1840/// parameters so that \c Args[ArgIdx] will be the available template argument.
1841///
1842/// \returns true if there is another template argument (which will be at
1843/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001844static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1845 unsigned &ArgIdx) {
1846 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001847 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001848
Douglas Gregor7baabef2010-12-22 18:17:10 +00001849 const TemplateArgument &Arg = Args[ArgIdx];
1850 if (Arg.getKind() != TemplateArgument::Pack)
1851 return true;
1852
Richard Smith0bda5b52016-12-23 23:46:56 +00001853 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1854 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001855 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001856 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001857}
1858
Douglas Gregord0ad2942010-12-23 01:24:45 +00001859/// \brief Determine whether the given set of template arguments has a pack
1860/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001861static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1862 bool FoundPackExpansion = false;
1863 for (const auto &A : Args) {
1864 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001865 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001866
1867 if (A.getKind() == TemplateArgument::Pack)
1868 return hasPackExpansionBeforeEnd(A.pack_elements());
1869
1870 if (A.isPackExpansion())
1871 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873
Douglas Gregord0ad2942010-12-23 01:24:45 +00001874 return false;
1875}
1876
Douglas Gregor7baabef2010-12-22 18:17:10 +00001877static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001878DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001879 ArrayRef<TemplateArgument> Params,
1880 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001881 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001882 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1883 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001884 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885 // If the template argument list of P contains a pack expansion that is not
1886 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001888 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001889 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892 // If P has a form that contains <T> or <i>, then each argument Pi of the
1893 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001894 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001896 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001897 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001898 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899
Douglas Gregor7baabef2010-12-22 18:17:10 +00001900 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001901 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00001902 return NumberOfArgumentsMustMatch
1903 ? Sema::TDK_MiscellaneousDeductionFailure
1904 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
Richard Smith26b86ea2016-12-31 21:41:23 +00001906 // C++1z [temp.deduct.type]p9:
1907 // During partial ordering, if Ai was originally a pack expansion [and]
1908 // Pi is not a pack expansion, template argument deduction fails.
1909 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001910 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001912 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001913 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001914 = DeduceTemplateArguments(S, TemplateParams,
1915 Params[ParamIdx], Args[ArgIdx],
1916 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917 return Result;
1918
Douglas Gregor7baabef2010-12-22 18:17:10 +00001919 // Move to the next argument.
1920 ++ArgIdx;
1921 continue;
1922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001924 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001926 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927 // If Pi is a pack expansion, then the pattern of Pi is compared with
1928 // each remaining argument in the template argument list of A. Each
1929 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001930 // template parameter packs expanded by Pi.
1931 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001933 // FIXME: If there are no remaining arguments, we can bail out early
1934 // and set any deduced parameter packs to an empty argument pack.
1935 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936
Richard Smith0a80d572014-05-29 01:12:14 +00001937 // Prepare to deduce the packs within the pattern.
1938 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001939
1940 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001942 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00001943 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001944 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001946 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1947 Info, Deduced))
1948 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Richard Smith0a80d572014-05-29 01:12:14 +00001950 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001953 // Build argument packs for each of the parameter packs expanded by this
1954 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001955 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregor7baabef2010-12-22 18:17:10 +00001959 return Sema::TDK_Success;
1960}
1961
Mike Stump11289f42009-09-09 15:08:12 +00001962static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001963DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001964 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001965 const TemplateArgumentList &ParamList,
1966 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001967 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001968 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001969 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00001970 ArgList.asArray(), Info, Deduced,
1971 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001972}
1973
Douglas Gregor705c9002009-06-26 20:57:09 +00001974/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001975static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00001976 TemplateArgument X,
1977 const TemplateArgument &Y,
1978 bool PackExpansionMatchesPack = false) {
1979 // If we're checking deduced arguments (X) against original arguments (Y),
1980 // we will have flattened packs to non-expansions in X.
1981 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
1982 X = X.getPackExpansionPattern();
1983
Douglas Gregor705c9002009-06-26 20:57:09 +00001984 if (X.getKind() != Y.getKind())
1985 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001986
Douglas Gregor705c9002009-06-26 20:57:09 +00001987 switch (X.getKind()) {
1988 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001989 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregor705c9002009-06-26 20:57:09 +00001991 case TemplateArgument::Type:
1992 return Context.getCanonicalType(X.getAsType()) ==
1993 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001994
Douglas Gregor705c9002009-06-26 20:57:09 +00001995 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001996 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001997
1998 case TemplateArgument::NullPtr:
1999 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002001 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002002 case TemplateArgument::TemplateExpansion:
2003 return Context.getCanonicalTemplateName(
2004 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2005 Context.getCanonicalTemplateName(
2006 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Douglas Gregor705c9002009-06-26 20:57:09 +00002008 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002009 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002010
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002011 case TemplateArgument::Expression: {
2012 llvm::FoldingSetNodeID XID, YID;
2013 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002015 return XID == YID;
2016 }
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor705c9002009-06-26 20:57:09 +00002018 case TemplateArgument::Pack:
2019 if (X.pack_size() != Y.pack_size())
2020 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002021
2022 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2023 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002024 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002025 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002026 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002027 return false;
2028
2029 return true;
2030 }
2031
David Blaikiee4d798f2012-01-20 21:50:17 +00002032 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002033}
2034
Douglas Gregorca4686d2011-01-04 23:35:54 +00002035/// \brief Allocate a TemplateArgumentLoc where all locations have
2036/// been initialized to the given location.
2037///
James Dennett634962f2012-06-14 21:40:34 +00002038/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002039/// location information for.
2040///
2041/// \param NTTPType For a declaration template argument, the type of
2042/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002043/// argument. Can be null if no type sugar is available to add to the
2044/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002045///
2046/// \param Loc The source location to use for the resulting template
2047/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002048TemplateArgumentLoc
2049Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2050 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002051 switch (Arg.getKind()) {
2052 case TemplateArgument::Null:
2053 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Douglas Gregorca4686d2011-01-04 23:35:54 +00002055 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002056 return TemplateArgumentLoc(
2057 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002058
Douglas Gregorca4686d2011-01-04 23:35:54 +00002059 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002060 if (NTTPType.isNull())
2061 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002062 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2063 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002064 return TemplateArgumentLoc(TemplateArgument(E), E);
2065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066
Eli Friedmanb826a002012-09-26 02:36:12 +00002067 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002068 if (NTTPType.isNull())
2069 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002070 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2071 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002072 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2073 E);
2074 }
2075
Douglas Gregorca4686d2011-01-04 23:35:54 +00002076 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002077 Expr *E =
2078 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002079 return TemplateArgumentLoc(TemplateArgument(E), E);
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Douglas Gregor9d802122011-03-02 17:09:35 +00002082 case TemplateArgument::Template:
2083 case TemplateArgument::TemplateExpansion: {
2084 NestedNameSpecifierLocBuilder Builder;
2085 TemplateName Template = Arg.getAsTemplate();
2086 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002087 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002088 else if (QualifiedTemplateName *QTN =
2089 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002090 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002091
Douglas Gregor9d802122011-03-02 17:09:35 +00002092 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002093 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002094 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002095
2096 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002097 Loc, Loc);
2098 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002099
Douglas Gregorca4686d2011-01-04 23:35:54 +00002100 case TemplateArgument::Expression:
2101 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102
Douglas Gregorca4686d2011-01-04 23:35:54 +00002103 case TemplateArgument::Pack:
2104 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106
David Blaikiee4d798f2012-01-20 21:50:17 +00002107 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002108}
2109
2110
2111/// \brief Convert the given deduced template argument and add it to the set of
2112/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002113static bool
2114ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2115 DeducedTemplateArgument Arg,
2116 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002117 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002118 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002119 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002120 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2121 unsigned ArgumentPackIndex) {
2122 // Convert the deduced template argument into a template
2123 // argument that we can check, almost as if the user had written
2124 // the template argument explicitly.
2125 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002126 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002127
2128 // Check the template argument, converting it as necessary.
2129 return S.CheckTemplateArgument(
2130 Param, ArgLoc, Template, Template->getLocation(),
2131 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002132 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002133 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2134 : Sema::CTAK_Deduced)
2135 : Sema::CTAK_Specified);
2136 };
2137
Douglas Gregorca4686d2011-01-04 23:35:54 +00002138 if (Arg.getKind() == TemplateArgument::Pack) {
2139 // This is a template argument pack, so check each of its arguments against
2140 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002141 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002142 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002143 // When converting the deduced template argument, append it to the
2144 // general output list. We need to do this so that the template argument
2145 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002146 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002147 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002148 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2149 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002150 if (P.isNull()) {
2151 // We deduced arguments for some elements of this pack, but not for
2152 // all of them. This happens if we get a conditionally-non-deduced
2153 // context in a pack expansion (such as an overload set in one of the
2154 // arguments).
2155 S.Diag(Param->getLocation(),
2156 diag::err_template_arg_deduced_incomplete_pack)
2157 << Arg << Param;
2158 return true;
2159 }
Richard Smith37acb792016-02-03 20:15:01 +00002160 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002161 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Douglas Gregor51bc5712011-01-05 20:52:18 +00002163 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002164 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166
Richard Smithdf18ee92016-02-03 20:40:30 +00002167 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002168 // itself, in case that substitution fails.
2169 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002170 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002171 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002172 MultiLevelTemplateArgumentList Args(TemplateArgs);
2173
2174 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2175 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2176 NTTP, Output,
2177 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002178 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002179 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2180 NTTP->getDeclName()).isNull())
2181 return true;
2182 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2183 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2184 TTP, Output,
2185 Template->getSourceRange());
2186 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2187 return true;
2188 }
2189 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002190 }
Richard Smith37acb792016-02-03 20:15:01 +00002191
Douglas Gregorca4686d2011-01-04 23:35:54 +00002192 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002193 Output.push_back(
2194 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002195 return false;
2196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Richard Smith37acb792016-02-03 20:15:01 +00002198 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002199}
2200
Richard Smith1f5be4d2016-12-21 01:10:31 +00002201// FIXME: This should not be a template, but
2202// ClassTemplatePartialSpecializationDecl sadly does not derive from
2203// TemplateDecl.
2204template<typename TemplateDeclT>
2205static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002206 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002207 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2208 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2209 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2210 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2211 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2212
2213 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2214 NamedDecl *Param = TemplateParams->getParam(I);
2215
2216 if (!Deduced[I].isNull()) {
2217 if (I < NumAlreadyConverted) {
2218 // We have already fully type-checked and converted this
2219 // argument, because it was explicitly-specified. Just record the
2220 // presence of this argument.
2221 Builder.push_back(Deduced[I]);
2222 // We may have had explicitly-specified template arguments for a
2223 // template parameter pack (that may or may not have been extended
2224 // via additional deduced arguments).
2225 if (Param->isParameterPack() && CurrentInstantiationScope) {
2226 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2227 Param) {
2228 // Forget the partially-substituted pack; its substitution is now
2229 // complete.
2230 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2231 }
2232 }
2233 continue;
2234 }
2235
2236 // We have deduced this argument, so it still needs to be
2237 // checked and converted.
2238 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002239 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002240 Info.Param = makeTemplateParameter(Param);
2241 // FIXME: These template arguments are temporary. Free them!
2242 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2243 return Sema::TDK_SubstitutionFailure;
2244 }
2245
2246 continue;
2247 }
2248
2249 // C++0x [temp.arg.explicit]p3:
2250 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2251 // be deduced to an empty sequence of template arguments.
2252 // FIXME: Where did the word "trailing" come from?
2253 if (Param->isTemplateParameterPack()) {
2254 // We may have had explicitly-specified template arguments for this
2255 // template parameter pack. If so, our empty deduction extends the
2256 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2257 const TemplateArgument *ExplicitArgs;
2258 unsigned NumExplicitArgs;
2259 if (CurrentInstantiationScope &&
2260 CurrentInstantiationScope->getPartiallySubstitutedPack(
2261 &ExplicitArgs, &NumExplicitArgs) == Param) {
2262 Builder.push_back(TemplateArgument(
2263 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2264
2265 // Forget the partially-substituted pack; its substitution is now
2266 // complete.
2267 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2268 } else {
2269 // Go through the motions of checking the empty argument pack against
2270 // the parameter pack.
2271 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002272 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2273 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002274 Info.Param = makeTemplateParameter(Param);
2275 // FIXME: These template arguments are temporary. Free them!
2276 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2277 return Sema::TDK_SubstitutionFailure;
2278 }
2279 }
2280 continue;
2281 }
2282
2283 // Substitute into the default template argument, if available.
2284 bool HasDefaultArg = false;
2285 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2286 if (!TD) {
2287 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2288 return Sema::TDK_Incomplete;
2289 }
2290
2291 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2292 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2293 HasDefaultArg);
2294
2295 // If there was no default argument, deduction is incomplete.
2296 if (DefArg.getArgument().isNull()) {
2297 Info.Param = makeTemplateParameter(
2298 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2299 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2300 if (PartialOverloading) break;
2301
2302 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2303 : Sema::TDK_Incomplete;
2304 }
2305
2306 // Check whether we can actually use the default argument.
2307 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2308 TD->getSourceRange().getEnd(), 0, Builder,
2309 Sema::CTAK_Specified)) {
2310 Info.Param = makeTemplateParameter(
2311 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2312 // FIXME: These template arguments are temporary. Free them!
2313 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2314 return Sema::TDK_SubstitutionFailure;
2315 }
2316
2317 // If we get here, we successfully used the default template argument.
2318 }
2319
2320 return Sema::TDK_Success;
2321}
2322
Richard Smith0da6dc42016-12-24 16:40:51 +00002323DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2324 if (auto *DC = dyn_cast<DeclContext>(D))
2325 return DC;
2326 return D->getDeclContext();
2327}
2328
2329template<typename T> struct IsPartialSpecialization {
2330 static constexpr bool value = false;
2331};
2332template<>
2333struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2334 static constexpr bool value = true;
2335};
2336template<>
2337struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2338 static constexpr bool value = true;
2339};
2340
2341/// Complete template argument deduction for a partial specialization.
2342template <typename T>
2343static typename std::enable_if<IsPartialSpecialization<T>::value,
2344 Sema::TemplateDeductionResult>::type
2345FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002346 Sema &S, T *Partial, bool IsPartialOrdering,
2347 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002348 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2349 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002350 // Unevaluated SFINAE context.
2351 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002352 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002353
Richard Smith0da6dc42016-12-24 16:40:51 +00002354 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002355
2356 // C++ [temp.deduct.type]p2:
2357 // [...] or if any template argument remains neither deduced nor
2358 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002359 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002360 if (auto Result = ConvertDeducedTemplateArguments(
2361 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002362 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363
Douglas Gregor684268d2010-04-29 06:21:43 +00002364 // Form the template argument list from the deduced template arguments.
2365 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002366 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002367
Douglas Gregor684268d2010-04-29 06:21:43 +00002368 Info.reset(DeducedArgumentList);
2369
2370 // Substitute the deduced template arguments into the template
2371 // arguments of the class template partial specialization, and
2372 // verify that the instantiated template arguments are both valid
2373 // and are equivalent to the template arguments originally provided
2374 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002375 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002376 auto *Template = Partial->getSpecializedTemplate();
2377 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2378 Partial->getTemplateArgsAsWritten();
2379 const TemplateArgumentLoc *PartialTemplateArgs =
2380 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002381
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002382 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2383 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002384
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002385 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002386 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2387 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2388 if (ParamIdx >= Partial->getTemplateParameters()->size())
2389 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2390
Richard Smith0da6dc42016-12-24 16:40:51 +00002391 Decl *Param = const_cast<NamedDecl *>(
2392 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002393 Info.Param = makeTemplateParameter(Param);
2394 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2395 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002396 }
2397
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002398 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002399 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2400 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002401 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002402
Richard Smith0da6dc42016-12-24 16:40:51 +00002403 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002404 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002405 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002406 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002407 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002408 Info.FirstArg = TemplateArgs[I];
2409 Info.SecondArg = InstArg;
2410 return Sema::TDK_NonDeducedMismatch;
2411 }
2412 }
2413
2414 if (Trap.hasErrorOccurred())
2415 return Sema::TDK_SubstitutionFailure;
2416
2417 return Sema::TDK_Success;
2418}
2419
Richard Smith0e617ec2016-12-27 07:56:27 +00002420/// Complete template argument deduction for a class or variable template,
2421/// when partial ordering against a partial specialization.
2422// FIXME: Factor out duplication with partial specialization version above.
2423Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2424 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2425 const TemplateArgumentList &TemplateArgs,
2426 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2427 TemplateDeductionInfo &Info) {
2428 // Unevaluated SFINAE context.
2429 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2430 Sema::SFINAETrap Trap(S);
2431
2432 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2433
2434 // C++ [temp.deduct.type]p2:
2435 // [...] or if any template argument remains neither deduced nor
2436 // explicitly specified, template argument deduction fails.
2437 SmallVector<TemplateArgument, 4> Builder;
2438 if (auto Result = ConvertDeducedTemplateArguments(
2439 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2440 return Result;
2441
2442 // Check that we produced the correct argument list.
2443 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2444 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2445 TemplateArgument InstArg = Builder[I];
2446 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2447 /*PackExpansionMatchesPack*/true)) {
2448 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2449 Info.FirstArg = TemplateArgs[I];
2450 Info.SecondArg = InstArg;
2451 return Sema::TDK_NonDeducedMismatch;
2452 }
2453 }
2454
2455 if (Trap.hasErrorOccurred())
2456 return Sema::TDK_SubstitutionFailure;
2457
2458 return Sema::TDK_Success;
2459}
2460
2461
Douglas Gregor170bc422009-06-12 22:31:52 +00002462/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002463/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002464/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002465Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002466Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002467 const TemplateArgumentList &TemplateArgs,
2468 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002469 if (Partial->isInvalidDecl())
2470 return TDK_Invalid;
2471
Douglas Gregor170bc422009-06-12 22:31:52 +00002472 // C++ [temp.class.spec.match]p2:
2473 // A partial specialization matches a given actual template
2474 // argument list if the template arguments of the partial
2475 // specialization can be deduced from the actual template argument
2476 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002477
2478 // Unevaluated SFINAE context.
2479 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002480 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002481
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002482 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002483 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002484 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002485 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002486 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002487 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002488 TemplateArgs, Info, Deduced))
2489 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002490
Richard Smith80934652012-07-16 01:09:10 +00002491 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002492 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2493 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002494 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002495 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002496
Douglas Gregore1416332009-06-14 08:02:22 +00002497 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002498 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002499
Richard Smith87d263e2016-12-25 08:05:23 +00002500 return ::FinishTemplateArgumentDeduction(
2501 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002502}
Douglas Gregor91772d12009-06-13 00:26:55 +00002503
Larisse Voufo39a1e502013-08-06 01:03:05 +00002504/// \brief Perform template argument deduction to determine whether
2505/// the given template arguments match the given variable template
2506/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002507Sema::TemplateDeductionResult
2508Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2509 const TemplateArgumentList &TemplateArgs,
2510 TemplateDeductionInfo &Info) {
2511 if (Partial->isInvalidDecl())
2512 return TDK_Invalid;
2513
2514 // C++ [temp.class.spec.match]p2:
2515 // A partial specialization matches a given actual template
2516 // argument list if the template arguments of the partial
2517 // specialization can be deduced from the actual template argument
2518 // list (14.8.2).
2519
2520 // Unevaluated SFINAE context.
2521 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2522 SFINAETrap Trap(*this);
2523
2524 SmallVector<DeducedTemplateArgument, 4> Deduced;
2525 Deduced.resize(Partial->getTemplateParameters()->size());
2526 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2527 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2528 TemplateArgs, Info, Deduced))
2529 return Result;
2530
2531 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002532 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2533 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002534 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002535 return TDK_InstantiationDepth;
2536
2537 if (Trap.hasErrorOccurred())
2538 return Sema::TDK_SubstitutionFailure;
2539
Richard Smith87d263e2016-12-25 08:05:23 +00002540 return ::FinishTemplateArgumentDeduction(
2541 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002542}
2543
Douglas Gregorfc516c92009-06-26 23:27:24 +00002544/// \brief Determine whether the given type T is a simple-template-id type.
2545static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002546 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002547 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002548 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregorfc516c92009-06-26 23:27:24 +00002550 return false;
2551}
Douglas Gregor9b146582009-07-08 20:55:45 +00002552
2553/// \brief Substitute the explicitly-provided template arguments into the
2554/// given function template according to C++ [temp.arg.explicit].
2555///
2556/// \param FunctionTemplate the function template into which the explicit
2557/// template arguments will be substituted.
2558///
James Dennett634962f2012-06-14 21:40:34 +00002559/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002560/// arguments.
2561///
Mike Stump11289f42009-09-09 15:08:12 +00002562/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002563/// with the converted and checked explicit template arguments.
2564///
Mike Stump11289f42009-09-09 15:08:12 +00002565/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002566/// parameters.
2567///
2568/// \param FunctionType if non-NULL, the result type of the function template
2569/// will also be instantiated and the pointed-to value will be updated with
2570/// the instantiated function type.
2571///
2572/// \param Info if substitution fails for any reason, this object will be
2573/// populated with more information about the failure.
2574///
2575/// \returns TDK_Success if substitution was successful, or some failure
2576/// condition.
2577Sema::TemplateDeductionResult
2578Sema::SubstituteExplicitTemplateArguments(
2579 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002580 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002581 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2582 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002583 QualType *FunctionType,
2584 TemplateDeductionInfo &Info) {
2585 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2586 TemplateParameterList *TemplateParams
2587 = FunctionTemplate->getTemplateParameters();
2588
John McCall6b51f282009-11-23 01:53:49 +00002589 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002590 // No arguments to substitute; just copy over the parameter types and
2591 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002592 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002593 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002594
Douglas Gregor9b146582009-07-08 20:55:45 +00002595 if (FunctionType)
2596 *FunctionType = Function->getType();
2597 return TDK_Success;
2598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Eli Friedman77dcc722012-02-08 03:07:05 +00002600 // Unevaluated SFINAE context.
2601 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002602 SFINAETrap Trap(*this);
2603
Douglas Gregor9b146582009-07-08 20:55:45 +00002604 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002605 // Template arguments that are present shall be specified in the
2606 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002607 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002608 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002609 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002610
2611 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002612 // explicitly-specified template arguments against this function template,
2613 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002614 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002615 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2616 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002617 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2618 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002619 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002620 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002621
Douglas Gregor9b146582009-07-08 20:55:45 +00002622 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002623 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002624 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002625 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002626 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002627 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002628 if (Index >= TemplateParams->size())
2629 Index = TemplateParams->size() - 1;
2630 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002631 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002632 }
Mike Stump11289f42009-09-09 15:08:12 +00002633
Douglas Gregor9b146582009-07-08 20:55:45 +00002634 // Form the template argument list from the explicitly-specified
2635 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002636 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002637 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002638 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002639
John McCall036855a2010-10-12 19:40:14 +00002640 // Template argument deduction and the final substitution should be
2641 // done in the context of the templated declaration. Explicit
2642 // argument substitution, on the other hand, needs to happen in the
2643 // calling context.
2644 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2645
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002646 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002647 // note that the template argument pack is partially substituted and record
2648 // the explicit template arguments. They'll be used as part of deduction
2649 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002650 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2651 const TemplateArgument &Arg = Builder[I];
2652 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002653 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002655 Arg.pack_begin(),
2656 Arg.pack_size());
2657 break;
2658 }
2659 }
2660
Richard Smith5e580292012-02-10 09:58:53 +00002661 const FunctionProtoType *Proto
2662 = Function->getType()->getAs<FunctionProtoType>();
2663 assert(Proto && "Function template does not have a prototype?");
2664
Richard Smith70b13042015-01-09 01:19:56 +00002665 // Isolate our substituted parameters from our caller.
2666 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2667
John McCallc8e321d2016-03-01 02:09:25 +00002668 ExtParameterInfoBuilder ExtParamInfos;
2669
Douglas Gregor9b146582009-07-08 20:55:45 +00002670 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002671 // explicitly-specified template arguments. If the function has a trailing
2672 // return type, substitute it after the arguments to ensure we substitute
2673 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002674 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002675 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002676 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002677 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002678 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002679 return TDK_SubstitutionFailure;
2680 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002681
Richard Smith5e580292012-02-10 09:58:53 +00002682 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002683 QualType ResultType;
2684 {
2685 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002686 // If a declaration declares a member function or member function
2687 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002688 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002689 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002690 // declarator.
2691 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002692 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2694 ThisContext = Method->getParent();
2695 ThisTypeQuals = Method->getTypeQualifiers();
2696 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002697
Douglas Gregor3024f072012-04-16 07:05:22 +00002698 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002699 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002700
2701 ResultType =
2702 SubstType(Proto->getReturnType(),
2703 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2704 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002705 if (ResultType.isNull() || Trap.hasErrorOccurred())
2706 return TDK_SubstitutionFailure;
2707 }
John McCallc8e321d2016-03-01 02:09:25 +00002708
Richard Smith5e580292012-02-10 09:58:53 +00002709 // Instantiate the types of each of the function parameters given the
2710 // explicitly-specified template arguments if we didn't do so earlier.
2711 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002712 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002713 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002714 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002715 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002716 return TDK_SubstitutionFailure;
2717
Douglas Gregor9b146582009-07-08 20:55:45 +00002718 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002719 auto EPI = Proto->getExtProtoInfo();
2720 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002721 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002722 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002723 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002724 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002725 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2726 return TDK_SubstitutionFailure;
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Douglas Gregor9b146582009-07-08 20:55:45 +00002729 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002730 // Trailing template arguments that can be deduced (14.8.2) may be
2731 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002732 // template arguments can be deduced, they may all be omitted; in this
2733 // case, the empty template argument list <> itself may also be omitted.
2734 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002735 // Take all of the explicitly-specified arguments and put them into
2736 // the set of deduced template arguments. Explicitly-specified
2737 // parameter packs, however, will be set to NULL since the deduction
2738 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002739 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002740 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2741 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2742 if (Arg.getKind() == TemplateArgument::Pack)
2743 Deduced.push_back(DeducedTemplateArgument());
2744 else
2745 Deduced.push_back(Arg);
2746 }
Mike Stump11289f42009-09-09 15:08:12 +00002747
Douglas Gregor9b146582009-07-08 20:55:45 +00002748 return TDK_Success;
2749}
2750
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002751/// \brief Check whether the deduced argument type for a call to a function
2752/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002753static bool
2754CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002755 QualType DeducedA) {
2756 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002757
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002758 QualType A = OriginalArg.OriginalArgType;
2759 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002760
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002761 // Check for type equality (top-level cv-qualifiers are ignored).
2762 if (Context.hasSameUnqualifiedType(A, DeducedA))
2763 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002764
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002765 // Strip off references on the argument types; they aren't needed for
2766 // the following checks.
2767 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2768 DeducedA = DeducedARef->getPointeeType();
2769 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2770 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002771
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002772 // C++ [temp.deduct.call]p4:
2773 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002774 // - If the original P is a reference type, the deduced A (i.e., the
2775 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002776 // the transformed A.
2777 if (const ReferenceType *OriginalParamRef
2778 = OriginalParamType->getAs<ReferenceType>()) {
2779 // We don't want to keep the reference around any more.
2780 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002781
Richard Smith1be59c52016-10-22 01:32:19 +00002782 // FIXME: Resolve core issue (no number yet): if the original P is a
2783 // reference type and the transformed A is function type "noexcept F",
2784 // the deduced A can be F.
2785 QualType Tmp;
2786 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2787 return false;
2788
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002789 Qualifiers AQuals = A.getQualifiers();
2790 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002791
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002792 // Under Objective-C++ ARC, the deduced type may have implicitly
2793 // been given strong or (when dealing with a const reference)
2794 // unsafe_unretained lifetime. If so, update the original
2795 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002796 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002797 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2798 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2799 (DeducedAQuals.hasConst() &&
2800 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2801 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002802 }
2803
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002804 if (AQuals == DeducedAQuals) {
2805 // Qualifiers match; there's nothing to do.
2806 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002807 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002808 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002809 // Qualifiers are compatible, so have the argument type adopt the
2810 // deduced argument type's qualifiers as if we had performed the
2811 // qualification conversion.
2812 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2813 }
2814 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002815
2816 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002817 // type that can be converted to the deduced A via a function pointer
2818 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002819 //
Richard Smith1be59c52016-10-22 01:32:19 +00002820 // Also allow conversions which merely strip __attribute__((noreturn)) from
2821 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002822 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002823 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002824 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002825 (S.IsQualificationConversion(A, DeducedA, false,
2826 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002827 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002828 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002829
Simon Pilgrim728134c2016-08-12 11:43:57 +00002830 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002831 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002832 // [...] Likewise, if P is a pointer to a class of the form
2833 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002834 // derived class pointed to by the deduced A.
2835 if (const PointerType *OriginalParamPtr
2836 = OriginalParamType->getAs<PointerType>()) {
2837 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2838 if (const PointerType *APtr = A->getAs<PointerType>()) {
2839 if (A->getPointeeType()->isRecordType()) {
2840 OriginalParamType = OriginalParamPtr->getPointeeType();
2841 DeducedA = DeducedAPtr->getPointeeType();
2842 A = APtr->getPointeeType();
2843 }
2844 }
2845 }
2846 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002847
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002848 if (Context.hasSameUnqualifiedType(A, DeducedA))
2849 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002850
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002851 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002852 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002853 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002854
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002855 return true;
2856}
2857
Mike Stump11289f42009-09-09 15:08:12 +00002858/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002859/// checking the deduced template arguments for completeness and forming
2860/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002861///
2862/// \param OriginalCallArgs If non-NULL, the original call arguments against
2863/// which the deduced argument types should be compared.
Renato Golindad96d62017-01-02 11:15:42 +00002864Sema::TemplateDeductionResult
2865Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2866 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2867 unsigned NumExplicitlySpecified,
2868 FunctionDecl *&Specialization,
2869 TemplateDeductionInfo &Info,
2870 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2871 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002872 // Unevaluated SFINAE context.
2873 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002874 SFINAETrap Trap(*this);
2875
Douglas Gregor9b146582009-07-08 20:55:45 +00002876 // Enter a new template instantiation context while we instantiate the
2877 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002878 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002879 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2880 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002881 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2882 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002883 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002884 return TDK_InstantiationDepth;
2885
John McCalle23b8712010-04-29 01:18:58 +00002886 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002887
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002888 // C++ [temp.deduct.type]p2:
2889 // [...] or if any template argument remains neither deduced nor
2890 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002891 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002892 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002893 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002894 CurrentInstantiationScope, NumExplicitlySpecified,
2895 PartialOverloading))
2896 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002897
2898 // Form the template argument list from the deduced template arguments.
2899 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002900 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002901 Info.reset(DeducedArgumentList);
2902
Mike Stump11289f42009-09-09 15:08:12 +00002903 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002904 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002905 DeclContext *Owner = FunctionTemplate->getDeclContext();
2906 if (FunctionTemplate->getFriendObjectKind())
2907 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002908 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002909 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002910 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002911 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002912 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002915 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916
Mike Stump11289f42009-09-09 15:08:12 +00002917 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002918 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002919 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2920 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002921 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002922
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002923 // There may have been an error that did not prevent us from constructing a
2924 // declaration. Mark the declaration invalid and return with a substitution
2925 // failure.
2926 if (Trap.hasErrorOccurred()) {
2927 Specialization->setInvalidDecl(true);
2928 return TDK_SubstitutionFailure;
2929 }
2930
Douglas Gregore65aacb2011-06-16 16:50:48 +00002931 if (OriginalCallArgs) {
2932 // C++ [temp.deduct.call]p4:
2933 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002934 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002935 // is transformed as described above). [...]
2936 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2937 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002938 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002939
Douglas Gregore65aacb2011-06-16 16:50:48 +00002940 if (ParamIdx >= Specialization->getNumParams())
2941 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002942
Douglas Gregore65aacb2011-06-16 16:50:48 +00002943 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002944 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2945 Info.FirstArg = TemplateArgument(DeducedA);
2946 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2947 Info.CallArgIndex = OriginalArg.ArgIdx;
2948 return TDK_DeducedMismatch;
2949 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002950 }
2951 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002952
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002953 // If we suppressed any diagnostics while performing template argument
2954 // deduction, and if we haven't already instantiated this declaration,
2955 // keep track of these diagnostics. They'll be emitted if this specialization
2956 // is actually used.
2957 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002958 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002959 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2960 if (Pos == SuppressedDiagnostics.end())
2961 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2962 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002964
Mike Stump11289f42009-09-09 15:08:12 +00002965 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002966}
2967
John McCall8d08b9b2010-08-27 09:08:28 +00002968/// Gets the type of a function for template-argument-deducton
2969/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002970static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002971 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002972 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002973 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002974 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002975 return QualType();
2976
John McCallc1f69982010-02-02 02:21:27 +00002977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002978 if (Method->isInstance()) {
2979 // An instance method that's referenced in a form that doesn't
2980 // look like a member pointer is just invalid.
2981 if (!R.HasFormOfMemberPointer) return QualType();
2982
Richard Smith2a7d4812013-05-04 07:00:32 +00002983 return S.Context.getMemberPointerType(Fn->getType(),
2984 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002985 }
2986
2987 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002988 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002989}
2990
2991/// Apply the deduction rules for overload sets.
2992///
2993/// \return the null type if this argument should be treated as an
2994/// undeduced context
2995static QualType
2996ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002997 Expr *Arg, QualType ParamType,
2998 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999
John McCall8d08b9b2010-08-27 09:08:28 +00003000 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003001
John McCall8d08b9b2010-08-27 09:08:28 +00003002 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003003
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003004 // C++0x [temp.deduct.call]p4
3005 unsigned TDF = 0;
3006 if (ParamWasReference)
3007 TDF |= TDF_ParamWithReferenceType;
3008 if (R.IsAddressOfOperand)
3009 TDF |= TDF_IgnoreQualifiers;
3010
John McCallc1f69982010-02-02 02:21:27 +00003011 // C++0x [temp.deduct.call]p6:
3012 // When P is a function type, pointer to function type, or pointer
3013 // to member function type:
3014
3015 if (!ParamType->isFunctionType() &&
3016 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003017 !ParamType->isMemberFunctionPointerType()) {
3018 if (Ovl->hasExplicitTemplateArgs()) {
3019 // But we can still look for an explicit specialization.
3020 if (FunctionDecl *ExplicitSpec
3021 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003022 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003023 }
John McCallc1f69982010-02-02 02:21:27 +00003024
George Burgess IVcc2f3552016-03-19 21:51:45 +00003025 DeclAccessPair DAP;
3026 if (FunctionDecl *Viable =
3027 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3028 return GetTypeOfFunction(S, R, Viable);
3029
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003030 return QualType();
3031 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003032
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003033 // Gather the explicit template arguments, if any.
3034 TemplateArgumentListInfo ExplicitTemplateArgs;
3035 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003036 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003037 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003038 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3039 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003040 NamedDecl *D = (*I)->getUnderlyingDecl();
3041
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003042 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3043 // - If the argument is an overload set containing one or more
3044 // function templates, the parameter is treated as a
3045 // non-deduced context.
3046 if (!Ovl->hasExplicitTemplateArgs())
3047 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003048
3049 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003050 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003051 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003052 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3053 Specialization, Info))
3054 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003055
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003056 D = Specialization;
3057 }
John McCallc1f69982010-02-02 02:21:27 +00003058
3059 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003060 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003061 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003062
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003063 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003065 ArgType->isFunctionType())
3066 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003067
John McCallc1f69982010-02-02 02:21:27 +00003068 // - If the argument is an overload set (not containing function
3069 // templates), trial argument deduction is attempted using each
3070 // of the members of the set. If deduction succeeds for only one
3071 // of the overload set members, that member is used as the
3072 // argument value for the deduction. If deduction succeeds for
3073 // more than one member of the overload set the parameter is
3074 // treated as a non-deduced context.
3075
3076 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3077 // Type deduction is done independently for each P/A pair, and
3078 // the deduced template argument values are then combined.
3079 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003080 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003081 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003082 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003083 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003084 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3085 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003086 if (Result) continue;
3087 if (!Match.isNull()) return QualType();
3088 Match = ArgType;
3089 }
3090
3091 return Match;
3092}
3093
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003095/// described in C++ [temp.deduct.call].
3096///
3097/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003098/// argument deduction based on this P/A pair because the argument is an
3099/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003100static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3101 TemplateParameterList *TemplateParams,
3102 QualType &ParamType,
3103 QualType &ArgType,
3104 Expr *Arg,
3105 unsigned &TDF) {
3106 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003107 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003108 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003109 if (ParamType.hasQualifiers())
3110 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003111
3112 // [...] If P is a reference type, the type referred to by P is
3113 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003114 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003115 if (ParamRefType)
3116 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003117
Nathan Sidwell96090022015-01-16 15:20:14 +00003118 // Overload sets usually make this parameter an undeduced context,
3119 // but there are sometimes special circumstances. Typically
3120 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003121 if (ArgType == S.Context.OverloadTy) {
3122 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3123 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003124 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003125 if (ArgType.isNull())
3126 return true;
3127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128
Douglas Gregor7825bf32011-01-06 22:09:01 +00003129 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003130 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003131 if (ArgType->isIncompleteArrayType()) {
3132 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003133 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003134 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003135
Douglas Gregor7825bf32011-01-06 22:09:01 +00003136 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003137 // If P is an rvalue reference to a cv-unqualified template
3138 // parameter and the argument is an lvalue, the type "lvalue
3139 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003140 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003141 !ParamType.getQualifiers() &&
3142 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003143 Arg->isLValue())
3144 ArgType = S.Context.getLValueReferenceType(ArgType);
3145 } else {
3146 // C++ [temp.deduct.call]p2:
3147 // If P is not a reference type:
3148 // - If A is an array type, the pointer type produced by the
3149 // array-to-pointer standard conversion (4.2) is used in place of
3150 // A for type deduction; otherwise,
3151 if (ArgType->isArrayType())
3152 ArgType = S.Context.getArrayDecayedType(ArgType);
3153 // - If A is a function type, the pointer type produced by the
3154 // function-to-pointer standard conversion (4.3) is used in place
3155 // of A for type deduction; otherwise,
3156 else if (ArgType->isFunctionType())
3157 ArgType = S.Context.getPointerType(ArgType);
3158 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003159 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003160 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003161 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003162 }
3163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor7825bf32011-01-06 22:09:01 +00003165 // C++0x [temp.deduct.call]p4:
3166 // In general, the deduction process attempts to find template argument
3167 // values that will make the deduced A identical to A (after the type A
3168 // is transformed as described above). [...]
3169 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170
Douglas Gregor7825bf32011-01-06 22:09:01 +00003171 // - If the original P is a reference type, the deduced A (i.e., the
3172 // type referred to by the reference) can be more cv-qualified than
3173 // the transformed A.
3174 if (ParamRefType)
3175 TDF |= TDF_ParamWithReferenceType;
3176 // - The transformed A can be another pointer or pointer to member
3177 // type that can be converted to the deduced A via a qualification
3178 // conversion (4.4).
3179 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3180 ArgType->isObjCObjectPointerType())
3181 TDF |= TDF_IgnoreQualifiers;
3182 // - If P is a class and P has the form simple-template-id, then the
3183 // transformed A can be a derived class of the deduced A. Likewise,
3184 // if P is a pointer to a class of the form simple-template-id, the
3185 // transformed A can be a pointer to a derived class pointed to by
3186 // the deduced A.
3187 if (isSimpleTemplateIdType(ParamType) ||
3188 (isa<PointerType>(ParamType) &&
3189 isSimpleTemplateIdType(
3190 ParamType->getAs<PointerType>()->getPointeeType())))
3191 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
Douglas Gregor7825bf32011-01-06 22:09:01 +00003193 return false;
3194}
3195
Nico Weberc153d242014-07-28 00:02:09 +00003196static bool
3197hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3198 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003199
Richard Smith707eab62017-01-05 04:08:31 +00003200static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Hubert Tong3280b332015-06-25 00:25:49 +00003201 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3202 Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003203 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3204 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3205 Optional<unsigned> ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003206
3207/// \brief Attempt template argument deduction from an initializer list
3208/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003209static Sema::TemplateDeductionResult DeduceFromInitializerList(
3210 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3211 InitListExpr *ILE, TemplateDeductionInfo &Info,
3212 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3213 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003214 // C++ [temp.deduct.call]p1: (CWG 1591)
3215 // If removing references and cv-qualifiers from P gives
3216 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3217 // a non-empty initializer list, then deduction is performed instead for
3218 // each element of the initializer list, taking P0 as a function template
3219 // parameter type and the initializer element as its argument
3220 //
Richard Smith707eab62017-01-05 04:08:31 +00003221 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003222 if (!ILE->getNumInits())
3223 return Sema::TDK_Success;
3224
Richard Smitha7d5ec92017-01-04 19:47:19 +00003225 QualType ElTy;
3226 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3227 if (ArrTy)
3228 ElTy = ArrTy->getElementType();
3229 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3230 // Otherwise, an initializer list argument causes the parameter to be
3231 // considered a non-deduced context
3232 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003233 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003234
Faisal Valif6dfdb32015-12-10 05:36:39 +00003235 // Deduction only needs to be done for dependent types.
3236 if (ElTy->isDependentType()) {
3237 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003238 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3239 S, TemplateParams, ElTy, E, Info, Deduced, OriginalCallArgs, None,
3240 TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003241 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003242 }
3243 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003244
3245 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3246 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003247 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003248 // Determine the array bound is something we can deduce.
3249 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003250 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003251 // We can perform template argument deduction for the given non-type
3252 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003253 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3254 ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003255 if (auto Result = DeduceNonTypeTemplateArgument(
3256 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
3257 /*ArrayBound=*/true, Info, Deduced))
3258 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003259 }
3260 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003261
3262 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003263}
3264
Richard Smith707eab62017-01-05 04:08:31 +00003265/// \brief Perform template argument deduction per [temp.deduct.call] for a
3266/// single parameter / argument pair.
3267static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3268 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3269 Expr *Arg, TemplateDeductionInfo &Info,
3270 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3271 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3272 Optional<unsigned> ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003273 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003274 QualType OrigParamType = ParamType;
3275
3276 // If P is a reference type [...]
3277 // If P is a cv-qualified type [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003278 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith363ae812017-01-04 22:03:59 +00003279 ArgType, Arg, TDF))
3280 return Sema::TDK_Success;
3281
Richard Smith707eab62017-01-05 04:08:31 +00003282 // If [...] the argument is a non-empty initializer list [...]
3283 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3284 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3285 Deduced, OriginalCallArgs, TDF);
3286
3287 // [...] the deduction process attempts to find template argument values
3288 // that will make the deduced A identical to A
3289 //
3290 // Keep track of the argument type and corresponding parameter index,
3291 // so we can check for compatibility between the deduced A and A.
3292 //
3293 // FIXME: We are supposed to perform this check for the P/A pairs we extract
3294 // from the initializer list case too.
3295 if (ArgIdx)
3296 OriginalCallArgs.push_back(
3297 Sema::OriginalCallArg(OrigParamType, *ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003298 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003299 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003300}
3301
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003302/// \brief Perform template argument deduction from a function call
3303/// (C++ [temp.deduct.call]).
3304///
3305/// \param FunctionTemplate the function template for which we are performing
3306/// template argument deduction.
3307///
James Dennett18348b62012-06-22 08:52:37 +00003308/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003309/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003310///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003311/// \param Args the function call arguments
3312///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003313/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003314/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003315/// template argument deduction.
3316///
3317/// \param Info the argument will be updated to provide additional information
3318/// about template argument deduction.
3319///
3320/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003321Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3322 FunctionTemplateDecl *FunctionTemplate,
3323 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003324 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Renato Golindad96d62017-01-02 11:15:42 +00003325 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003326 if (FunctionTemplate->isInvalidDecl())
3327 return TDK_Invalid;
3328
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003329 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003330 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003331
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003332 // C++ [temp.deduct.call]p1:
3333 // Template argument deduction is done by comparing each function template
3334 // parameter type (call it P) with the type of the corresponding argument
3335 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003336 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003337 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003339 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003340 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003341 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003342 if (Proto->isTemplateVariadic())
3343 /* Do nothing */;
3344 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003345 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003347 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003348 }
Mike Stump11289f42009-09-09 15:08:12 +00003349
Douglas Gregor89026b52009-06-30 23:57:56 +00003350 // The types of the parameters from which we will perform template argument
3351 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003352 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003353 TemplateParameterList *TemplateParams
3354 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003355 SmallVector<DeducedTemplateArgument, 4> Deduced;
3356 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003357 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003358 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003359 TemplateDeductionResult Result =
3360 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003361 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003362 Deduced,
3363 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003364 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003365 Info);
3366 if (Result)
3367 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003368
3369 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003370 } else {
3371 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003372 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003373 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3374 }
Mike Stump11289f42009-09-09 15:08:12 +00003375
Richard Smitha7d5ec92017-01-04 19:47:19 +00003376 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3377
3378 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3379 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003380 // C++ [demp.deduct.call]p1: (DR1391)
3381 // Template argument deduction is done by comparing each function template
3382 // parameter that contains template-parameters that participate in
3383 // template argument deduction ...
Richard Smitha7d5ec92017-01-04 19:47:19 +00003384 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3385 return Sema::TDK_Success;
3386
Richard Smith707eab62017-01-05 04:08:31 +00003387 // ... with the type of the corresponding argument
3388 return DeduceTemplateArgumentsFromCallArgument(
3389 *this, TemplateParams, ParamType, Args[ArgIdx], Info, Deduced,
3390 OriginalCallArgs, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003391 };
3392
Douglas Gregor89026b52009-06-30 23:57:56 +00003393 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003394 Deduced.resize(TemplateParams->size());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003395 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003396 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003397 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003398
Richard Smitha7d5ec92017-01-04 19:47:19 +00003399 const PackExpansionType *ParamExpansion =
3400 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003401 if (!ParamExpansion) {
3402 // Simple case: matching a function parameter to a function argument.
3403 if (ArgIdx >= CheckArgs)
3404 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405
Richard Smitha7d5ec92017-01-04 19:47:19 +00003406 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003407 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003408
Douglas Gregor7825bf32011-01-06 22:09:01 +00003409 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregor7825bf32011-01-06 22:09:01 +00003412 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413 // For a function parameter pack that occurs at the end of the
3414 // parameter-declaration-list, the type A of each remaining argument of
3415 // the call is compared with the type P of the declarator-id of the
3416 // function parameter pack. Each comparison deduces template arguments
3417 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003418 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003420 // the parameter pack is a non-deduced context.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003421 // FIXME: This does not say that subsequent parameters are also non-deduced.
3422 // See also DR1388 / DR1399, which effectively says we should keep deducing
3423 // after the pack.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003424 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003425 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Douglas Gregor7825bf32011-01-06 22:09:01 +00003427 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003428 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3429 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430
Richard Smitha7d5ec92017-01-04 19:47:19 +00003431 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx)
3432 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3433 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434
Douglas Gregor7825bf32011-01-06 22:09:01 +00003435 // Build argument packs for each of the parameter packs expanded by this
3436 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003437 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003439
Douglas Gregor7825bf32011-01-06 22:09:01 +00003440 // After we've matching against a parameter pack, we're done.
3441 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003442 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003443
Mike Stump11289f42009-09-09 15:08:12 +00003444 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003445 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003446 Info, &OriginalCallArgs,
Renato Golindad96d62017-01-02 11:15:42 +00003447 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003448}
3449
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003450QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003451 QualType FunctionType,
3452 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003453 if (ArgFunctionType.isNull())
3454 return ArgFunctionType;
3455
3456 const FunctionProtoType *FunctionTypeP =
3457 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003458 const FunctionProtoType *ArgFunctionTypeP =
3459 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003460
3461 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3462 bool Rebuild = false;
3463
3464 CallingConv CC = FunctionTypeP->getCallConv();
3465 if (EPI.ExtInfo.getCC() != CC) {
3466 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3467 Rebuild = true;
3468 }
3469
3470 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3471 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3472 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3473 Rebuild = true;
3474 }
3475
3476 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3477 ArgFunctionTypeP->hasExceptionSpec())) {
3478 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3479 Rebuild = true;
3480 }
3481
3482 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003483 return ArgFunctionType;
3484
Richard Smithbaa47832016-12-01 02:11:49 +00003485 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3486 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003487}
3488
Douglas Gregor9b146582009-07-08 20:55:45 +00003489/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003490/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3491/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003492///
3493/// \param FunctionTemplate the function template for which we are performing
3494/// template argument deduction.
3495///
James Dennett18348b62012-06-22 08:52:37 +00003496/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003497/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003498///
3499/// \param ArgFunctionType the function type that will be used as the
3500/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003501/// function template's function type. This type may be NULL, if there is no
3502/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003503///
3504/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003505/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003506/// template argument deduction.
3507///
3508/// \param Info the argument will be updated to provide additional information
3509/// about template argument deduction.
3510///
Richard Smithbaa47832016-12-01 02:11:49 +00003511/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3512/// the address of a function template per [temp.deduct.funcaddr] and
3513/// [over.over]. If \c false, we are looking up a function template
3514/// specialization based on its signature, per [temp.deduct.decl].
3515///
Douglas Gregor9b146582009-07-08 20:55:45 +00003516/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003517Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3518 FunctionTemplateDecl *FunctionTemplate,
3519 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3520 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3521 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003522 if (FunctionTemplate->isInvalidDecl())
3523 return TDK_Invalid;
3524
Douglas Gregor9b146582009-07-08 20:55:45 +00003525 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3526 TemplateParameterList *TemplateParams
3527 = FunctionTemplate->getTemplateParameters();
3528 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003529
3530 // When taking the address of a function, we require convertibility of
3531 // the resulting function type. Otherwise, we allow arbitrary mismatches
3532 // of calling convention, noreturn, and noexcept.
3533 if (!IsAddressOfFunction)
3534 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3535 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003536
Douglas Gregor9b146582009-07-08 20:55:45 +00003537 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003538 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003539 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003540 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003541 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003542 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003543 if (TemplateDeductionResult Result
3544 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003545 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003546 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003547 &FunctionType, Info))
3548 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003549
3550 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003551 }
3552
Eli Friedman77dcc722012-02-08 03:07:05 +00003553 // Unevaluated SFINAE context.
3554 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003555 SFINAETrap Trap(*this);
3556
John McCallc1f69982010-02-02 02:21:27 +00003557 Deduced.resize(TemplateParams->size());
3558
Richard Smith2a7d4812013-05-04 07:00:32 +00003559 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003560 // type so that we treat it as a non-deduced context in what follows. If we
3561 // are looking up by signature, the signature type should also have a deduced
3562 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003563 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003564 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003565 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003566 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003567 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003568 }
3569
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003570 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003571 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003572 if (IsAddressOfFunction)
3573 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003574 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003575 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003576 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003577 FunctionType, ArgFunctionType,
3578 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003579 return Result;
3580 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003581
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003583 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3584 NumExplicitlySpecified,
3585 Specialization, Info))
3586 return Result;
3587
Richard Smith2a7d4812013-05-04 07:00:32 +00003588 // If the function has a deduced return type, deduce it now, so we can check
3589 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003590 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003591 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003592 DeduceReturnType(Specialization, Info.getLocation(), false))
3593 return TDK_MiscellaneousDeductionFailure;
3594
Richard Smith9095e5b2016-11-01 01:31:23 +00003595 // If the function has a dependent exception specification, resolve it now,
3596 // so we can check that the exception specification matches.
3597 auto *SpecializationFPT =
3598 Specialization->getType()->castAs<FunctionProtoType>();
3599 if (getLangOpts().CPlusPlus1z &&
3600 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3601 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3602 return TDK_MiscellaneousDeductionFailure;
3603
Richard Smithbaa47832016-12-01 02:11:49 +00003604 // Adjust the exception specification of the argument again to match the
3605 // substituted and resolved type we just formed. (Calling convention and
3606 // noreturn can't be dependent, so we don't actually need this for them
3607 // right now.)
3608 QualType SpecializationType = Specialization->getType();
3609 if (!IsAddressOfFunction)
3610 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3611 /*AdjustExceptionSpec*/true);
3612
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003613 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003614 // specialization with respect to arguments of compatible pointer to function
3615 // types, template argument deduction fails.
3616 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003617 if (IsAddressOfFunction &&
3618 !isSameOrCompatibleFunctionType(
3619 Context.getCanonicalType(SpecializationType),
3620 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003621 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003622
3623 if (!IsAddressOfFunction &&
3624 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003625 return TDK_MiscellaneousDeductionFailure;
3626 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003627
3628 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003629}
3630
Simon Pilgrim728134c2016-08-12 11:43:57 +00003631/// \brief Given a function declaration (e.g. a generic lambda conversion
3632/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003633/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3634/// to replace 'auto' with and not the actual result type you want
3635/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003636static inline void
3637SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003638 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003639 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003640 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003641 assert(AutoResultType->getContainedAutoType());
3642 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003643 TypeToReplaceAutoWith);
3644 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3645}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003646
Simon Pilgrim728134c2016-08-12 11:43:57 +00003647/// \brief Given a specialized conversion operator of a generic lambda
3648/// create the corresponding specializations of the call operator and
3649/// the static-invoker. If the return type of the call operator is auto,
3650/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003651/// return type of the destination function ptr.
3652
Simon Pilgrim728134c2016-08-12 11:43:57 +00003653static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003654SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3655 CXXConversionDecl *ConversionSpecialized,
3656 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3657 QualType ReturnTypeOfDestFunctionPtr,
3658 TemplateDeductionInfo &TDInfo,
3659 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003660
Faisal Vali2b3a3012013-10-24 23:40:02 +00003661 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003662 assert(LambdaClass && LambdaClass->isGenericLambda());
3663
Faisal Vali2b3a3012013-10-24 23:40:02 +00003664 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003665 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003666 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003667 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003668
3669 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003670 CallOpGeneric->getDescribedFunctionTemplate();
3671
Craig Topperc3ec1492014-05-26 06:22:03 +00003672 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003673 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003674 // generic lambda's call operator.
3675 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003676 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3677 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003678 0, CallOpSpecialized, TDInfo))
3679 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003680
Faisal Vali2b3a3012013-10-24 23:40:02 +00003681 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003682 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3683 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003684 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003685 CallOpSpecialized->getPointOfInstantiation(),
3686 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003687
Faisal Vali2b3a3012013-10-24 23:40:02 +00003688 // Check to see if the return type of the destination ptr-to-function
3689 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003690 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003691 ReturnTypeOfDestFunctionPtr))
3692 return Sema::TDK_NonDeducedMismatch;
3693 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003694 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003695 // specialized our corresponding call operator, we are ready to
3696 // specialize the static invoker with the deduced arguments of our
3697 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003698 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003699 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3700 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3701
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003702#ifndef NDEBUG
3703 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3704#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003705 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003706 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003707 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003708 "If the call operator succeeded so should the invoker!");
3709 // Set the result type to match the corresponding call operator
3710 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003711 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3712 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003713 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003714 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003715 // to substitute into the 'auto' of the invoker and conversion
3716 // function.
3717 // For e.g.
3718 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3719 // We don't want to subst 'int*' into 'auto' to get int**.
3720
Alp Toker314cc812014-01-25 16:55:45 +00003721 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3722 ->getContainedAutoType()
3723 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003724 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3725 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003726 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003727 TypeToReplaceAutoWith, S);
3728 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003729
Faisal Vali2b3a3012013-10-24 23:40:02 +00003730 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003731 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003732 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003733 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003734 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3735 getType().getTypePtr()->castAs<FunctionProtoType>();
3736 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3737 EPI.TypeQuals = 0;
3738 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003739 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003740 return Sema::TDK_Success;
3741}
Douglas Gregor05155d82009-08-21 23:19:43 +00003742/// \brief Deduce template arguments for a templated conversion
3743/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3744/// conversion function template specialization.
3745Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003746Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003747 QualType ToType,
3748 CXXConversionDecl *&Specialization,
3749 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003750 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003751 return TDK_Invalid;
3752
Faisal Vali2b3a3012013-10-24 23:40:02 +00003753 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003754 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3755
Faisal Vali2b3a3012013-10-24 23:40:02 +00003756 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003757
3758 // Canonicalize the types for deduction.
3759 QualType P = Context.getCanonicalType(FromType);
3760 QualType A = Context.getCanonicalType(ToType);
3761
Douglas Gregord99609a2011-03-06 09:03:20 +00003762 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003763 // If P is a reference type, the type referred to by P is used for
3764 // type deduction.
3765 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3766 P = PRef->getPointeeType();
3767
Douglas Gregord99609a2011-03-06 09:03:20 +00003768 // C++0x [temp.deduct.conv]p4:
3769 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003770 // for type deduction.
3771 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003772 A = ARef->getPointeeType().getUnqualifiedType();
3773 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003774 //
Mike Stump11289f42009-09-09 15:08:12 +00003775 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003776 else {
3777 assert(!A->isReferenceType() && "Reference types were handled above");
3778
3779 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003780 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003781 // of P for type deduction; otherwise,
3782 if (P->isArrayType())
3783 P = Context.getArrayDecayedType(P);
3784 // - If P is a function type, the pointer type produced by the
3785 // function-to-pointer standard conversion (4.3) is used in
3786 // place of P for type deduction; otherwise,
3787 else if (P->isFunctionType())
3788 P = Context.getPointerType(P);
3789 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003790 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003791 else
3792 P = P.getUnqualifiedType();
3793
Douglas Gregord99609a2011-03-06 09:03:20 +00003794 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003795 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003796 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003797 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003798 A = A.getUnqualifiedType();
3799 }
3800
Eli Friedman77dcc722012-02-08 03:07:05 +00003801 // Unevaluated SFINAE context.
3802 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003803 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003804
3805 // C++ [temp.deduct.conv]p1:
3806 // Template argument deduction is done by comparing the return
3807 // type of the template conversion function (call it P) with the
3808 // type that is required as the result of the conversion (call it
3809 // A) as described in 14.8.2.4.
3810 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003811 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003812 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003813 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003814
3815 // C++0x [temp.deduct.conv]p4:
3816 // In general, the deduction process attempts to find template
3817 // argument values that will make the deduced A identical to
3818 // A. However, there are two cases that allow a difference:
3819 unsigned TDF = 0;
3820 // - If the original A is a reference type, A can be more
3821 // cv-qualified than the deduced A (i.e., the type referred to
3822 // by the reference)
3823 if (ToType->isReferenceType())
3824 TDF |= TDF_ParamWithReferenceType;
3825 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003826 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003827 // conversion.
3828 //
3829 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3830 // both P and A are pointers or member pointers. In this case, we
3831 // just ignore cv-qualifiers completely).
3832 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003833 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003834 TDF |= TDF_IgnoreQualifiers;
3835 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003836 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3837 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003838 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003839
3840 // Create an Instantiation Scope for finalizing the operator.
3841 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003842 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003844 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003845 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003846 ConversionSpecialized, Info);
3847 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3848
3849 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003850 // to a ptr-to-function, use the deduced arguments from the conversion
3851 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003852 // e.g., int (*fp)(int) = [](auto a) { return a; };
3853 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003854
Faisal Vali2b3a3012013-10-24 23:40:02 +00003855 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003856 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003857 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003858 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003859 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003860 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003861 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003862 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3863
Simon Pilgrim728134c2016-08-12 11:43:57 +00003864 // Create the corresponding specializations of the call operator and
3865 // the static-invoker; and if the return type is auto,
3866 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003867 // DestFunctionPtrReturnType.
3868 // For instance:
3869 // auto L = [](auto a) { return f(a); };
3870 // int (*fp)(int) = L;
3871 // char (*fp2)(int) = L; <-- Not OK.
3872
3873 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003874 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003875 Info, *this);
3876 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003877 return Result;
3878}
3879
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003880/// \brief Deduce template arguments for a function template when there is
3881/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3882///
3883/// \param FunctionTemplate the function template for which we are performing
3884/// template argument deduction.
3885///
James Dennett18348b62012-06-22 08:52:37 +00003886/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003887/// arguments.
3888///
3889/// \param Specialization if template argument deduction was successful,
3890/// this will be set to the function template specialization produced by
3891/// template argument deduction.
3892///
3893/// \param Info the argument will be updated to provide additional information
3894/// about template argument deduction.
3895///
Richard Smithbaa47832016-12-01 02:11:49 +00003896/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3897/// the address of a function template in a context where we do not have a
3898/// target type, per [over.over]. If \c false, we are looking up a function
3899/// template specialization based on its signature, which only happens when
3900/// deducing a function parameter type from an argument that is a template-id
3901/// naming a function template specialization.
3902///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003903/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003904Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3905 FunctionTemplateDecl *FunctionTemplate,
3906 TemplateArgumentListInfo *ExplicitTemplateArgs,
3907 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3908 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003909 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003910 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003911 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003912}
3913
Richard Smith30482bc2011-02-20 03:19:35 +00003914namespace {
3915 /// Substitute the 'auto' type specifier within a type for a given replacement
3916 /// type.
3917 class SubstituteAutoTransform :
3918 public TreeTransform<SubstituteAutoTransform> {
3919 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003920 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003921 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003922 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3923 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003924 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003925 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003926
Richard Smith30482bc2011-02-20 03:19:35 +00003927 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3928 // If we're building the type pattern to deduce against, don't wrap the
3929 // substituted type in an AutoType. Certain template deduction rules
3930 // apply only when a template type parameter appears directly (and not if
3931 // the parameter is found through desugaring). For instance:
3932 // auto &&lref = lvalue;
3933 // must transform into "rvalue reference to T" not "rvalue reference to
3934 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003935 if (!UseAutoSugar) {
3936 assert(isa<TemplateTypeParmType>(Replacement) &&
3937 "unexpected unsugared replacement kind");
Richard Smith30482bc2011-02-20 03:19:35 +00003938 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003939 TemplateTypeParmTypeLoc NewTL =
3940 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003941 NewTL.setNameLoc(TL.getNameLoc());
3942 return Result;
3943 } else {
Richard Smith87d263e2016-12-25 08:05:23 +00003944 QualType Result = SemaRef.Context.getAutoType(
3945 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00003946 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3947 NewTL.setNameLoc(TL.getNameLoc());
3948 return Result;
3949 }
3950 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003951
3952 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3953 // Lambdas never need to be transformed.
3954 return E;
3955 }
Richard Smith061f1e22013-04-30 21:23:01 +00003956
Richard Smith2a7d4812013-05-04 07:00:32 +00003957 QualType Apply(TypeLoc TL) {
3958 // Create some scratch storage for the transformed type locations.
3959 // FIXME: We're just going to throw this information away. Don't build it.
3960 TypeLocBuilder TLB;
3961 TLB.reserve(TL.getFullDataSize());
3962 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003963 }
Richard Smith30482bc2011-02-20 03:19:35 +00003964 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003965}
Richard Smith30482bc2011-02-20 03:19:35 +00003966
Richard Smith2a7d4812013-05-04 07:00:32 +00003967Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003968Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
3969 Optional<unsigned> DependentDeductionDepth) {
3970 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
3971 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00003972}
3973
Richard Smith061f1e22013-04-30 21:23:01 +00003974/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003975///
Richard Smith87d263e2016-12-25 08:05:23 +00003976/// Note that this is done even if the initializer is dependent. (This is
3977/// necessary to support partial ordering of templates using 'auto'.)
3978/// A dependent type will be produced when deducing from a dependent type.
3979///
Richard Smith30482bc2011-02-20 03:19:35 +00003980/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003981/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003982/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003983/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00003984/// \param DependentDeductionDepth Set if we should permit deduction in
3985/// dependent cases. This is necessary for template partial ordering with
3986/// 'auto' template parameters. The value specified is the template
3987/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00003988Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003989Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
3990 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00003991 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003992 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3993 if (NonPlaceholder.isInvalid())
3994 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003995 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003996 }
3997
Richard Smith87d263e2016-12-25 08:05:23 +00003998 if (!DependentDeductionDepth &&
3999 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4000 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004001 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004002 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004003 }
4004
Richard Smith87d263e2016-12-25 08:05:23 +00004005 // Find the depth of template parameter to synthesize.
4006 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4007
Richard Smith74aeef52013-04-26 16:15:35 +00004008 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4009 // Since 'decltype(auto)' can only occur at the top of the type, we
4010 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004011 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004012 if (AT->isDecltypeAuto()) {
4013 if (isa<InitListExpr>(Init)) {
4014 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4015 return DAR_FailedAlreadyDiagnosed;
4016 }
4017
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004018 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004019 if (Deduced.isNull())
4020 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004021 // FIXME: Support a non-canonical deduced type for 'auto'.
4022 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004023 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004024 if (Result.isNull())
4025 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004026 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004027 } else if (!getLangOpts().CPlusPlus) {
4028 if (isa<InitListExpr>(Init)) {
4029 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4030 return DAR_FailedAlreadyDiagnosed;
4031 }
Richard Smith74aeef52013-04-26 16:15:35 +00004032 }
4033 }
4034
Richard Smith30482bc2011-02-20 03:19:35 +00004035 SourceLocation Loc = Init->getExprLoc();
4036
4037 LocalInstantiationScope InstScope(*this);
4038
4039 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004040 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4041 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004042 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4043 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004044 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4045 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004046
Richard Smith87d263e2016-12-25 08:05:23 +00004047 QualType FuncParam =
4048 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4049 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004050 assert(!FuncParam.isNull() &&
4051 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004052
4053 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004054 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004055 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004056
Richard Smith87d263e2016-12-25 08:05:23 +00004057 TemplateDeductionInfo Info(Loc, Depth);
4058
4059 // If deduction failed, don't diagnose if the initializer is dependent; it
4060 // might acquire a matching type in the instantiation.
4061 auto DeductionFailed = [&]() -> DeduceAutoResult {
4062 if (Init->isTypeDependent()) {
4063 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4064 assert(!Result.isNull() && "substituting DependentTy can't fail");
4065 return DAR_Succeeded;
4066 }
4067 return DAR_Failed;
4068 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004069
Richard Smith707eab62017-01-05 04:08:31 +00004070 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4071
Richard Smith74801c82012-07-08 04:13:07 +00004072 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004073 if (InitList) {
4074 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004075 if (DeduceTemplateArgumentsFromCallArgument(
4076 *this, TemplateParamsSt.get(), TemplArg, InitList->getInit(i),
4077 Info, Deduced, OriginalCallArgs, None, /*TDF*/0))
Richard Smith87d263e2016-12-25 08:05:23 +00004078 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004079 }
4080 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004081 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4082 Diag(Loc, diag::err_auto_bitfield);
4083 return DAR_FailedAlreadyDiagnosed;
4084 }
4085
Richard Smith707eab62017-01-05 04:08:31 +00004086 if (DeduceTemplateArgumentsFromCallArgument(
4087 *this, TemplateParamsSt.get(), FuncParam, Init, Info, Deduced,
4088 OriginalCallArgs, /*ArgIdx*/0, /*TDF*/0))
Richard Smith87d263e2016-12-25 08:05:23 +00004089 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004090 }
Richard Smith30482bc2011-02-20 03:19:35 +00004091
Richard Smith87d263e2016-12-25 08:05:23 +00004092 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004093 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004094 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004095
Eli Friedmane4310952012-11-06 23:56:42 +00004096 QualType DeducedType = Deduced[0].getAsType();
4097
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004098 if (InitList) {
4099 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4100 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004101 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004102 }
4103
Richard Smith061f1e22013-04-30 21:23:01 +00004104 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004105 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004106 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004107
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004108 // Check that the deduced argument type is compatible with the original
4109 // argument type per C++ [temp.deduct.call]p4.
Richard Smith707eab62017-01-05 04:08:31 +00004110 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4111 if (CheckOriginalCallArgDeduction(*this, OriginalArg, Result)) {
4112 Result = QualType();
4113 return DeductionFailed();
4114 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004115 }
4116
Sebastian Redl09edce02012-01-23 22:09:39 +00004117 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004118}
4119
Simon Pilgrim728134c2016-08-12 11:43:57 +00004120QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004121 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004122 if (TypeToReplaceAuto->isDependentType())
4123 TypeToReplaceAuto = QualType();
4124 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4125 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004126}
4127
Simon Pilgrim728134c2016-08-12 11:43:57 +00004128TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004129 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004130 if (TypeToReplaceAuto->isDependentType())
4131 TypeToReplaceAuto = QualType();
4132 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4133 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004134}
4135
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004136void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4137 if (isa<InitListExpr>(Init))
4138 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004139 VDecl->isInitCapture()
4140 ? diag::err_init_capture_deduction_failure_from_init_list
4141 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004142 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4143 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004144 Diag(VDecl->getLocation(),
4145 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4146 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004147 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4148 << Init->getSourceRange();
4149}
4150
Richard Smith2a7d4812013-05-04 07:00:32 +00004151bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4152 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004153 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004154
4155 if (FD->getTemplateInstantiationPattern())
4156 InstantiateFunctionDefinition(Loc, FD);
4157
Alp Toker314cc812014-01-25 16:55:45 +00004158 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004159 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4160 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4161 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4162 }
4163
4164 return StillUndeduced;
4165}
4166
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004167static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004168MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004169 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004170 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004171 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
4173/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004174static void
4175AddImplicitObjectParameterType(ASTContext &Context,
4176 CXXMethodDecl *Method,
4177 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004178 // C++11 [temp.func.order]p3:
4179 // [...] The new parameter is of type "reference to cv A," where cv are
4180 // the cv-qualifiers of the function template (if any) and A is
4181 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004182 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004183 // The standard doesn't say explicitly, but we pick the appropriate kind of
4184 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004185 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4186 ArgTy = Context.getQualifiedType(ArgTy,
4187 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004188 if (Method->getRefQualifier() == RQ_RValue)
4189 ArgTy = Context.getRValueReferenceType(ArgTy);
4190 else
4191 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004192 ArgTypes.push_back(ArgTy);
4193}
4194
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004195/// \brief Determine whether the function template \p FT1 is at least as
4196/// specialized as \p FT2.
4197static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004198 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004199 FunctionTemplateDecl *FT1,
4200 FunctionTemplateDecl *FT2,
4201 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004202 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004203 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004205 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4206 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004208 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4209 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004210 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004211 Deduced.resize(TemplateParams->size());
4212
4213 // C++0x [temp.deduct.partial]p3:
4214 // The types used to determine the ordering depend on the context in which
4215 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004216 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004217 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004218 switch (TPOC) {
4219 case TPOC_Call: {
4220 // - In the context of a function call, the function parameter types are
4221 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004222 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4223 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004224
Eli Friedman3b5774a2012-09-19 23:27:04 +00004225 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004226 // [...] If only one of the function templates is a non-static
4227 // member, that function template is considered to have a new
4228 // first parameter inserted in its function parameter list. The
4229 // new parameter is of type "reference to cv A," where cv are
4230 // the cv-qualifiers of the function template (if any) and A is
4231 // the class of which the function template is a member.
4232 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004233 // Note that we interpret this to mean "if one of the function
4234 // templates is a non-static member and the other is a non-member";
4235 // otherwise, the ordering rules for static functions against non-static
4236 // functions don't make any sense.
4237 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004238 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4239 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004240 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004241
Richard Smithe5b52202013-09-11 00:52:39 +00004242 unsigned NumComparedArguments = NumCallArguments1;
4243
4244 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004245 // Compare 'this' from Method1 against first parameter from Method2.
4246 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4247 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004248 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004249 // Compare 'this' from Method2 against first parameter from Method1.
4250 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004251 }
4252
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004253 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004254 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004255 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004256 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257
Douglas Gregorb837ea42011-01-11 17:34:58 +00004258 // C++ [temp.func.order]p5:
4259 // The presence of unused ellipsis and default arguments has no effect on
4260 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004261 if (Args1.size() > NumComparedArguments)
4262 Args1.resize(NumComparedArguments);
4263 if (Args2.size() > NumComparedArguments)
4264 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004265 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4266 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004267 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004268 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004270 break;
4271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004273 case TPOC_Conversion:
4274 // - In the context of a call to a conversion operator, the return types
4275 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004276 if (DeduceTemplateArgumentsByTypeMatch(
4277 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4278 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004279 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004280 return false;
4281 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004283 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004284 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004285 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004286 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4287 FD2->getType(), FD1->getType(),
4288 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004289 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004290 return false;
4291 break;
4292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004294 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295 // In most cases, all template parameters must have values in order for
4296 // deduction to succeed, but for partial ordering purposes a template
4297 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004298 // types being used for partial ordering. [ Note: a template parameter used
4299 // in a non-deduced context is considered used. -end note]
4300 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4301 for (; ArgIdx != NumArgs; ++ArgIdx)
4302 if (Deduced[ArgIdx].isNull())
4303 break;
4304
Richard Smithcf824862016-12-30 04:32:02 +00004305 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4306 // to substitute the deduced arguments back into the template and check that
4307 // we get the right type.
4308
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004309 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004311 // as FT2.
4312 return true;
4313 }
4314
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004315 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004316 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004317 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004318 case TPOC_Call:
4319 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4320 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004321 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004322 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004323 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004325 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004326 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4327 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004328 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004330 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004331 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004332 TemplateParams->getDepth(),
4333 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004334 break;
4335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004337 for (; ArgIdx != NumArgs; ++ArgIdx)
4338 // If this argument had no value deduced but was used in one of the types
4339 // used for partial ordering, then deduction fails.
4340 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4341 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004343 return true;
4344}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
Douglas Gregorcef1a032011-01-16 16:03:23 +00004346/// \brief Determine whether this a function template whose parameter-type-list
4347/// ends with a function parameter pack.
4348static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4349 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4350 unsigned NumParams = Function->getNumParams();
4351 if (NumParams == 0)
4352 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353
Douglas Gregorcef1a032011-01-16 16:03:23 +00004354 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4355 if (!Last->isParameterPack())
4356 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregorcef1a032011-01-16 16:03:23 +00004358 // Make sure that no previous parameter is a parameter pack.
4359 while (--NumParams > 0) {
4360 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4361 return false;
4362 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004363
Douglas Gregorcef1a032011-01-16 16:03:23 +00004364 return true;
4365}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366
Douglas Gregorbe999392009-09-15 16:23:51 +00004367/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004368/// to the rules of function template partial ordering (C++ [temp.func.order]).
4369///
4370/// \param FT1 the first function template
4371///
4372/// \param FT2 the second function template
4373///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004374/// \param TPOC the context in which we are performing partial ordering of
4375/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004376///
Richard Smithe5b52202013-09-11 00:52:39 +00004377/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4378/// only when \c TPOC is \c TPOC_Call.
4379///
4380/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4381/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004382///
Douglas Gregorbe999392009-09-15 16:23:51 +00004383/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004384/// template is more specialized, returns NULL.
4385FunctionTemplateDecl *
4386Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4387 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004388 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004389 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004390 unsigned NumCallArguments1,
4391 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004393 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004395 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004397 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004398 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004400 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004401 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004402
Douglas Gregorcef1a032011-01-16 16:03:23 +00004403 // FIXME: This mimics what GCC implements, but doesn't match up with the
4404 // proposed resolution for core issue 692. This area needs to be sorted out,
4405 // but for now we attempt to maintain compatibility.
4406 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4407 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4408 if (Variadic1 != Variadic2)
4409 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Craig Topperc3ec1492014-05-26 06:22:03 +00004411 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004412}
Douglas Gregor9b146582009-07-08 20:55:45 +00004413
Douglas Gregor450f00842009-09-25 18:43:00 +00004414/// \brief Determine if the two templates are equivalent.
4415static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4416 if (T1 == T2)
4417 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418
Douglas Gregor450f00842009-09-25 18:43:00 +00004419 if (!T1 || !T2)
4420 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421
Douglas Gregor450f00842009-09-25 18:43:00 +00004422 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4423}
4424
4425/// \brief Retrieve the most specialized of the given function template
4426/// specializations.
4427///
John McCall58cc69d2010-01-27 01:50:18 +00004428/// \param SpecBegin the start iterator of the function template
4429/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004430///
John McCall58cc69d2010-01-27 01:50:18 +00004431/// \param SpecEnd the end iterator of the function template
4432/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004433///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004435/// diagnostic should occur.
4436///
4437/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4438/// no matching candidates.
4439///
4440/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4441/// occurs.
4442///
4443/// \param CandidateDiag partial diagnostic used for each function template
4444/// specialization that is a candidate in the ambiguous ordering. One parameter
4445/// in this diagnostic should be unbound, which will correspond to the string
4446/// describing the template arguments for the function template specialization.
4447///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004449/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004450UnresolvedSetIterator Sema::getMostSpecialized(
4451 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4452 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004453 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4454 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4455 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004456 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004457 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004458 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004459 FailedCandidates.NoteCandidates(*this, Loc);
4460 }
John McCall58cc69d2010-01-27 01:50:18 +00004461 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
4464 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004465 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466
Douglas Gregor450f00842009-09-25 18:43:00 +00004467 // Find the function template that is better than all of the templates it
4468 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004469 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004471 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004472 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004473 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4474 FunctionTemplateDecl *Challenger
4475 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004476 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004477 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004478 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004479 Challenger)) {
4480 Best = I;
4481 BestTemplate = Challenger;
4482 }
4483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004484
Douglas Gregor450f00842009-09-25 18:43:00 +00004485 // Make sure that the "best" function template is more specialized than all
4486 // of the others.
4487 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004488 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4489 FunctionTemplateDecl *Challenger
4490 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004491 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004493 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004494 BestTemplate)) {
4495 Ambiguous = true;
4496 break;
4497 }
4498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregor450f00842009-09-25 18:43:00 +00004500 if (!Ambiguous) {
4501 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004502 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
Douglas Gregor450f00842009-09-25 18:43:00 +00004505 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004506 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004507 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508
Richard Smithb875c432013-05-04 01:51:08 +00004509 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004510 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4511 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004512 const auto *FD = cast<FunctionDecl>(*I);
4513 PD << FD << getTemplateArgumentBindingsText(
4514 FD->getPrimaryTemplate()->getTemplateParameters(),
4515 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004516 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004517 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004518 Diag((*I)->getLocation(), PD);
4519 }
Richard Smithb875c432013-05-04 01:51:08 +00004520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
John McCall58cc69d2010-01-27 01:50:18 +00004522 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004523}
4524
Richard Smith0da6dc42016-12-24 16:40:51 +00004525/// Determine whether one partial specialization, P1, is at least as
4526/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004527///
Richard Smith26b86ea2016-12-31 21:41:23 +00004528/// \tparam TemplateLikeDecl The kind of P2, which must be a
4529/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004530/// \param T1 The injected-class-name of P1 (faked for a variable template).
4531/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004532template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004533static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004534 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004535 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004536 // C++ [temp.class.order]p1:
4537 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538 // specialized as the second if, given the following rewrite to two
4539 // function templates, the first function template is at least as
4540 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004541 // templates (14.6.6.2):
4542 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543 // first partial specialization and has a single function parameter
4544 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004545 // arguments of the first partial specialization, and
4546 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547 // second partial specialization and has a single function parameter
4548 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004549 // arguments of the second partial specialization.
4550 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004551 // Rather than synthesize function templates, we merely perform the
4552 // equivalent partial ordering by performing deduction directly on
4553 // the template arguments of the class template partial
4554 // specializations. This computation is slightly simpler than the
4555 // general problem of function template partial ordering, because
4556 // class template partial specializations are more constrained. We
4557 // know that every template parameter is deducible from the class
4558 // template partial specialization's template arguments, for
4559 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004560 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004561
Richard Smith0da6dc42016-12-24 16:40:51 +00004562 // Determine whether P1 is at least as specialized as P2.
4563 Deduced.resize(P2->getTemplateParameters()->size());
4564 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4565 T2, T1, Info, Deduced, TDF_None,
4566 /*PartialOrdering=*/true))
4567 return false;
4568
4569 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4570 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004571 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4572 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004573 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4574 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004575 S, P2, /*PartialOrdering=*/true,
4576 TemplateArgumentList(TemplateArgumentList::OnStack,
4577 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004578 Deduced, Info))
4579 return false;
4580
4581 return true;
4582}
4583
4584/// \brief Returns the more specialized class template partial specialization
4585/// according to the rules of partial ordering of class template partial
4586/// specializations (C++ [temp.class.order]).
4587///
4588/// \param PS1 the first class template partial specialization
4589///
4590/// \param PS2 the second class template partial specialization
4591///
4592/// \returns the more specialized class template partial specialization. If
4593/// neither partial specialization is more specialized, returns NULL.
4594ClassTemplatePartialSpecializationDecl *
4595Sema::getMoreSpecializedPartialSpecialization(
4596 ClassTemplatePartialSpecializationDecl *PS1,
4597 ClassTemplatePartialSpecializationDecl *PS2,
4598 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004599 QualType PT1 = PS1->getInjectedSpecializationType();
4600 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601
Richard Smith0e617ec2016-12-27 07:56:27 +00004602 TemplateDeductionInfo Info(Loc);
4603 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4604 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004605
4606 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004607 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004608
4609 return Better1 ? PS1 : PS2;
4610}
4611
Richard Smith0e617ec2016-12-27 07:56:27 +00004612bool Sema::isMoreSpecializedThanPrimary(
4613 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4614 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4615 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4616 QualType PartialT = Spec->getInjectedSpecializationType();
4617 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4618 return false;
4619 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4620 Info.clearSFINAEDiagnostic();
4621 return false;
4622 }
4623 return true;
4624}
4625
Larisse Voufo39a1e502013-08-06 01:03:05 +00004626VarTemplatePartialSpecializationDecl *
4627Sema::getMoreSpecializedPartialSpecialization(
4628 VarTemplatePartialSpecializationDecl *PS1,
4629 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004630 // Pretend the variable template specializations are class template
4631 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004632 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004633 "the partial specializations being compared should specialize"
4634 " the same template.");
4635 TemplateName Name(PS1->getSpecializedTemplate());
4636 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4637 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004638 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004639 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004640 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004641
Richard Smith0e617ec2016-12-27 07:56:27 +00004642 TemplateDeductionInfo Info(Loc);
4643 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4644 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645
Douglas Gregorbe999392009-09-15 16:23:51 +00004646 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004647 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648
Richard Smith0da6dc42016-12-24 16:40:51 +00004649 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004650}
4651
Richard Smith0e617ec2016-12-27 07:56:27 +00004652bool Sema::isMoreSpecializedThanPrimary(
4653 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4654 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4655 // FIXME: Cache the injected template arguments rather than recomputing
4656 // them for each partial specialization.
4657 SmallVector<TemplateArgument, 8> PrimaryArgs;
4658 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4659 PrimaryArgs);
4660
4661 TemplateName CanonTemplate =
4662 Context.getCanonicalTemplateName(TemplateName(Primary));
4663 QualType PrimaryT = Context.getTemplateSpecializationType(
4664 CanonTemplate, PrimaryArgs);
4665 QualType PartialT = Context.getTemplateSpecializationType(
4666 CanonTemplate, Spec->getTemplateArgs().asArray());
4667 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4668 return false;
4669 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4670 Info.clearSFINAEDiagnostic();
4671 return false;
4672 }
4673 return true;
4674}
4675
Richard Smith26b86ea2016-12-31 21:41:23 +00004676bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4677 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4678 // C++1z [temp.arg.template]p4: (DR 150)
4679 // A template template-parameter P is at least as specialized as a
4680 // template template-argument A if, given the following rewrite to two
4681 // function templates...
4682
4683 // Rather than synthesize function templates, we merely perform the
4684 // equivalent partial ordering by performing deduction directly on
4685 // the template parameter lists of the template template parameters.
4686 //
4687 // Given an invented class template X with the template parameter list of
4688 // A (including default arguments):
4689 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4690 TemplateParameterList *A = AArg->getTemplateParameters();
4691
4692 // - Each function template has a single function parameter whose type is
4693 // a specialization of X with template arguments corresponding to the
4694 // template parameters from the respective function template
4695 SmallVector<TemplateArgument, 8> AArgs;
4696 Context.getInjectedTemplateArgs(A, AArgs);
4697
4698 // Check P's arguments against A's parameter list. This will fill in default
4699 // template arguments as needed. AArgs are already correct by construction.
4700 // We can't just use CheckTemplateIdType because that will expand alias
4701 // templates.
4702 SmallVector<TemplateArgument, 4> PArgs;
4703 {
4704 SFINAETrap Trap(*this);
4705
4706 Context.getInjectedTemplateArgs(P, PArgs);
4707 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4708 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4709 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4710 // expansions, to form an "as written" argument list.
4711 TemplateArgument Arg = PArgs[I];
4712 if (Arg.getKind() == TemplateArgument::Pack) {
4713 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4714 Arg = *Arg.pack_begin();
4715 }
4716 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4717 Arg, QualType(), P->getParam(I)->getLocation()));
4718 }
4719 PArgs.clear();
4720
4721 // C++1z [temp.arg.template]p3:
4722 // If the rewrite produces an invalid type, then P is not at least as
4723 // specialized as A.
4724 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4725 Trap.hasErrorOccurred())
4726 return false;
4727 }
4728
4729 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4730 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4731
Richard Smith26b86ea2016-12-31 21:41:23 +00004732 // ... the function template corresponding to P is at least as specialized
4733 // as the function template corresponding to A according to the partial
4734 // ordering rules for function templates.
4735 TemplateDeductionInfo Info(Loc, A->getDepth());
4736 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4737}
4738
Mike Stump11289f42009-09-09 15:08:12 +00004739static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004741 const TemplateArgument &TemplateArg,
4742 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004743 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004744 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004745
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004746/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004747/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004748static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004749MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004750 const Expr *E,
4751 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004752 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004753 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004754 // We can deduce from a pack expansion.
4755 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4756 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757
Richard Smith34349002012-07-09 03:07:20 +00004758 // Skip through any implicit casts we added while type-checking, and any
4759 // substitutions performed by template alias expansion.
4760 while (1) {
4761 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4762 E = ICE->getSubExpr();
4763 else if (const SubstNonTypeTemplateParmExpr *Subst =
4764 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4765 E = Subst->getReplacement();
4766 else
4767 break;
4768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
4770 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004771 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004772 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004773 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004774 return;
4775
Mike Stump11289f42009-09-09 15:08:12 +00004776 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004777 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4778 if (!NTTP)
4779 return;
4780
Douglas Gregor21610382009-10-29 00:04:11 +00004781 if (NTTP->getDepth() == Depth)
4782 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004783
4784 // In C++1z mode, additional arguments may be deduced from the type of a
4785 // non-type argument.
4786 if (Ctx.getLangOpts().CPlusPlus1z)
4787 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004788}
4789
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004790/// \brief Mark the template parameters that are used by the given
4791/// nested name specifier.
4792static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004793MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004794 NestedNameSpecifier *NNS,
4795 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004796 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004797 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004798 if (!NNS)
4799 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004801 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004802 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004803 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004804 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004805}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004807/// \brief Mark the template parameters that are used by the given
4808/// template name.
4809static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004810MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004811 TemplateName Name,
4812 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004813 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004814 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004815 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4816 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004817 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4818 if (TTP->getDepth() == Depth)
4819 Used[TTP->getIndex()] = true;
4820 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004821 return;
4822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004824 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004825 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004826 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004827 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004828 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004829 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004830}
4831
4832/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004833/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004834static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004835MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004836 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004837 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004838 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004839 if (T.isNull())
4840 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregor91772d12009-06-13 00:26:55 +00004842 // Non-dependent types have nothing deducible
4843 if (!T->isDependentType())
4844 return;
4845
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004846 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004847 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004848 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004849 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004850 cast<PointerType>(T)->getPointeeType(),
4851 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004852 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004853 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004854 break;
4855
4856 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004857 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004858 cast<BlockPointerType>(T)->getPointeeType(),
4859 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004860 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004861 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004862 break;
4863
4864 case Type::LValueReference:
4865 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004866 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004867 cast<ReferenceType>(T)->getPointeeType(),
4868 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004869 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004870 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004871 break;
4872
4873 case Type::MemberPointer: {
4874 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004875 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004876 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004877 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004878 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004879 break;
4880 }
4881
4882 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004883 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004884 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004885 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004886 // Fall through to check the element type
4887
4888 case Type::ConstantArray:
4889 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004890 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004891 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004892 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004893 break;
4894
4895 case Type::Vector:
4896 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004897 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004898 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004899 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004900 break;
4901
Douglas Gregor758a8692009-06-17 21:51:59 +00004902 case Type::DependentSizedExtVector: {
4903 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004904 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004905 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004906 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004907 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004908 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004909 break;
4910 }
4911
Douglas Gregor91772d12009-06-13 00:26:55 +00004912 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004913 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004914 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4915 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004916 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4917 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004918 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004919 break;
4920 }
4921
Douglas Gregor21610382009-10-29 00:04:11 +00004922 case Type::TemplateTypeParm: {
4923 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4924 if (TTP->getDepth() == Depth)
4925 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004926 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004927 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004928
Douglas Gregorfb322d82011-01-14 05:11:40 +00004929 case Type::SubstTemplateTypeParmPack: {
4930 const SubstTemplateTypeParmPackType *Subst
4931 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004932 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004933 QualType(Subst->getReplacedParameter(), 0),
4934 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004936 OnlyDeduced, Depth, Used);
4937 break;
4938 }
4939
John McCall2408e322010-04-27 00:57:59 +00004940 case Type::InjectedClassName:
4941 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4942 // fall through
4943
Douglas Gregor91772d12009-06-13 00:26:55 +00004944 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004945 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004946 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004947 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004948 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Douglas Gregord0ad2942010-12-23 01:24:45 +00004950 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004951 // If the template argument list of P contains a pack expansion that is
4952 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004953 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004955 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004956 break;
4957
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004958 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004959 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004960 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004961 break;
4962 }
4963
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004964 case Type::Complex:
4965 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004966 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004967 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004968 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004969 break;
4970
Eli Friedman0dfb8892011-10-06 23:00:33 +00004971 case Type::Atomic:
4972 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004973 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004974 cast<AtomicType>(T)->getValueType(),
4975 OnlyDeduced, Depth, Used);
4976 break;
4977
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004978 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004979 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004980 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004981 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004982 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004983 break;
4984
John McCallc392f372010-06-11 00:33:02 +00004985 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004986 // C++14 [temp.deduct.type]p5:
4987 // The non-deduced contexts are:
4988 // -- The nested-name-specifier of a type that was specified using a
4989 // qualified-id
4990 //
4991 // C++14 [temp.deduct.type]p6:
4992 // When a type name is specified in a way that includes a non-deduced
4993 // context, all of the types that comprise that type name are also
4994 // non-deduced.
4995 if (OnlyDeduced)
4996 break;
4997
John McCallc392f372010-06-11 00:33:02 +00004998 const DependentTemplateSpecializationType *Spec
4999 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000
Richard Smith50d5b972015-12-30 20:56:05 +00005001 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5002 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005003
John McCallc392f372010-06-11 00:33:02 +00005004 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005005 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005006 Used);
5007 break;
5008 }
5009
John McCallbd8d9bd2010-03-01 23:49:17 +00005010 case Type::TypeOf:
5011 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005012 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005013 cast<TypeOfType>(T)->getUnderlyingType(),
5014 OnlyDeduced, Depth, Used);
5015 break;
5016
5017 case Type::TypeOfExpr:
5018 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005019 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005020 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5021 OnlyDeduced, Depth, Used);
5022 break;
5023
5024 case Type::Decltype:
5025 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005026 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005027 cast<DecltypeType>(T)->getUnderlyingExpr(),
5028 OnlyDeduced, Depth, Used);
5029 break;
5030
Alexis Hunte852b102011-05-24 22:41:36 +00005031 case Type::UnaryTransform:
5032 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005034 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005035 OnlyDeduced, Depth, Used);
5036 break;
5037
Douglas Gregord2fa7662010-12-20 02:24:11 +00005038 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005039 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005040 cast<PackExpansionType>(T)->getPattern(),
5041 OnlyDeduced, Depth, Used);
5042 break;
5043
Richard Smith30482bc2011-02-20 03:19:35 +00005044 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005045 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005046 cast<AutoType>(T)->getDeducedType(),
5047 OnlyDeduced, Depth, Used);
5048
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005049 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005050 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005051 case Type::VariableArray:
5052 case Type::FunctionNoProto:
5053 case Type::Record:
5054 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005055 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005056 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005057 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005058 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005059 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005060#define TYPE(Class, Base)
5061#define ABSTRACT_TYPE(Class, Base)
5062#define DEPENDENT_TYPE(Class, Base)
5063#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5064#include "clang/AST/TypeNodes.def"
5065 break;
5066 }
5067}
5068
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005069/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005070/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005071static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005072MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005073 const TemplateArgument &TemplateArg,
5074 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005075 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005076 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005077 switch (TemplateArg.getKind()) {
5078 case TemplateArgument::Null:
5079 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005080 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005081 break;
Mike Stump11289f42009-09-09 15:08:12 +00005082
Eli Friedmanb826a002012-09-26 02:36:12 +00005083 case TemplateArgument::NullPtr:
5084 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5085 Depth, Used);
5086 break;
5087
Douglas Gregor91772d12009-06-13 00:26:55 +00005088 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005089 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005090 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005091 break;
5092
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005093 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005094 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005095 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005097 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005098 break;
5099
5100 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005101 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005102 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005103 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005104
Anders Carlssonbc343912009-06-15 17:04:53 +00005105 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005106 for (const auto &P : TemplateArg.pack_elements())
5107 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005108 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005109 }
5110}
5111
James Dennett41725122012-06-22 10:16:05 +00005112/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005113/// template argument list.
5114///
5115/// \param TemplateArgs the template argument list from which template
5116/// parameters will be deduced.
5117///
James Dennett41725122012-06-22 10:16:05 +00005118/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005119/// to indicate when the corresponding template parameter will be
5120/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005121void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005122Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005123 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005124 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005125 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126 // If the template argument list of P contains a pack expansion that is not
5127 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005128 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005129 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005130 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005131 return;
5132
Douglas Gregor91772d12009-06-13 00:26:55 +00005133 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005134 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005135 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005136}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005137
5138/// \brief Marks all of the template parameters that will be deduced by a
5139/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005140void Sema::MarkDeducedTemplateParameters(
5141 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5142 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005144 = FunctionTemplate->getTemplateParameters();
5145 Deduced.clear();
5146 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
Douglas Gregorce23bae2009-09-18 23:21:38 +00005148 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5149 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005150 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005151 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005152}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005153
5154bool hasDeducibleTemplateParameters(Sema &S,
5155 FunctionTemplateDecl *FunctionTemplate,
5156 QualType T) {
5157 if (!T->isDependentType())
5158 return false;
5159
5160 TemplateParameterList *TemplateParams
5161 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005162 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005163 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005164 Deduced);
5165
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005166 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005167}