blob: 75b69ae04f56379eb1ea8fba96cdc8417824e4b7 [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"
Richard Smithc92d2062017-01-05 23:02:44 +000022#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Sema.h"
25#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000026#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000027#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000028
29namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000030 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000031 /// \brief Various flags that control template argument deduction.
32 ///
33 /// These flags can be bitwise-OR'd together.
34 enum TemplateDeductionFlags {
35 /// \brief No template argument deduction flags, which indicates the
36 /// strictest results for template argument deduction (as used for, e.g.,
37 /// matching class template partial specializations).
38 TDF_None = 0,
39 /// \brief Within template argument deduction from a function call, we are
40 /// matching with a parameter type for which the original parameter was
41 /// a reference.
42 TDF_ParamWithReferenceType = 0x1,
43 /// \brief Within template argument deduction from a function call, we
44 /// are matching in a case where we ignore cv-qualifiers.
45 TDF_IgnoreQualifiers = 0x02,
46 /// \brief Within template argument deduction from a function call,
47 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000048 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000049 TDF_DerivedClass = 0x04,
50 /// \brief Allow non-dependent types to differ, e.g., when performing
51 /// template argument deduction from a function call where conversions
52 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000053 TDF_SkipNonDependent = 0x08,
54 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000055 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000056 TDF_TopLevelParameterTypeList = 0x10,
57 /// \brief Within template argument deduction from overload resolution per
58 /// C++ [over.over] allow matching function types that are compatible in
59 /// terms of noreturn and default calling convention adjustments.
60 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000061 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000062}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000063
Douglas Gregor55ca8f62009-06-04 00:03:07 +000064using namespace clang;
65
Douglas Gregor0a29a052010-03-26 05:50:28 +000066/// \brief Compare two APSInts, extending and switching the sign as
67/// necessary to compare their values regardless of underlying type.
68static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
69 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000070 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000071 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000072 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000073
74 // If there is a signedness mismatch, correct it.
75 if (X.isSigned() != Y.isSigned()) {
76 // If the signed value is negative, then the values cannot be the same.
77 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
78 return false;
79
80 Y.setIsSigned(true);
81 X.setIsSigned(true);
82 }
83
84 return X == Y;
85}
86
Douglas Gregor181aa4a2009-06-12 18:26:56 +000087static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000088DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000089 TemplateParameterList *TemplateParams,
90 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000091 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000092 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000093 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000094
Douglas Gregor7baabef2010-12-22 18:17:10 +000095static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000096DeduceTemplateArgumentsByTypeMatch(Sema &S,
97 TemplateParameterList *TemplateParams,
98 QualType Param,
99 QualType Arg,
100 TemplateDeductionInfo &Info,
101 SmallVectorImpl<DeducedTemplateArgument> &
102 Deduced,
103 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000104 bool PartialOrdering = false,
105 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000106
107static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000108DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000109 ArrayRef<TemplateArgument> Params,
110 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000111 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000112 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
113 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000114
Richard Smith130cc442017-02-21 23:49:18 +0000115static void MarkUsedTemplateParameters(ASTContext &Ctx,
116 const TemplateArgument &TemplateArg,
117 bool OnlyDeduced, unsigned Depth,
118 llvm::SmallBitVector &Used);
119
120static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
121 bool OnlyDeduced, unsigned Level,
122 llvm::SmallBitVector &Deduced);
123
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000124/// \brief If the given expression is of a form that permits the deduction
125/// of a non-type template parameter, return the declaration of that
126/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000127static NonTypeTemplateParmDecl *
128getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000129 // If we are within an alias template, the expression may have undergone
130 // any number of parameter substitutions already.
131 while (1) {
132 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
133 E = IC->getSubExpr();
134 else if (SubstNonTypeTemplateParmExpr *Subst =
135 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
136 E = Subst->getReplacement();
137 else
138 break;
139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000141 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000142 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
143 if (NTTP->getDepth() == Info.getDeducedDepth())
144 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000145
Craig Topperc3ec1492014-05-26 06:22:03 +0000146 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000147}
148
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000149/// \brief Determine whether two declaration pointers refer to the same
150/// declaration.
151static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000152 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
153 X = NX->getUnderlyingDecl();
154 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
155 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000156
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000157 return X->getCanonicalDecl() == Y->getCanonicalDecl();
158}
159
160/// \brief Verify that the given, deduced template arguments are compatible.
161///
162/// \returns The deduced template argument, or a NULL template argument if
163/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000164static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000165checkDeducedTemplateArguments(ASTContext &Context,
166 const DeducedTemplateArgument &X,
167 const DeducedTemplateArgument &Y) {
168 // We have no deduction for one or both of the arguments; they're compatible.
169 if (X.isNull())
170 return Y;
171 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000172 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000173
Richard Smith593d6a12016-12-23 01:30:39 +0000174 // If we have two non-type template argument values deduced for the same
175 // parameter, they must both match the type of the parameter, and thus must
176 // match each other's type. As we're only keeping one of them, we must check
177 // for that now. The exception is that if either was deduced from an array
178 // bound, the type is permitted to differ.
179 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
180 QualType XType = X.getNonTypeTemplateArgumentType();
181 if (!XType.isNull()) {
182 QualType YType = Y.getNonTypeTemplateArgumentType();
183 if (YType.isNull() || !Context.hasSameType(XType, YType))
184 return DeducedTemplateArgument();
185 }
186 }
187
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000188 switch (X.getKind()) {
189 case TemplateArgument::Null:
190 llvm_unreachable("Non-deduced template arguments handled above");
191
192 case TemplateArgument::Type:
193 // If two template type arguments have the same type, they're compatible.
194 if (Y.getKind() == TemplateArgument::Type &&
195 Context.hasSameType(X.getAsType(), Y.getAsType()))
196 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
Richard Smith5f274382016-09-28 23:55:27 +0000198 // If one of the two arguments was deduced from an array bound, the other
199 // supersedes it.
200 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
201 return X.wasDeducedFromArrayBound() ? Y : X;
202
203 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000204 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000206 case TemplateArgument::Integral:
207 // If we deduced a constant in one case and either a dependent expression or
208 // declaration in another case, keep the integral constant.
209 // If both are integral constants with the same value, keep that value.
210 if (Y.getKind() == TemplateArgument::Expression ||
211 Y.getKind() == TemplateArgument::Declaration ||
212 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000213 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000214 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000215
216 // All other combinations are incompatible.
217 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000218
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000219 case TemplateArgument::Template:
220 if (Y.getKind() == TemplateArgument::Template &&
221 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
222 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000224 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000226
227 case TemplateArgument::TemplateExpansion:
228 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000229 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000230 Y.getAsTemplateOrTemplatePattern()))
231 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000232
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000233 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000234 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000235
Richard Smith593d6a12016-12-23 01:30:39 +0000236 case TemplateArgument::Expression: {
237 if (Y.getKind() != TemplateArgument::Expression)
238 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000239
Richard Smith593d6a12016-12-23 01:30:39 +0000240 // Compare the expressions for equality
241 llvm::FoldingSetNodeID ID1, ID2;
242 X.getAsExpr()->Profile(ID1, Context, true);
243 Y.getAsExpr()->Profile(ID2, Context, true);
244 if (ID1 == ID2)
245 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000246
Richard Smith593d6a12016-12-23 01:30:39 +0000247 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000248 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000250
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000251 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000252 assert(!X.wasDeducedFromArrayBound());
253
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000254 // If we deduced a declaration and a dependent expression, keep the
255 // declaration.
256 if (Y.getKind() == TemplateArgument::Expression)
257 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000258
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000260 // integral constant and whichever type did not come from an array
261 // bound.
262 if (Y.getKind() == TemplateArgument::Integral) {
263 if (Y.wasDeducedFromArrayBound())
264 return TemplateArgument(Context, Y.getAsIntegral(),
265 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000266 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000268
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000269 // If we deduced two declarations, make sure they they refer to the
270 // same declaration.
271 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000272 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000273 return X;
274
275 // All other combinations are incompatible.
276 return DeducedTemplateArgument();
277
278 case TemplateArgument::NullPtr:
279 // If we deduced a null pointer and a dependent expression, keep the
280 // null pointer.
281 if (Y.getKind() == TemplateArgument::Expression)
282 return X;
283
284 // If we deduced a null pointer and an integral constant, keep the
285 // integral constant.
286 if (Y.getKind() == TemplateArgument::Integral)
287 return Y;
288
Richard Smith593d6a12016-12-23 01:30:39 +0000289 // If we deduced two null pointers, they are the same.
290 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000291 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000293 // All other combinations are incompatible.
294 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000296 case TemplateArgument::Pack:
297 if (Y.getKind() != TemplateArgument::Pack ||
298 X.pack_size() != Y.pack_size())
299 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000300
Richard Smith539e8e32017-01-04 01:48:55 +0000301 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 XAEnd = X.pack_end(),
304 YA = Y.pack_begin();
305 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000306 TemplateArgument Merged = checkDeducedTemplateArguments(
307 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
308 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
309 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000310 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000311 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313
Richard Smith539e8e32017-01-04 01:48:55 +0000314 return DeducedTemplateArgument(
315 TemplateArgument::CreatePackCopy(Context, NewPack),
316 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000318
David Blaikiee4d798f2012-01-20 21:50:17 +0000319 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000320}
321
Mike Stump11289f42009-09-09 15:08:12 +0000322/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000323/// as the given deduced template argument. All non-type template parameter
324/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000325static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000326 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000327 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
328 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000329 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000330 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
331 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000332
Richard Smith5d102892016-12-27 03:59:58 +0000333 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
334 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000335 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000336 Info.Param = NTTP;
337 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000338 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000341
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000342 Deduced[NTTP->getIndex()] = Result;
Richard Smithd92eddf2016-12-27 06:14:37 +0000343 if (!S.getLangOpts().CPlusPlus1z)
344 return Sema::TDK_Success;
345
Richard Smith130cc442017-02-21 23:49:18 +0000346 if (NTTP->isExpandedParameterPack())
347 // FIXME: We may still need to deduce parts of the type here! But we
348 // don't have any way to find which slice of the type to use, and the
349 // type stored on the NTTP itself is nonsense. Perhaps the type of an
350 // expanded NTTP should be a pack expansion type?
351 return Sema::TDK_Success;
352
353 // Get the type of the parameter for deduction.
354 QualType ParamType = NTTP->getType();
355 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
356 ParamType = Expansion->getPattern();
357
Richard Smithd92eddf2016-12-27 06:14:37 +0000358 // FIXME: It's not clear how deduction of a parameter of reference
359 // type from an argument (of non-reference type) should be performed.
360 // For now, we just remove reference types from both sides and let
361 // the final check for matching types sort out the mess.
362 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000363 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000364 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
365 /*PartialOrdering=*/false,
366 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000367}
368
Mike Stump11289f42009-09-09 15:08:12 +0000369/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000370/// from the given integral constant.
371static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
372 Sema &S, TemplateParameterList *TemplateParams,
373 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
374 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
375 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
376 return DeduceNonTypeTemplateArgument(
377 S, TemplateParams, NTTP,
378 DeducedTemplateArgument(S.Context, Value, ValueType,
379 DeducedFromArrayBound),
380 ValueType, Info, Deduced);
381}
382
383/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000384/// from the given null pointer template argument type.
385static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000386 Sema &S, TemplateParameterList *TemplateParams,
387 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000388 TemplateDeductionInfo &Info,
389 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
390 Expr *Value =
391 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
392 S.Context.NullPtrTy, NTTP->getLocation()),
393 NullPtrType, CK_NullToPointer)
394 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000395 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
396 DeducedTemplateArgument(Value),
397 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000398}
399
400/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000401/// from the given type- or value-dependent expression.
402///
403/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000404static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
405 Sema &S, TemplateParameterList *TemplateParams,
406 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
407 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000408 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
409 DeducedTemplateArgument(Value),
410 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000411}
412
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000413/// \brief Deduce the value of the given non-type template parameter
414/// from the given declaration.
415///
416/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000417static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
418 Sema &S, TemplateParameterList *TemplateParams,
419 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
420 TemplateDeductionInfo &Info,
421 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000422 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000423 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000424 return DeduceNonTypeTemplateArgument(
425 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000426}
427
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000428static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000429DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000430 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000431 TemplateName Param,
432 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000433 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000434 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000435 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000436 if (!ParamDecl) {
437 // The parameter type is dependent and is not a template template parameter,
438 // so there is nothing that we can deduce.
439 return Sema::TDK_Success;
440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 if (TemplateTemplateParmDecl *TempParam
443 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000444 // If we're not deducing at this depth, there's nothing to deduce.
445 if (TempParam->getDepth() != Info.getDeducedDepth())
446 return Sema::TDK_Success;
447
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000448 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000450 Deduced[TempParam->getIndex()],
451 NewDeduced);
452 if (Result.isNull()) {
453 Info.Param = TempParam;
454 Info.FirstArg = Deduced[TempParam->getIndex()];
455 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000459 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000460 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregoradee3e32009-11-11 23:06:43 +0000463 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000464 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000465 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000466
Douglas Gregoradee3e32009-11-11 23:06:43 +0000467 // Mismatch of non-dependent template parameter to argument.
468 Info.FirstArg = TemplateArgument(Param);
469 Info.SecondArg = TemplateArgument(Arg);
470 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000471}
472
Mike Stump11289f42009-09-09 15:08:12 +0000473/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000474/// type (which is a template-id) with the template argument type.
475///
Chandler Carruthc1263112010-02-07 21:33:28 +0000476/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000477///
478/// \param TemplateParams the template parameters that we are deducing
479///
480/// \param Param the parameter type
481///
482/// \param Arg the argument type
483///
484/// \param Info information about the template argument deduction itself
485///
486/// \param Deduced the deduced template arguments
487///
488/// \returns the result of template argument deduction so far. Note that a
489/// "success" result means that template argument deduction has not yet failed,
490/// but it may still fail, later, for other reasons.
491static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000492DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000493 TemplateParameterList *TemplateParams,
494 const TemplateSpecializationType *Param,
495 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000496 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000497 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000498 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregore81f3e72009-07-07 23:09:34 +0000500 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000501 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000502 = dyn_cast<TemplateSpecializationType>(Arg)) {
503 // Perform template argument deduction for the template name.
504 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000505 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 Param->getTemplateName(),
507 SpecArg->getTemplateName(),
508 Info, Deduced))
509 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000510
Mike Stump11289f42009-09-09 15:08:12 +0000511
Douglas Gregore81f3e72009-07-07 23:09:34 +0000512 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000513 // argument. Ignore any missing/extra arguments, since they could be
514 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000515 return DeduceTemplateArguments(S, TemplateParams,
516 Param->template_arguments(),
517 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000518 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Douglas Gregore81f3e72009-07-07 23:09:34 +0000521 // If the argument type is a class template specialization, we
522 // perform template argument deduction using its template
523 // arguments.
524 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000525 if (!RecordArg) {
526 Info.FirstArg = TemplateArgument(QualType(Param, 0));
527 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000528 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 }
Mike Stump11289f42009-09-09 15:08:12 +0000530
531 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000532 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000533 if (!SpecArg) {
534 Info.FirstArg = TemplateArgument(QualType(Param, 0));
535 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000536 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
Douglas Gregore81f3e72009-07-07 23:09:34 +0000539 // Perform template argument deduction for the template name.
540 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000541 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000542 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000543 Param->getTemplateName(),
544 TemplateName(SpecArg->getSpecializedTemplate()),
545 Info, Deduced))
546 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregor7baabef2010-12-22 18:17:10 +0000548 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000549 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
550 SpecArg->getTemplateArgs().asArray(), Info,
551 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000552}
553
John McCall08569062010-08-28 22:14:41 +0000554/// \brief Determines whether the given type is an opaque type that
555/// might be more qualified when instantiated.
556static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
557 switch (T->getTypeClass()) {
558 case Type::TypeOfExpr:
559 case Type::TypeOf:
560 case Type::DependentName:
561 case Type::Decltype:
562 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000563 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000564 return true;
565
566 case Type::ConstantArray:
567 case Type::IncompleteArray:
568 case Type::VariableArray:
569 case Type::DependentSizedArray:
570 return IsPossiblyOpaquelyQualifiedType(
571 cast<ArrayType>(T)->getElementType());
572
573 default:
574 return false;
575 }
576}
577
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000578/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000580getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000581 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
582 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor5499af42011-01-05 23:12:31 +0000584 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
585 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Douglas Gregor5499af42011-01-05 23:12:31 +0000587 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
588 return std::make_pair(TTP->getDepth(), TTP->getIndex());
589}
590
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000591/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000593getDepthAndIndex(UnexpandedParameterPack UPP) {
594 if (const TemplateTypeParmType *TTP
595 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
596 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000598 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
599}
600
Douglas Gregor5499af42011-01-05 23:12:31 +0000601/// \brief Helper function to build a TemplateParameter when we don't
602/// know its type statically.
603static TemplateParameter makeTemplateParameter(Decl *D) {
604 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
605 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000606 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000607 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor5499af42011-01-05 23:12:31 +0000609 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
610}
611
Richard Smith0a80d572014-05-29 01:12:14 +0000612/// A pack that we're currently deducing.
613struct clang::DeducedPack {
614 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000615
Richard Smith0a80d572014-05-29 01:12:14 +0000616 // The index of the pack.
617 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Richard Smith0a80d572014-05-29 01:12:14 +0000619 // The old value of the pack before we started deducing it.
620 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000621
Richard Smith0a80d572014-05-29 01:12:14 +0000622 // A deferred value of this pack from an inner deduction, that couldn't be
623 // deduced because this deduction hadn't happened yet.
624 DeducedTemplateArgument DeferredDeduction;
625
626 // The new value of the pack.
627 SmallVector<DeducedTemplateArgument, 4> New;
628
629 // The outer deduction for this pack, if any.
630 DeducedPack *Outer;
631};
632
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000633namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000634/// A scope in which we're performing pack deduction.
635class PackDeductionScope {
636public:
637 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
638 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
639 TemplateDeductionInfo &Info, TemplateArgument Pattern)
640 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith130cc442017-02-21 23:49:18 +0000641 // Dig out the partially-substituted pack, if there is one.
642 const TemplateArgument *PartialPackArgs = nullptr;
643 unsigned NumPartialPackArgs = 0;
644 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
645 if (auto *Scope = S.CurrentInstantiationScope)
646 if (auto *Partial = Scope->getPartiallySubstitutedPack(
647 &PartialPackArgs, &NumPartialPackArgs))
648 PartialPackDepthIndex = getDepthAndIndex(Partial);
649
Richard Smith0a80d572014-05-29 01:12:14 +0000650 // Compute the set of template parameter indices that correspond to
651 // parameter packs expanded by the pack expansion.
652 {
653 llvm::SmallBitVector SawIndices(TemplateParams->size());
Richard Smith130cc442017-02-21 23:49:18 +0000654
655 auto AddPack = [&](unsigned Index) {
656 if (SawIndices[Index])
657 return;
658 SawIndices[Index] = true;
659
660 // Save the deduced template argument for the parameter pack expanded
661 // by this pack expansion, then clear out the deduction.
662 DeducedPack Pack(Index);
663 Pack.Saved = Deduced[Index];
664 Deduced[Index] = TemplateArgument();
665
666 Packs.push_back(Pack);
667 };
668
669 // First look for unexpanded packs in the pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000670 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
671 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
672 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
673 unsigned Depth, Index;
674 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith130cc442017-02-21 23:49:18 +0000675 if (Depth == Info.getDeducedDepth())
676 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000677 }
Richard Smith130cc442017-02-21 23:49:18 +0000678 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
679
680 // This pack expansion will have been partially expanded iff the only
681 // unexpanded parameter pack within it is the partially-substituted pack.
682 IsPartiallyExpanded =
683 Packs.size() == 1 &&
684 PartialPackDepthIndex ==
685 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
686
687 // Skip over the pack elements that were expanded into separate arguments.
688 if (IsPartiallyExpanded)
689 PackElements += NumPartialPackArgs;
690
691 // We can also have deduced template parameters that do not actually
692 // appear in the pattern, but can be deduced by it (the type of a non-type
693 // template parameter pack, in particular). These won't have prevented us
694 // from partially expanding the pack.
695 llvm::SmallBitVector Used(TemplateParams->size());
696 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
697 Info.getDeducedDepth(), Used);
698 for (int Index = Used.find_first(); Index != -1;
699 Index = Used.find_next(Index))
700 if (TemplateParams->getParam(Index)->isParameterPack())
701 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000702 }
Richard Smith0a80d572014-05-29 01:12:14 +0000703
704 for (auto &Pack : Packs) {
705 if (Info.PendingDeducedPacks.size() > Pack.Index)
706 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
707 else
708 Info.PendingDeducedPacks.resize(Pack.Index + 1);
709 Info.PendingDeducedPacks[Pack.Index] = &Pack;
710
Richard Smith130cc442017-02-21 23:49:18 +0000711 if (PartialPackDepthIndex ==
712 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
713 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
714 // We pre-populate the deduced value of the partially-substituted
715 // pack with the specified value. This is not entirely correct: the
716 // value is supposed to have been substituted, not deduced, but the
717 // cases where this is observable require an exact type match anyway.
718 //
719 // FIXME: If we could represent a "depth i, index j, pack elem k"
720 // parameter, we could substitute the partially-substituted pack
721 // everywhere and avoid this.
722 if (Pack.New.size() > PackElements)
723 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000724 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000725 }
726 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000727
Richard Smith0a80d572014-05-29 01:12:14 +0000728 ~PackDeductionScope() {
729 for (auto &Pack : Packs)
730 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000731 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000732
Richard Smithde0d34a2017-01-09 07:14:40 +0000733 /// Determine whether this pack has already been partially expanded into a
734 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000735 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000736
Richard Smith0a80d572014-05-29 01:12:14 +0000737 /// Move to deducing the next element in each pack that is being deduced.
738 void nextPackElement() {
739 // Capture the deduced template arguments for each parameter pack expanded
740 // by this pack expansion, add them to the list of arguments we've deduced
741 // for that pack, then clear out the deduced argument.
742 for (auto &Pack : Packs) {
743 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000744 if (!Pack.New.empty() || !DeducedArg.isNull()) {
745 while (Pack.New.size() < PackElements)
746 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000747 if (Pack.New.size() == PackElements)
748 Pack.New.push_back(DeducedArg);
749 else
750 Pack.New[PackElements] = DeducedArg;
751 DeducedArg = Pack.New.size() > PackElements + 1
752 ? Pack.New[PackElements + 1]
753 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000754 }
755 }
Richard Smith539e8e32017-01-04 01:48:55 +0000756 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000757 }
758
759 /// \brief Finish template argument deduction for a set of argument packs,
760 /// producing the argument packs and checking for consistency with prior
761 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000762 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000763 // Build argument packs for each of the parameter packs expanded by this
764 // pack expansion.
765 for (auto &Pack : Packs) {
766 // Put back the old value for this pack.
767 Deduced[Pack.Index] = Pack.Saved;
768
769 // Build or find a new value for this pack.
770 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000771 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000772 if (Pack.DeferredDeduction.isNull()) {
773 // We were not able to deduce anything for this parameter pack
774 // (because it only appeared in non-deduced contexts), so just
775 // restore the saved argument pack.
776 continue;
777 }
778
779 NewPack = Pack.DeferredDeduction;
780 Pack.DeferredDeduction = TemplateArgument();
781 } else if (Pack.New.empty()) {
782 // If we deduced an empty argument pack, create it now.
783 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
784 } else {
785 TemplateArgument *ArgumentPack =
786 new (S.Context) TemplateArgument[Pack.New.size()];
787 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
788 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000789 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000790 // FIXME: This is wrong, it's possible that some pack elements are
791 // deduced from an array bound and others are not:
792 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
793 // g({1, 2, 3}, {{}, {}});
794 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000795 Pack.New[0].wasDeducedFromArrayBound());
796 }
797
798 // Pick where we're going to put the merged pack.
799 DeducedTemplateArgument *Loc;
800 if (Pack.Outer) {
801 if (Pack.Outer->DeferredDeduction.isNull()) {
802 // Defer checking this pack until we have a complete pack to compare
803 // it against.
804 Pack.Outer->DeferredDeduction = NewPack;
805 continue;
806 }
807 Loc = &Pack.Outer->DeferredDeduction;
808 } else {
809 Loc = &Deduced[Pack.Index];
810 }
811
812 // Check the new pack matches any previous value.
813 DeducedTemplateArgument OldPack = *Loc;
814 DeducedTemplateArgument Result =
815 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
816
817 // If we deferred a deduction of this pack, check that one now too.
818 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
819 OldPack = Result;
820 NewPack = Pack.DeferredDeduction;
821 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
822 }
823
824 if (Result.isNull()) {
825 Info.Param =
826 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
827 Info.FirstArg = OldPack;
828 Info.SecondArg = NewPack;
829 return Sema::TDK_Inconsistent;
830 }
831
832 *Loc = Result;
833 }
834
835 return Sema::TDK_Success;
836 }
837
838private:
839 Sema &S;
840 TemplateParameterList *TemplateParams;
841 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
842 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000843 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000844 bool IsPartiallyExpanded = false;
Richard Smith0a80d572014-05-29 01:12:14 +0000845
846 SmallVector<DeducedPack, 2> Packs;
847};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000848} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000849
Douglas Gregor5499af42011-01-05 23:12:31 +0000850/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851/// types to the list of argument types, as in the parameter-type-lists of
852/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000853///
854/// \param S The semantic analysis object within which we are deducing
855///
856/// \param TemplateParams The template parameters that we are deducing
857///
858/// \param Params The list of parameter types
859///
860/// \param NumParams The number of types in \c Params
861///
862/// \param Args The list of argument types
863///
864/// \param NumArgs The number of types in \c Args
865///
866/// \param Info information about the template argument deduction itself
867///
868/// \param Deduced the deduced template arguments
869///
870/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
871/// how template argument deduction is performed.
872///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000873/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000875/// (C++0x [temp.deduct.partial]).
876///
Douglas Gregor5499af42011-01-05 23:12:31 +0000877/// \returns the result of template argument deduction so far. Note that a
878/// "success" result means that template argument deduction has not yet failed,
879/// but it may still fail, later, for other reasons.
880static Sema::TemplateDeductionResult
881DeduceTemplateArguments(Sema &S,
882 TemplateParameterList *TemplateParams,
883 const QualType *Params, unsigned NumParams,
884 const QualType *Args, unsigned NumArgs,
885 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000886 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000887 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000888 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000889 // Fast-path check to see if we have too many/too few arguments.
890 if (NumParams != NumArgs &&
891 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
892 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000893 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894
Douglas Gregor5499af42011-01-05 23:12:31 +0000895 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896 // Similarly, if P has a form that contains (T), then each parameter type
897 // Pi of the respective parameter-type- list of P is compared with the
898 // corresponding parameter type Ai of the corresponding parameter-type-list
899 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000900 unsigned ArgIdx = 0, ParamIdx = 0;
901 for (; ParamIdx != NumParams; ++ParamIdx) {
902 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000904 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
905 if (!Expansion) {
906 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907
Douglas Gregor5499af42011-01-05 23:12:31 +0000908 // Make sure we have an argument.
909 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000910 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000911
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000912 if (isa<PackExpansionType>(Args[ArgIdx])) {
913 // C++0x [temp.deduct.type]p22:
914 // If the original function parameter associated with A is a function
915 // parameter pack and the function parameter associated with P is not
916 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000917 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919
Douglas Gregor5499af42011-01-05 23:12:31 +0000920 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000921 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
922 Params[ParamIdx], Args[ArgIdx],
923 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000924 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000925 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000926
Douglas Gregor5499af42011-01-05 23:12:31 +0000927 ++ArgIdx;
928 continue;
929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000931 // C++0x [temp.deduct.type]p5:
932 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000933 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000934 // parameter-declaration-clause.
935 if (ParamIdx + 1 < NumParams)
936 return Sema::TDK_Success;
937
Douglas Gregor5499af42011-01-05 23:12:31 +0000938 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000940 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000942 // comparison deduces template arguments for subsequent positions in the
943 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000944
Douglas Gregor5499af42011-01-05 23:12:31 +0000945 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000946 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000947
Douglas Gregor5499af42011-01-05 23:12:31 +0000948 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000949 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000951 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
952 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000953 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000954 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000955
Richard Smith0a80d572014-05-29 01:12:14 +0000956 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000958
Douglas Gregor5499af42011-01-05 23:12:31 +0000959 // Build argument packs for each of the parameter packs expanded by this
960 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000961 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000964
Douglas Gregor5499af42011-01-05 23:12:31 +0000965 // Make sure we don't have any extra arguments.
966 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000967 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000968
Douglas Gregor5499af42011-01-05 23:12:31 +0000969 return Sema::TDK_Success;
970}
971
Douglas Gregor1d684c22011-04-28 00:56:09 +0000972/// \brief Determine whether the parameter has qualifiers that are either
973/// inconsistent with or a superset of the argument's qualifiers.
974static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
975 QualType ArgType) {
976 Qualifiers ParamQs = ParamType.getQualifiers();
977 Qualifiers ArgQs = ArgType.getQualifiers();
978
979 if (ParamQs == ArgQs)
980 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000981
Douglas Gregor1d684c22011-04-28 00:56:09 +0000982 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000983 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000984 ParamQs.hasObjCGCAttr())
985 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000986
Douglas Gregor1d684c22011-04-28 00:56:09 +0000987 // Mismatched (but not missing) address spaces.
988 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
989 ParamQs.hasAddressSpace())
990 return true;
991
John McCall31168b02011-06-15 23:02:42 +0000992 // Mismatched (but not missing) Objective-C lifetime qualifiers.
993 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
994 ParamQs.hasObjCLifetime())
995 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000996
Douglas Gregor1d684c22011-04-28 00:56:09 +0000997 // CVR qualifier superset.
998 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
999 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
1000 == ParamQs.getCVRQualifiers());
1001}
1002
Douglas Gregor19a41f12013-04-17 08:45:07 +00001003/// \brief Compare types for equality with respect to possibly compatible
1004/// function types (noreturn adjustment, implicit calling conventions). If any
1005/// of parameter and argument is not a function, just perform type comparison.
1006///
1007/// \param Param the template parameter type.
1008///
1009/// \param Arg the argument type.
1010bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1011 CanQualType Arg) {
1012 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1013 *ArgFunction = Arg->getAs<FunctionType>();
1014
1015 // Just compare if not functions.
1016 if (!ParamFunction || !ArgFunction)
1017 return Param == Arg;
1018
Richard Smith3c4f8d22016-10-16 17:54:23 +00001019 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001020 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001021 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001022 return Arg == Context.getCanonicalType(AdjustedParam);
1023
1024 // FIXME: Compatible calling conventions.
1025
1026 return Param == Arg;
1027}
1028
Richard Smith32918772017-02-14 00:25:28 +00001029/// Get the index of the first template parameter that was originally from the
1030/// innermost template-parameter-list. This is 0 except when we concatenate
1031/// the template parameter lists of a class template and a constructor template
1032/// when forming an implicit deduction guide.
1033static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001034 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1035 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001036 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001037 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001038}
1039
1040/// Determine whether a type denotes a forwarding reference.
1041static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1042 // C++1z [temp.deduct.call]p3:
1043 // A forwarding reference is an rvalue reference to a cv-unqualified
1044 // template parameter that does not represent a template parameter of a
1045 // class template.
1046 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1047 if (ParamRef->getPointeeType().getQualifiers())
1048 return false;
1049 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1050 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1051 }
1052 return false;
1053}
1054
Douglas Gregorcceb9752009-06-26 18:27:22 +00001055/// \brief Deduce the template arguments by comparing the parameter type and
1056/// the argument type (C++ [temp.deduct.type]).
1057///
Chandler Carruthc1263112010-02-07 21:33:28 +00001058/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001059///
1060/// \param TemplateParams the template parameters that we are deducing
1061///
1062/// \param ParamIn the parameter type
1063///
1064/// \param ArgIn the argument type
1065///
1066/// \param Info information about the template argument deduction itself
1067///
1068/// \param Deduced the deduced template arguments
1069///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001070/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001071/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001072///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001073/// \param PartialOrdering Whether we're performing template argument deduction
1074/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1075///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001076/// \returns the result of template argument deduction so far. Note that a
1077/// "success" result means that template argument deduction has not yet failed,
1078/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001079static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001080DeduceTemplateArgumentsByTypeMatch(Sema &S,
1081 TemplateParameterList *TemplateParams,
1082 QualType ParamIn, QualType ArgIn,
1083 TemplateDeductionInfo &Info,
1084 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1085 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001086 bool PartialOrdering,
1087 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001088 // We only want to look at the canonical types, since typedefs and
1089 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001090 QualType Param = S.Context.getCanonicalType(ParamIn);
1091 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001092
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001093 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001095 if (const PackExpansionType *ArgExpansion
1096 = dyn_cast<PackExpansionType>(Arg))
1097 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098
Douglas Gregorb837ea42011-01-11 17:34:58 +00001099 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001100 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101 // Before the partial ordering is done, certain transformations are
1102 // performed on the types used for partial ordering:
1103 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001104 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1105 if (ParamRef)
1106 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Douglas Gregorb837ea42011-01-11 17:34:58 +00001108 // - If A is a reference type, A is replaced by the type referred to.
1109 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1110 if (ArgRef)
1111 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Richard Smithed563c22015-02-20 04:45:22 +00001113 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1114 // C++11 [temp.deduct.partial]p9:
1115 // If, for a given type, deduction succeeds in both directions (i.e.,
1116 // the types are identical after the transformations above) and both
1117 // P and A were reference types [...]:
1118 // - if [one type] was an lvalue reference and [the other type] was
1119 // not, [the other type] is not considered to be at least as
1120 // specialized as [the first type]
1121 // - if [one type] is more cv-qualified than [the other type],
1122 // [the other type] is not considered to be at least as specialized
1123 // as [the first type]
1124 // Objective-C ARC adds:
1125 // - [one type] has non-trivial lifetime, [the other type] has
1126 // __unsafe_unretained lifetime, and the types are otherwise
1127 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001128 //
Richard Smithed563c22015-02-20 04:45:22 +00001129 // A is "considered to be at least as specialized" as P iff deduction
1130 // succeeds, so we model this as a deduction failure. Note that
1131 // [the first type] is P and [the other type] is A here; the standard
1132 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001133 Qualifiers ParamQuals = Param.getQualifiers();
1134 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001135 if ((ParamRef->isLValueReferenceType() &&
1136 !ArgRef->isLValueReferenceType()) ||
1137 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1138 (ParamQuals.hasNonTrivialObjCLifetime() &&
1139 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1140 ParamQuals.withoutObjCLifetime() ==
1141 ArgQuals.withoutObjCLifetime())) {
1142 Info.FirstArg = TemplateArgument(ParamIn);
1143 Info.SecondArg = TemplateArgument(ArgIn);
1144 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001145 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001147
Richard Smithed563c22015-02-20 04:45:22 +00001148 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001149 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001150 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001151 // version of P.
1152 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001154 // version of A.
1155 Arg = Arg.getUnqualifiedType();
1156 } else {
1157 // C++0x [temp.deduct.call]p4 bullet 1:
1158 // - If the original P is a reference type, the deduced A (i.e., the type
1159 // referred to by the reference) can be more cv-qualified than the
1160 // transformed A.
1161 if (TDF & TDF_ParamWithReferenceType) {
1162 Qualifiers Quals;
1163 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1164 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001165 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001166 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001168
Douglas Gregor85f240c2011-01-25 17:19:08 +00001169 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1170 // C++0x [temp.deduct.type]p10:
1171 // If P and A are function types that originated from deduction when
1172 // taking the address of a function template (14.8.2.2) or when deducing
1173 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001174 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001175 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1176 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001178 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1179 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001180 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001181 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001182 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1183 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001184 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001187 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001188 // A template type argument T, a template template argument TT or a
1189 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001190 // the following forms:
1191 //
1192 // T
1193 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001194 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001195 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001196 // Just skip any attempts to deduce from a placeholder type or a parameter
1197 // at a different depth.
1198 if (Arg->isPlaceholderType() ||
1199 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001200 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001201
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001202 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001203 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001204
Douglas Gregor60454822009-07-22 20:02:25 +00001205 // If the argument type is an array type, move the qualifiers up to the
1206 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001207 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001208 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001209 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001210 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001211 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001212 RecanonicalizeArg = true;
1213 }
1214 }
Mike Stump11289f42009-09-09 15:08:12 +00001215
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001216 // The argument type can not be less qualified than the parameter
1217 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001218 if (!(TDF & TDF_IgnoreQualifiers) &&
1219 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001220 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001221 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001222 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001223 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001224 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001225
Richard Smith87d263e2016-12-25 08:05:23 +00001226 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1227 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001228 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001229 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001230
Douglas Gregor1d684c22011-04-28 00:56:09 +00001231 // Remove any qualifiers on the parameter from the deduced type.
1232 // We checked the qualifiers for consistency above.
1233 Qualifiers DeducedQs = DeducedType.getQualifiers();
1234 Qualifiers ParamQs = Param.getQualifiers();
1235 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1236 if (ParamQs.hasObjCGCAttr())
1237 DeducedQs.removeObjCGCAttr();
1238 if (ParamQs.hasAddressSpace())
1239 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001240 if (ParamQs.hasObjCLifetime())
1241 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001242
Douglas Gregore46db902011-06-17 22:11:49 +00001243 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001244 // If template deduction would produce a lifetime qualifier on a type
1245 // that is not a lifetime type, template argument deduction fails.
1246 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1247 !DeducedType->isDependentType()) {
1248 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1249 Info.FirstArg = TemplateArgument(Param);
1250 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001251 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001252 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001253
Douglas Gregora4f2b432011-07-26 14:53:44 +00001254 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001255 // If template deduction would produce an argument type with lifetime type
1256 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001257 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001258 DeducedType->isObjCLifetimeType() &&
1259 !DeducedQs.hasObjCLifetime())
1260 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001261
Douglas Gregor1d684c22011-04-28 00:56:09 +00001262 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1263 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001264
Douglas Gregord6605db2009-07-22 21:30:48 +00001265 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001266 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001267
Richard Smith5f274382016-09-28 23:55:27 +00001268 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001269 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001270 Deduced[Index],
1271 NewDeduced);
1272 if (Result.isNull()) {
1273 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1274 Info.FirstArg = Deduced[Index];
1275 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001276 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001279 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001281 }
1282
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001283 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001284 Info.FirstArg = TemplateArgument(ParamIn);
1285 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001286
Douglas Gregorfb322d82011-01-14 05:11:40 +00001287 // If the parameter is an already-substituted template parameter
1288 // pack, do nothing: we don't know which of its arguments to look
1289 // at, so we have to wait until all of the parameter packs in this
1290 // expansion have arguments.
1291 if (isa<SubstTemplateTypeParmPackType>(Param))
1292 return Sema::TDK_Success;
1293
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001294 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001295 CanQualType CanParam = S.Context.getCanonicalType(Param);
1296 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001297 if (!(TDF & TDF_IgnoreQualifiers)) {
1298 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001299 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001300 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001301 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001302 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001303 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001304 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001305
Douglas Gregor194ea692012-03-11 03:29:50 +00001306 // If the parameter type is not dependent, there is nothing to deduce.
1307 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001308 if (!(TDF & TDF_SkipNonDependent)) {
1309 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1310 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1311 Param != Arg;
1312 if (NonDeduced) {
1313 return Sema::TDK_NonDeducedMismatch;
1314 }
1315 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001316 return Sema::TDK_Success;
1317 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001318 } else if (!Param->isDependentType()) {
1319 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1320 ArgUnqualType = CanArg.getUnqualifiedType();
1321 bool Success = (TDF & TDF_InOverloadResolution)?
1322 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1323 ArgUnqualType) :
1324 ParamUnqualType == ArgUnqualType;
1325 if (Success)
1326 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001327 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001328
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001329 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001330 // Non-canonical types cannot appear here.
1331#define NON_CANONICAL_TYPE(Class, Base) \
1332 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1333#define TYPE(Class, Base)
1334#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001335
Douglas Gregor39c02722011-06-15 16:02:29 +00001336 case Type::TemplateTypeParm:
1337 case Type::SubstTemplateTypeParmPack:
1338 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001339
1340 // These types cannot be dependent, so simply check whether the types are
1341 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001343 case Type::VariableArray:
1344 case Type::Vector:
1345 case Type::FunctionNoProto:
1346 case Type::Record:
1347 case Type::Enum:
1348 case Type::ObjCObject:
1349 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001350 case Type::ObjCObjectPointer: {
1351 if (TDF & TDF_SkipNonDependent)
1352 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001353
Douglas Gregor194ea692012-03-11 03:29:50 +00001354 if (TDF & TDF_IgnoreQualifiers) {
1355 Param = Param.getUnqualifiedType();
1356 Arg = Arg.getUnqualifiedType();
1357 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001358
Douglas Gregor194ea692012-03-11 03:29:50 +00001359 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1360 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001361
1362 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001363 case Type::Complex:
1364 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001365 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1366 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001367 ComplexArg->getElementType(),
1368 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001369
1370 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001371
1372 // _Atomic T [extension]
1373 case Type::Atomic:
1374 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001375 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001376 cast<AtomicType>(Param)->getValueType(),
1377 AtomicArg->getValueType(),
1378 Info, Deduced, TDF);
1379
1380 return Sema::TDK_NonDeducedMismatch;
1381
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001382 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001383 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001384 QualType PointeeType;
1385 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1386 PointeeType = PointerArg->getPointeeType();
1387 } else if (const ObjCObjectPointerType *PointerArg
1388 = Arg->getAs<ObjCObjectPointerType>()) {
1389 PointeeType = PointerArg->getPointeeType();
1390 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001391 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Douglas Gregorfc516c92009-06-26 23:27:24 +00001394 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001395 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1396 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001397 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001398 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001399 }
Mike Stump11289f42009-09-09 15:08:12 +00001400
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001401 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001402 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001403 const LValueReferenceType *ReferenceArg =
1404 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001405 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001406 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001407
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001408 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001409 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001410 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001411 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001412
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001413 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001414 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001415 const RValueReferenceType *ReferenceArg =
1416 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001417 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001418 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001420 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1421 cast<RValueReferenceType>(Param)->getPointeeType(),
1422 ReferenceArg->getPointeeType(),
1423 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001426 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001427 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001428 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001429 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001430 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001432
John McCallf7332682010-08-19 00:20:19 +00001433 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001434 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1435 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1436 IncompleteArrayArg->getElementType(),
1437 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001438 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001439
1440 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001441 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001442 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001443 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001444 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001445 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001446
1447 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001448 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001449 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001450 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001451
John McCallf7332682010-08-19 00:20:19 +00001452 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001453 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1454 ConstantArrayParm->getElementType(),
1455 ConstantArrayArg->getElementType(),
1456 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001457 }
1458
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001459 // type [i]
1460 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001461 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001462 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001463 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001464
John McCallf7332682010-08-19 00:20:19 +00001465 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1466
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001467 // Check the element type of the arrays
1468 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001469 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001470 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001471 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1472 DependentArrayParm->getElementType(),
1473 ArrayArg->getElementType(),
1474 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001475 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001476
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001477 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001478 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001479 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001480 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001481 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001482
1483 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001484 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001485 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1486 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001487 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001488 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1489 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001490 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001491 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001492 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001493 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001494 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001495 if (const DependentSizedArrayType *DependentArrayArg
1496 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001497 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001498 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001499 DependentArrayArg->getSizeExpr(),
1500 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001502 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001503 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
1506 // type(*)(T)
1507 // T(*)()
1508 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001509 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001510 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001511 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001512 dyn_cast<FunctionProtoType>(Arg);
1513 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001514 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001515
1516 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001517 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001518
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001520 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001522 != FunctionProtoArg->getRefQualifier() ||
1523 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001524 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001525
Anders Carlsson2128ec72009-06-08 15:19:08 +00001526 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001527 if (Sema::TemplateDeductionResult Result =
1528 DeduceTemplateArgumentsByTypeMatch(
1529 S, TemplateParams, FunctionProtoParam->getReturnType(),
1530 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001531 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001532
Alp Toker9cacbab2014-01-20 20:26:09 +00001533 return DeduceTemplateArguments(
1534 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1535 FunctionProtoParam->getNumParams(),
1536 FunctionProtoArg->param_type_begin(),
1537 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
John McCalle78aac42010-03-10 03:28:59 +00001540 case Type::InjectedClassName: {
1541 // Treat a template's injected-class-name as if the template
1542 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001543 Param = cast<InjectedClassNameType>(Param)
1544 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001545 assert(isa<TemplateSpecializationType>(Param) &&
1546 "injected class name is not a template specialization type");
1547 // fall through
1548 }
1549
Douglas Gregor705c9002009-06-26 20:57:09 +00001550 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001551 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001552 // TT<T>
1553 // TT<i>
1554 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001555 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001556 const TemplateSpecializationType *SpecParam =
1557 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001558
Richard Smith9b296e32016-04-25 19:09:05 +00001559 // When Arg cannot be a derived class, we can just try to deduce template
1560 // arguments from the template-id.
1561 const RecordType *RecordT = Arg->getAs<RecordType>();
1562 if (!(TDF & TDF_DerivedClass) || !RecordT)
1563 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1564 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001565
Richard Smith9b296e32016-04-25 19:09:05 +00001566 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1567 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001568
Richard Smith9b296e32016-04-25 19:09:05 +00001569 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1570 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Richard Smith9b296e32016-04-25 19:09:05 +00001572 if (Result == Sema::TDK_Success)
1573 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001574
Richard Smith9b296e32016-04-25 19:09:05 +00001575 // We cannot inspect base classes as part of deduction when the type
1576 // is incomplete, so either instantiate any templates necessary to
1577 // complete the type, or skip over it if it cannot be completed.
1578 if (!S.isCompleteType(Info.getLocation(), Arg))
1579 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001580
Richard Smith9b296e32016-04-25 19:09:05 +00001581 // C++14 [temp.deduct.call] p4b3:
1582 // If P is a class and P has the form simple-template-id, then the
1583 // transformed A can be a derived class of the deduced A. Likewise if
1584 // P is a pointer to a class of the form simple-template-id, the
1585 // transformed A can be a pointer to a derived class pointed to by the
1586 // deduced A.
1587 //
1588 // These alternatives are considered only if type deduction would
1589 // otherwise fail. If they yield more than one possible deduced A, the
1590 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001591
Faisal Vali683b0742016-05-19 02:28:21 +00001592 // Reset the incorrectly deduced argument from above.
1593 Deduced = DeducedOrig;
1594
1595 // Use data recursion to crawl through the list of base classes.
1596 // Visited contains the set of nodes we have already visited, while
1597 // ToVisit is our stack of records that we still need to visit.
1598 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1599 SmallVector<const RecordType *, 8> ToVisit;
1600 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001601 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001602 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001603 while (!ToVisit.empty()) {
1604 // Retrieve the next class in the inheritance hierarchy.
1605 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001606
Faisal Vali683b0742016-05-19 02:28:21 +00001607 // If we have already seen this type, skip it.
1608 if (!Visited.insert(NextT).second)
1609 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001610
Faisal Vali683b0742016-05-19 02:28:21 +00001611 // If this is a base class, try to perform template argument
1612 // deduction from it.
1613 if (NextT != RecordT) {
1614 TemplateDeductionInfo BaseInfo(Info.getLocation());
1615 Sema::TemplateDeductionResult BaseResult =
1616 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1617 QualType(NextT, 0), BaseInfo, Deduced);
1618
1619 // If template argument deduction for this base was successful,
1620 // note that we had some success. Otherwise, ignore any deductions
1621 // from this base class.
1622 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001623 // If we've already seen some success, then deduction fails due to
1624 // an ambiguity (temp.deduct.call p5).
1625 if (Successful)
1626 return Sema::TDK_MiscellaneousDeductionFailure;
1627
Faisal Vali683b0742016-05-19 02:28:21 +00001628 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001629 std::swap(SuccessfulDeduced, Deduced);
1630
Faisal Vali683b0742016-05-19 02:28:21 +00001631 Info.Param = BaseInfo.Param;
1632 Info.FirstArg = BaseInfo.FirstArg;
1633 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001634 }
1635
1636 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001637 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
Faisal Vali683b0742016-05-19 02:28:21 +00001639 // Visit base classes
1640 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1641 for (const auto &Base : Next->bases()) {
1642 assert(Base.getType()->isRecordType() &&
1643 "Base class that isn't a record?");
1644 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1645 }
1646 }
Mike Stump11289f42009-09-09 15:08:12 +00001647
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001648 if (Successful) {
1649 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001650 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001651 }
Richard Smith9b296e32016-04-25 19:09:05 +00001652
Douglas Gregore81f3e72009-07-07 23:09:34 +00001653 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001654 }
1655
Douglas Gregor637d9982009-06-10 23:47:09 +00001656 // T type::*
1657 // T T::*
1658 // T (type::*)()
1659 // type (T::*)()
1660 // type (type::*)(T)
1661 // type (T::*)(T)
1662 // T (type::*)(T)
1663 // T (T::*)()
1664 // T (T::*)(T)
1665 case Type::MemberPointer: {
1666 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1667 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1668 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001669 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001670
David Majnemera381cda2015-11-30 20:34:28 +00001671 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1672 if (ParamPointeeType->isFunctionType())
1673 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1674 /*IsCtorOrDtor=*/false, Info.getLocation());
1675 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1676 if (ArgPointeeType->isFunctionType())
1677 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1678 /*IsCtorOrDtor=*/false, Info.getLocation());
1679
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001680 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001681 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001682 ParamPointeeType,
1683 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001684 Info, Deduced,
1685 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001686 return Result;
1687
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001688 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1689 QualType(MemPtrParam->getClass(), 0),
1690 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001691 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001692 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001693 }
1694
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001695 // (clang extension)
1696 //
Mike Stump11289f42009-09-09 15:08:12 +00001697 // type(^)(T)
1698 // T(^)()
1699 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001700 case Type::BlockPointer: {
1701 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1702 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001703
Anders Carlssona767eee2009-06-12 16:23:10 +00001704 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001705 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001706
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001707 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1708 BlockPtrParam->getPointeeType(),
1709 BlockPtrArg->getPointeeType(),
1710 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001711 }
1712
Douglas Gregor39c02722011-06-15 16:02:29 +00001713 // (clang extension)
1714 //
1715 // T __attribute__(((ext_vector_type(<integral constant>))))
1716 case Type::ExtVector: {
1717 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1718 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1719 // Make sure that the vectors have the same number of elements.
1720 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1721 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001722
Douglas Gregor39c02722011-06-15 16:02:29 +00001723 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001724 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1725 VectorParam->getElementType(),
1726 VectorArg->getElementType(),
1727 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001728 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001729
1730 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001731 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1732 // We can't check the number of elements, since the argument has a
1733 // dependent number of elements. This can only occur during partial
1734 // ordering.
1735
1736 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001737 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1738 VectorParam->getElementType(),
1739 VectorArg->getElementType(),
1740 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001741 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001742
Douglas Gregor39c02722011-06-15 16:02:29 +00001743 return Sema::TDK_NonDeducedMismatch;
1744 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001745
Douglas Gregor39c02722011-06-15 16:02:29 +00001746 // (clang extension)
1747 //
1748 // T __attribute__(((ext_vector_type(N))))
1749 case Type::DependentSizedExtVector: {
1750 const DependentSizedExtVectorType *VectorParam
1751 = cast<DependentSizedExtVectorType>(Param);
1752
1753 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1754 // Perform deduction on the element types.
1755 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001756 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1757 VectorParam->getElementType(),
1758 VectorArg->getElementType(),
1759 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001760 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001761
Douglas Gregor39c02722011-06-15 16:02:29 +00001762 // Perform deduction on the vector size, if we can.
1763 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001764 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001765 if (!NTTP)
1766 return Sema::TDK_Success;
1767
1768 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1769 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001770 // Note that we use the "array bound" rules here; just like in that
1771 // case, we don't have any particular type for the vector size, but
1772 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001773 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001774 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001775 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001776 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001777
1778 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001779 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1780 // Perform deduction on the element types.
1781 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001782 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1783 VectorParam->getElementType(),
1784 VectorArg->getElementType(),
1785 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001786 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001787
Douglas Gregor39c02722011-06-15 16:02:29 +00001788 // Perform deduction on the vector size, if we can.
1789 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001790 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001791 if (!NTTP)
1792 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001793
Richard Smith5f274382016-09-28 23:55:27 +00001794 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1795 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001796 Info, Deduced);
1797 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001798
Douglas Gregor39c02722011-06-15 16:02:29 +00001799 return Sema::TDK_NonDeducedMismatch;
1800 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001801
Douglas Gregor637d9982009-06-10 23:47:09 +00001802 case Type::TypeOfExpr:
1803 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001804 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001805 case Type::UnresolvedUsing:
1806 case Type::Decltype:
1807 case Type::UnaryTransform:
1808 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001809 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00001810 case Type::DependentTemplateSpecialization:
1811 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001812 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001813 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001814 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001815 }
1816
David Blaikiee4d798f2012-01-20 21:50:17 +00001817 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001818}
1819
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001820static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001821DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001822 TemplateParameterList *TemplateParams,
1823 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001824 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001825 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001826 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001827 // If the template argument is a pack expansion, perform template argument
1828 // deduction against the pattern of that expansion. This only occurs during
1829 // partial ordering.
1830 if (Arg.isPackExpansion())
1831 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001832
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001833 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001834 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001835 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001836
1837 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001838 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001839 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1840 Param.getAsType(),
1841 Arg.getAsType(),
1842 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001843 Info.FirstArg = Param;
1844 Info.SecondArg = Arg;
1845 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001846
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001847 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001848 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001850 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001851 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001852 Info.FirstArg = Param;
1853 Info.SecondArg = Arg;
1854 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001855
1856 case TemplateArgument::TemplateExpansion:
1857 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001859 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001860 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001861 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001862 return Sema::TDK_Success;
1863
1864 Info.FirstArg = Param;
1865 Info.SecondArg = Arg;
1866 return Sema::TDK_NonDeducedMismatch;
1867
1868 case TemplateArgument::NullPtr:
1869 if (Arg.getKind() == TemplateArgument::NullPtr &&
1870 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001871 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001873 Info.FirstArg = Param;
1874 Info.SecondArg = Arg;
1875 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001876
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001877 case TemplateArgument::Integral:
1878 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001879 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001880 return Sema::TDK_Success;
1881
1882 Info.FirstArg = Param;
1883 Info.SecondArg = Arg;
1884 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001885 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001886
1887 if (Arg.getKind() == TemplateArgument::Expression) {
1888 Info.FirstArg = Param;
1889 Info.SecondArg = Arg;
1890 return Sema::TDK_NonDeducedMismatch;
1891 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001892
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001893 Info.FirstArg = Param;
1894 Info.SecondArg = Arg;
1895 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001896
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001897 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001898 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001899 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001900 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001901 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001902 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001903 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001904 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001905 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001906 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001907 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1908 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001909 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001910 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001911 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1912 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001913 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001914 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1915 Arg.getAsDecl(),
1916 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001917 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001919 Info.FirstArg = Param;
1920 Info.SecondArg = Arg;
1921 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001922 }
Mike Stump11289f42009-09-09 15:08:12 +00001923
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001924 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001925 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001926 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001927 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001928 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001929 }
Mike Stump11289f42009-09-09 15:08:12 +00001930
David Blaikiee4d798f2012-01-20 21:50:17 +00001931 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001932}
1933
Douglas Gregor7baabef2010-12-22 18:17:10 +00001934/// \brief Determine whether there is a template argument to be used for
1935/// deduction.
1936///
1937/// This routine "expands" argument packs in-place, overriding its input
1938/// parameters so that \c Args[ArgIdx] will be the available template argument.
1939///
1940/// \returns true if there is another template argument (which will be at
1941/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001942static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1943 unsigned &ArgIdx) {
1944 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001945 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregor7baabef2010-12-22 18:17:10 +00001947 const TemplateArgument &Arg = Args[ArgIdx];
1948 if (Arg.getKind() != TemplateArgument::Pack)
1949 return true;
1950
Richard Smith0bda5b52016-12-23 23:46:56 +00001951 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1952 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001953 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001954 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001955}
1956
Douglas Gregord0ad2942010-12-23 01:24:45 +00001957/// \brief Determine whether the given set of template arguments has a pack
1958/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001959static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1960 bool FoundPackExpansion = false;
1961 for (const auto &A : Args) {
1962 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001963 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001964
1965 if (A.getKind() == TemplateArgument::Pack)
1966 return hasPackExpansionBeforeEnd(A.pack_elements());
1967
1968 if (A.isPackExpansion())
1969 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971
Douglas Gregord0ad2942010-12-23 01:24:45 +00001972 return false;
1973}
1974
Douglas Gregor7baabef2010-12-22 18:17:10 +00001975static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001976DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001977 ArrayRef<TemplateArgument> Params,
1978 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001979 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001980 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1981 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001982 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983 // If the template argument list of P contains a pack expansion that is not
1984 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001985 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001986 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001987 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001989 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 // If P has a form that contains <T> or <i>, then each argument Pi of the
1991 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001992 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001993 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001994 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001995 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001996 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997
Douglas Gregor7baabef2010-12-22 18:17:10 +00001998 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001999 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002000 return NumberOfArgumentsMustMatch
2001 ? Sema::TDK_MiscellaneousDeductionFailure
2002 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Richard Smith26b86ea2016-12-31 21:41:23 +00002004 // C++1z [temp.deduct.type]p9:
2005 // During partial ordering, if Ai was originally a pack expansion [and]
2006 // Pi is not a pack expansion, template argument deduction fails.
2007 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002008 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002010 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002011 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002012 = DeduceTemplateArguments(S, TemplateParams,
2013 Params[ParamIdx], Args[ArgIdx],
2014 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015 return Result;
2016
Douglas Gregor7baabef2010-12-22 18:17:10 +00002017 // Move to the next argument.
2018 ++ArgIdx;
2019 continue;
2020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002022 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002023
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002024 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025 // If Pi is a pack expansion, then the pattern of Pi is compared with
2026 // each remaining argument in the template argument list of A. Each
2027 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002028 // template parameter packs expanded by Pi.
2029 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002031 // FIXME: If there are no remaining arguments, we can bail out early
2032 // and set any deduced parameter packs to an empty argument pack.
2033 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
Richard Smith0a80d572014-05-29 01:12:14 +00002035 // Prepare to deduce the packs within the pattern.
2036 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002037
2038 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002040 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00002041 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002042 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002044 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2045 Info, Deduced))
2046 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Richard Smith0a80d572014-05-29 01:12:14 +00002048 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002051 // Build argument packs for each of the parameter packs expanded by this
2052 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002053 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056
Douglas Gregor7baabef2010-12-22 18:17:10 +00002057 return Sema::TDK_Success;
2058}
2059
Mike Stump11289f42009-09-09 15:08:12 +00002060static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002061DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002062 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002063 const TemplateArgumentList &ParamList,
2064 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002065 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002066 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002067 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002068 ArgList.asArray(), Info, Deduced,
2069 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002070}
2071
Douglas Gregor705c9002009-06-26 20:57:09 +00002072/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002073static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002074 TemplateArgument X,
2075 const TemplateArgument &Y,
2076 bool PackExpansionMatchesPack = false) {
2077 // If we're checking deduced arguments (X) against original arguments (Y),
2078 // we will have flattened packs to non-expansions in X.
2079 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2080 X = X.getPackExpansionPattern();
2081
Douglas Gregor705c9002009-06-26 20:57:09 +00002082 if (X.getKind() != Y.getKind())
2083 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002084
Douglas Gregor705c9002009-06-26 20:57:09 +00002085 switch (X.getKind()) {
2086 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002087 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002088
Douglas Gregor705c9002009-06-26 20:57:09 +00002089 case TemplateArgument::Type:
2090 return Context.getCanonicalType(X.getAsType()) ==
2091 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002092
Douglas Gregor705c9002009-06-26 20:57:09 +00002093 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002094 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002095
2096 case TemplateArgument::NullPtr:
2097 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002098
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002099 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002100 case TemplateArgument::TemplateExpansion:
2101 return Context.getCanonicalTemplateName(
2102 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2103 Context.getCanonicalTemplateName(
2104 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105
Douglas Gregor705c9002009-06-26 20:57:09 +00002106 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002107 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002108
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002109 case TemplateArgument::Expression: {
2110 llvm::FoldingSetNodeID XID, YID;
2111 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002113 return XID == YID;
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
Douglas Gregor705c9002009-06-26 20:57:09 +00002116 case TemplateArgument::Pack:
2117 if (X.pack_size() != Y.pack_size())
2118 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002119
2120 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2121 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002122 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002123 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002124 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002125 return false;
2126
2127 return true;
2128 }
2129
David Blaikiee4d798f2012-01-20 21:50:17 +00002130 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002131}
2132
Douglas Gregorca4686d2011-01-04 23:35:54 +00002133/// \brief Allocate a TemplateArgumentLoc where all locations have
2134/// been initialized to the given location.
2135///
James Dennett634962f2012-06-14 21:40:34 +00002136/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002137/// location information for.
2138///
2139/// \param NTTPType For a declaration template argument, the type of
2140/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002141/// argument. Can be null if no type sugar is available to add to the
2142/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002143///
2144/// \param Loc The source location to use for the resulting template
2145/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002146TemplateArgumentLoc
2147Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2148 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002149 switch (Arg.getKind()) {
2150 case TemplateArgument::Null:
2151 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152
Douglas Gregorca4686d2011-01-04 23:35:54 +00002153 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002154 return TemplateArgumentLoc(
2155 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Douglas Gregorca4686d2011-01-04 23:35:54 +00002157 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002158 if (NTTPType.isNull())
2159 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002160 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2161 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002162 return TemplateArgumentLoc(TemplateArgument(E), E);
2163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Eli Friedmanb826a002012-09-26 02:36:12 +00002165 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002166 if (NTTPType.isNull())
2167 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002168 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2169 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002170 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2171 E);
2172 }
2173
Douglas Gregorca4686d2011-01-04 23:35:54 +00002174 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002175 Expr *E =
2176 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177 return TemplateArgumentLoc(TemplateArgument(E), E);
2178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179
Douglas Gregor9d802122011-03-02 17:09:35 +00002180 case TemplateArgument::Template:
2181 case TemplateArgument::TemplateExpansion: {
2182 NestedNameSpecifierLocBuilder Builder;
2183 TemplateName Template = Arg.getAsTemplate();
2184 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002185 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002186 else if (QualifiedTemplateName *QTN =
2187 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002188 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002189
Douglas Gregor9d802122011-03-02 17:09:35 +00002190 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002191 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002192 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002193
2194 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002195 Loc, Loc);
2196 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002197
Douglas Gregorca4686d2011-01-04 23:35:54 +00002198 case TemplateArgument::Expression:
2199 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200
Douglas Gregorca4686d2011-01-04 23:35:54 +00002201 case TemplateArgument::Pack:
2202 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
David Blaikiee4d798f2012-01-20 21:50:17 +00002205 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002206}
2207
2208
2209/// \brief Convert the given deduced template argument and add it to the set of
2210/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002211static bool
2212ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2213 DeducedTemplateArgument Arg,
2214 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002215 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002216 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002217 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002218 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2219 unsigned ArgumentPackIndex) {
2220 // Convert the deduced template argument into a template
2221 // argument that we can check, almost as if the user had written
2222 // the template argument explicitly.
2223 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002224 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002225
2226 // Check the template argument, converting it as necessary.
2227 return S.CheckTemplateArgument(
2228 Param, ArgLoc, Template, Template->getLocation(),
2229 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002230 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002231 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2232 : Sema::CTAK_Deduced)
2233 : Sema::CTAK_Specified);
2234 };
2235
Douglas Gregorca4686d2011-01-04 23:35:54 +00002236 if (Arg.getKind() == TemplateArgument::Pack) {
2237 // This is a template argument pack, so check each of its arguments against
2238 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002239 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002240 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002241 // When converting the deduced template argument, append it to the
2242 // general output list. We need to do this so that the template argument
2243 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002244 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002245 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002246 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2247 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002248 if (P.isNull()) {
2249 // We deduced arguments for some elements of this pack, but not for
2250 // all of them. This happens if we get a conditionally-non-deduced
2251 // context in a pack expansion (such as an overload set in one of the
2252 // arguments).
2253 S.Diag(Param->getLocation(),
2254 diag::err_template_arg_deduced_incomplete_pack)
2255 << Arg << Param;
2256 return true;
2257 }
Richard Smith37acb792016-02-03 20:15:01 +00002258 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002259 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260
Douglas Gregor51bc5712011-01-05 20:52:18 +00002261 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002262 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002264
Richard Smithdf18ee92016-02-03 20:40:30 +00002265 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002266 // itself, in case that substitution fails.
2267 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002268 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002269 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002270 MultiLevelTemplateArgumentList Args(TemplateArgs);
2271
2272 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2273 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2274 NTTP, Output,
2275 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002276 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002277 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2278 NTTP->getDeclName()).isNull())
2279 return true;
2280 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2281 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2282 TTP, Output,
2283 Template->getSourceRange());
2284 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2285 return true;
2286 }
2287 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002288 }
Richard Smith37acb792016-02-03 20:15:01 +00002289
Douglas Gregorca4686d2011-01-04 23:35:54 +00002290 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002291 Output.push_back(
2292 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002293 return false;
2294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002295
Richard Smith37acb792016-02-03 20:15:01 +00002296 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002297}
2298
Richard Smith1f5be4d2016-12-21 01:10:31 +00002299// FIXME: This should not be a template, but
2300// ClassTemplatePartialSpecializationDecl sadly does not derive from
2301// TemplateDecl.
2302template<typename TemplateDeclT>
2303static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002304 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002305 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2306 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2307 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002308 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002309 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2310
2311 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2312 NamedDecl *Param = TemplateParams->getParam(I);
2313
2314 if (!Deduced[I].isNull()) {
2315 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002316 // We may have had explicitly-specified template arguments for a
2317 // template parameter pack (that may or may not have been extended
2318 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002319 if (Param->isParameterPack() && CurrentInstantiationScope &&
2320 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2321 // Forget the partially-substituted pack; its substitution is now
2322 // complete.
2323 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2324 // We still need to check the argument in case it was extended by
2325 // deduction.
2326 } else {
2327 // We have already fully type-checked and converted this
2328 // argument, because it was explicitly-specified. Just record the
2329 // presence of this argument.
2330 Builder.push_back(Deduced[I]);
2331 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002332 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002333 }
2334
Richard Smith9c0c9862017-01-05 20:27:28 +00002335 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002336 // checked and converted.
2337 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002338 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002339 Info.Param = makeTemplateParameter(Param);
2340 // FIXME: These template arguments are temporary. Free them!
2341 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2342 return Sema::TDK_SubstitutionFailure;
2343 }
2344
2345 continue;
2346 }
2347
2348 // C++0x [temp.arg.explicit]p3:
2349 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2350 // be deduced to an empty sequence of template arguments.
2351 // FIXME: Where did the word "trailing" come from?
2352 if (Param->isTemplateParameterPack()) {
2353 // We may have had explicitly-specified template arguments for this
2354 // template parameter pack. If so, our empty deduction extends the
2355 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2356 const TemplateArgument *ExplicitArgs;
2357 unsigned NumExplicitArgs;
2358 if (CurrentInstantiationScope &&
2359 CurrentInstantiationScope->getPartiallySubstitutedPack(
2360 &ExplicitArgs, &NumExplicitArgs) == Param) {
2361 Builder.push_back(TemplateArgument(
2362 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2363
2364 // Forget the partially-substituted pack; its substitution is now
2365 // complete.
2366 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2367 } else {
2368 // Go through the motions of checking the empty argument pack against
2369 // the parameter pack.
2370 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002371 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2372 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002373 Info.Param = makeTemplateParameter(Param);
2374 // FIXME: These template arguments are temporary. Free them!
2375 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2376 return Sema::TDK_SubstitutionFailure;
2377 }
2378 }
2379 continue;
2380 }
2381
2382 // Substitute into the default template argument, if available.
2383 bool HasDefaultArg = false;
2384 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2385 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002386 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2387 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002388 return Sema::TDK_Incomplete;
2389 }
2390
2391 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2392 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2393 HasDefaultArg);
2394
2395 // If there was no default argument, deduction is incomplete.
2396 if (DefArg.getArgument().isNull()) {
2397 Info.Param = makeTemplateParameter(
2398 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2399 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002400 if (PartialOverloading) break;
2401
Richard Smith1f5be4d2016-12-21 01:10:31 +00002402 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2403 : Sema::TDK_Incomplete;
2404 }
2405
2406 // Check whether we can actually use the default argument.
2407 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2408 TD->getSourceRange().getEnd(), 0, Builder,
2409 Sema::CTAK_Specified)) {
2410 Info.Param = makeTemplateParameter(
2411 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2412 // FIXME: These template arguments are temporary. Free them!
2413 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2414 return Sema::TDK_SubstitutionFailure;
2415 }
2416
2417 // If we get here, we successfully used the default template argument.
2418 }
2419
2420 return Sema::TDK_Success;
2421}
2422
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002423static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002424 if (auto *DC = dyn_cast<DeclContext>(D))
2425 return DC;
2426 return D->getDeclContext();
2427}
2428
2429template<typename T> struct IsPartialSpecialization {
2430 static constexpr bool value = false;
2431};
2432template<>
2433struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2434 static constexpr bool value = true;
2435};
2436template<>
2437struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2438 static constexpr bool value = true;
2439};
2440
2441/// Complete template argument deduction for a partial specialization.
2442template <typename T>
2443static typename std::enable_if<IsPartialSpecialization<T>::value,
2444 Sema::TemplateDeductionResult>::type
2445FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002446 Sema &S, T *Partial, bool IsPartialOrdering,
2447 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002448 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2449 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002450 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002451 EnterExpressionEvaluationContext Unevaluated(
2452 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002453 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454
Richard Smith0da6dc42016-12-24 16:40:51 +00002455 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002456
2457 // C++ [temp.deduct.type]p2:
2458 // [...] or if any template argument remains neither deduced nor
2459 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002460 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002461 if (auto Result = ConvertDeducedTemplateArguments(
2462 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002463 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
Douglas Gregor684268d2010-04-29 06:21:43 +00002465 // Form the template argument list from the deduced template arguments.
2466 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002467 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002468
Douglas Gregor684268d2010-04-29 06:21:43 +00002469 Info.reset(DeducedArgumentList);
2470
2471 // Substitute the deduced template arguments into the template
2472 // arguments of the class template partial specialization, and
2473 // verify that the instantiated template arguments are both valid
2474 // and are equivalent to the template arguments originally provided
2475 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002476 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002477 auto *Template = Partial->getSpecializedTemplate();
2478 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2479 Partial->getTemplateArgsAsWritten();
2480 const TemplateArgumentLoc *PartialTemplateArgs =
2481 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002482
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002483 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2484 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002485
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002486 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002487 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2488 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2489 if (ParamIdx >= Partial->getTemplateParameters()->size())
2490 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2491
Richard Smith0da6dc42016-12-24 16:40:51 +00002492 Decl *Param = const_cast<NamedDecl *>(
2493 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002494 Info.Param = makeTemplateParameter(Param);
2495 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2496 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002497 }
2498
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002499 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002500 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2501 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002502 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002503
Richard Smith0da6dc42016-12-24 16:40:51 +00002504 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002505 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002506 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002507 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002508 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002509 Info.FirstArg = TemplateArgs[I];
2510 Info.SecondArg = InstArg;
2511 return Sema::TDK_NonDeducedMismatch;
2512 }
2513 }
2514
2515 if (Trap.hasErrorOccurred())
2516 return Sema::TDK_SubstitutionFailure;
2517
2518 return Sema::TDK_Success;
2519}
2520
Richard Smith0e617ec2016-12-27 07:56:27 +00002521/// Complete template argument deduction for a class or variable template,
2522/// when partial ordering against a partial specialization.
2523// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002524static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002525 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2526 const TemplateArgumentList &TemplateArgs,
2527 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2528 TemplateDeductionInfo &Info) {
2529 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002530 EnterExpressionEvaluationContext Unevaluated(
2531 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002532 Sema::SFINAETrap Trap(S);
2533
2534 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2535
2536 // C++ [temp.deduct.type]p2:
2537 // [...] or if any template argument remains neither deduced nor
2538 // explicitly specified, template argument deduction fails.
2539 SmallVector<TemplateArgument, 4> Builder;
2540 if (auto Result = ConvertDeducedTemplateArguments(
2541 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2542 return Result;
2543
2544 // Check that we produced the correct argument list.
2545 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2546 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2547 TemplateArgument InstArg = Builder[I];
2548 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2549 /*PackExpansionMatchesPack*/true)) {
2550 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2551 Info.FirstArg = TemplateArgs[I];
2552 Info.SecondArg = InstArg;
2553 return Sema::TDK_NonDeducedMismatch;
2554 }
2555 }
2556
2557 if (Trap.hasErrorOccurred())
2558 return Sema::TDK_SubstitutionFailure;
2559
2560 return Sema::TDK_Success;
2561}
2562
2563
Douglas Gregor170bc422009-06-12 22:31:52 +00002564/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002565/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002566/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002567Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002568Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002569 const TemplateArgumentList &TemplateArgs,
2570 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002571 if (Partial->isInvalidDecl())
2572 return TDK_Invalid;
2573
Douglas Gregor170bc422009-06-12 22:31:52 +00002574 // C++ [temp.class.spec.match]p2:
2575 // A partial specialization matches a given actual template
2576 // argument list if the template arguments of the partial
2577 // specialization can be deduced from the actual template argument
2578 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002579
2580 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002581 EnterExpressionEvaluationContext Unevaluated(
2582 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002583 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002584
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002585 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002586 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002587 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002588 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002589 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002590 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002591 TemplateArgs, Info, Deduced))
2592 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002593
Richard Smith80934652012-07-16 01:09:10 +00002594 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002595 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2596 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002597 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002598 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002599
Douglas Gregore1416332009-06-14 08:02:22 +00002600 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002601 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602
Richard Smith87d263e2016-12-25 08:05:23 +00002603 return ::FinishTemplateArgumentDeduction(
2604 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002605}
Douglas Gregor91772d12009-06-13 00:26:55 +00002606
Larisse Voufo39a1e502013-08-06 01:03:05 +00002607/// \brief Perform template argument deduction to determine whether
2608/// the given template arguments match the given variable template
2609/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002610Sema::TemplateDeductionResult
2611Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2612 const TemplateArgumentList &TemplateArgs,
2613 TemplateDeductionInfo &Info) {
2614 if (Partial->isInvalidDecl())
2615 return TDK_Invalid;
2616
2617 // C++ [temp.class.spec.match]p2:
2618 // A partial specialization matches a given actual template
2619 // argument list if the template arguments of the partial
2620 // specialization can be deduced from the actual template argument
2621 // list (14.8.2).
2622
2623 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002624 EnterExpressionEvaluationContext Unevaluated(
2625 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002626 SFINAETrap Trap(*this);
2627
2628 SmallVector<DeducedTemplateArgument, 4> Deduced;
2629 Deduced.resize(Partial->getTemplateParameters()->size());
2630 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2631 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2632 TemplateArgs, Info, Deduced))
2633 return Result;
2634
2635 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002636 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2637 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002638 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002639 return TDK_InstantiationDepth;
2640
2641 if (Trap.hasErrorOccurred())
2642 return Sema::TDK_SubstitutionFailure;
2643
Richard Smith87d263e2016-12-25 08:05:23 +00002644 return ::FinishTemplateArgumentDeduction(
2645 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002646}
2647
Douglas Gregorfc516c92009-06-26 23:27:24 +00002648/// \brief Determine whether the given type T is a simple-template-id type.
2649static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002650 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002651 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002652 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002653
Douglas Gregorfc516c92009-06-26 23:27:24 +00002654 return false;
2655}
Douglas Gregor9b146582009-07-08 20:55:45 +00002656
2657/// \brief Substitute the explicitly-provided template arguments into the
2658/// given function template according to C++ [temp.arg.explicit].
2659///
2660/// \param FunctionTemplate the function template into which the explicit
2661/// template arguments will be substituted.
2662///
James Dennett634962f2012-06-14 21:40:34 +00002663/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002664/// arguments.
2665///
Mike Stump11289f42009-09-09 15:08:12 +00002666/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002667/// with the converted and checked explicit template arguments.
2668///
Mike Stump11289f42009-09-09 15:08:12 +00002669/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002670/// parameters.
2671///
2672/// \param FunctionType if non-NULL, the result type of the function template
2673/// will also be instantiated and the pointed-to value will be updated with
2674/// the instantiated function type.
2675///
2676/// \param Info if substitution fails for any reason, this object will be
2677/// populated with more information about the failure.
2678///
2679/// \returns TDK_Success if substitution was successful, or some failure
2680/// condition.
2681Sema::TemplateDeductionResult
2682Sema::SubstituteExplicitTemplateArguments(
2683 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002684 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002685 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2686 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002687 QualType *FunctionType,
2688 TemplateDeductionInfo &Info) {
2689 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2690 TemplateParameterList *TemplateParams
2691 = FunctionTemplate->getTemplateParameters();
2692
John McCall6b51f282009-11-23 01:53:49 +00002693 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002694 // No arguments to substitute; just copy over the parameter types and
2695 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002696 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002697 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002698
Douglas Gregor9b146582009-07-08 20:55:45 +00002699 if (FunctionType)
2700 *FunctionType = Function->getType();
2701 return TDK_Success;
2702 }
Mike Stump11289f42009-09-09 15:08:12 +00002703
Eli Friedman77dcc722012-02-08 03:07:05 +00002704 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002705 EnterExpressionEvaluationContext Unevaluated(
2706 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002707 SFINAETrap Trap(*this);
2708
Douglas Gregor9b146582009-07-08 20:55:45 +00002709 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002710 // Template arguments that are present shall be specified in the
2711 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002712 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002713 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002714 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002715
2716 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002717 // explicitly-specified template arguments against this function template,
2718 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002719 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00002720 InstantiatingTemplate Inst(
2721 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
2722 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002723 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002724 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002725
Richard Smith11255ec2017-01-18 19:19:22 +00002726 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2727 ExplicitTemplateArgs, true, Builder, false) ||
2728 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002729 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002730 if (Index >= TemplateParams->size())
2731 Index = TemplateParams->size() - 1;
2732 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002733 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002734 }
Mike Stump11289f42009-09-09 15:08:12 +00002735
Douglas Gregor9b146582009-07-08 20:55:45 +00002736 // Form the template argument list from the explicitly-specified
2737 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002738 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002739 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002740 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002741
John McCall036855a2010-10-12 19:40:14 +00002742 // Template argument deduction and the final substitution should be
2743 // done in the context of the templated declaration. Explicit
2744 // argument substitution, on the other hand, needs to happen in the
2745 // calling context.
2746 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2747
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002748 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002749 // note that the template argument pack is partially substituted and record
2750 // the explicit template arguments. They'll be used as part of deduction
2751 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002752 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2753 const TemplateArgument &Arg = Builder[I];
2754 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002755 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002756 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002757 Arg.pack_begin(),
2758 Arg.pack_size());
2759 break;
2760 }
2761 }
2762
Richard Smith5e580292012-02-10 09:58:53 +00002763 const FunctionProtoType *Proto
2764 = Function->getType()->getAs<FunctionProtoType>();
2765 assert(Proto && "Function template does not have a prototype?");
2766
Richard Smith70b13042015-01-09 01:19:56 +00002767 // Isolate our substituted parameters from our caller.
2768 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2769
John McCallc8e321d2016-03-01 02:09:25 +00002770 ExtParameterInfoBuilder ExtParamInfos;
2771
Douglas Gregor9b146582009-07-08 20:55:45 +00002772 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002773 // explicitly-specified template arguments. If the function has a trailing
2774 // return type, substitute it after the arguments to ensure we substitute
2775 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002776 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002777 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002778 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002779 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002780 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002781 return TDK_SubstitutionFailure;
2782 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002783
Richard Smith5e580292012-02-10 09:58:53 +00002784 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002785 QualType ResultType;
2786 {
2787 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002788 // If a declaration declares a member function or member function
2789 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002790 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002791 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002792 // declarator.
2793 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002794 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002795 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2796 ThisContext = Method->getParent();
2797 ThisTypeQuals = Method->getTypeQualifiers();
2798 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002799
Douglas Gregor3024f072012-04-16 07:05:22 +00002800 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002801 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002802
2803 ResultType =
2804 SubstType(Proto->getReturnType(),
2805 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2806 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002807 if (ResultType.isNull() || Trap.hasErrorOccurred())
2808 return TDK_SubstitutionFailure;
2809 }
John McCallc8e321d2016-03-01 02:09:25 +00002810
Richard Smith5e580292012-02-10 09:58:53 +00002811 // Instantiate the types of each of the function parameters given the
2812 // explicitly-specified template arguments if we didn't do so earlier.
2813 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002814 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002815 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002816 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002817 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002818 return TDK_SubstitutionFailure;
2819
Douglas Gregor9b146582009-07-08 20:55:45 +00002820 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002821 auto EPI = Proto->getExtProtoInfo();
2822 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002823 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002824 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002825 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002826 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002827 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2828 return TDK_SubstitutionFailure;
2829 }
Mike Stump11289f42009-09-09 15:08:12 +00002830
Douglas Gregor9b146582009-07-08 20:55:45 +00002831 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002832 // Trailing template arguments that can be deduced (14.8.2) may be
2833 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002834 // template arguments can be deduced, they may all be omitted; in this
2835 // case, the empty template argument list <> itself may also be omitted.
2836 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002837 // Take all of the explicitly-specified arguments and put them into
2838 // the set of deduced template arguments. Explicitly-specified
2839 // parameter packs, however, will be set to NULL since the deduction
2840 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002841 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002842 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2843 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2844 if (Arg.getKind() == TemplateArgument::Pack)
2845 Deduced.push_back(DeducedTemplateArgument());
2846 else
2847 Deduced.push_back(Arg);
2848 }
Mike Stump11289f42009-09-09 15:08:12 +00002849
Douglas Gregor9b146582009-07-08 20:55:45 +00002850 return TDK_Success;
2851}
2852
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002853/// \brief Check whether the deduced argument type for a call to a function
2854/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002855static bool
2856CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002857 QualType DeducedA) {
2858 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002859
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002860 QualType A = OriginalArg.OriginalArgType;
2861 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002862
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002863 // Check for type equality (top-level cv-qualifiers are ignored).
2864 if (Context.hasSameUnqualifiedType(A, DeducedA))
2865 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002866
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002867 // Strip off references on the argument types; they aren't needed for
2868 // the following checks.
2869 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2870 DeducedA = DeducedARef->getPointeeType();
2871 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2872 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002873
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002874 // C++ [temp.deduct.call]p4:
2875 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002876 // - If the original P is a reference type, the deduced A (i.e., the
2877 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002878 // the transformed A.
2879 if (const ReferenceType *OriginalParamRef
2880 = OriginalParamType->getAs<ReferenceType>()) {
2881 // We don't want to keep the reference around any more.
2882 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002883
Richard Smith1be59c52016-10-22 01:32:19 +00002884 // FIXME: Resolve core issue (no number yet): if the original P is a
2885 // reference type and the transformed A is function type "noexcept F",
2886 // the deduced A can be F.
2887 QualType Tmp;
2888 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2889 return false;
2890
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002891 Qualifiers AQuals = A.getQualifiers();
2892 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002893
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002894 // Under Objective-C++ ARC, the deduced type may have implicitly
2895 // been given strong or (when dealing with a const reference)
2896 // unsafe_unretained lifetime. If so, update the original
2897 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002898 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002899 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2900 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2901 (DeducedAQuals.hasConst() &&
2902 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2903 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002904 }
2905
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002906 if (AQuals == DeducedAQuals) {
2907 // Qualifiers match; there's nothing to do.
2908 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002909 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002910 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002911 // Qualifiers are compatible, so have the argument type adopt the
2912 // deduced argument type's qualifiers as if we had performed the
2913 // qualification conversion.
2914 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2915 }
2916 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002917
2918 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002919 // type that can be converted to the deduced A via a function pointer
2920 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002921 //
Richard Smith1be59c52016-10-22 01:32:19 +00002922 // Also allow conversions which merely strip __attribute__((noreturn)) from
2923 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002924 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002925 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002926 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002927 (S.IsQualificationConversion(A, DeducedA, false,
2928 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002929 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002930 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002931
Simon Pilgrim728134c2016-08-12 11:43:57 +00002932 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002933 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002934 // [...] Likewise, if P is a pointer to a class of the form
2935 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002936 // derived class pointed to by the deduced A.
2937 if (const PointerType *OriginalParamPtr
2938 = OriginalParamType->getAs<PointerType>()) {
2939 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2940 if (const PointerType *APtr = A->getAs<PointerType>()) {
2941 if (A->getPointeeType()->isRecordType()) {
2942 OriginalParamType = OriginalParamPtr->getPointeeType();
2943 DeducedA = DeducedAPtr->getPointeeType();
2944 A = APtr->getPointeeType();
2945 }
2946 }
2947 }
2948 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002949
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002950 if (Context.hasSameUnqualifiedType(A, DeducedA))
2951 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002952
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002953 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002954 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002955 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002956
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002957 return true;
2958}
2959
Richard Smithc92d2062017-01-05 23:02:44 +00002960/// Find the pack index for a particular parameter index in an instantiation of
2961/// a function template with specific arguments.
2962///
2963/// \return The pack index for whichever pack produced this parameter, or -1
2964/// if this was not produced by a parameter. Intended to be used as the
2965/// ArgumentPackSubstitutionIndex for further substitutions.
2966// FIXME: We should track this in OriginalCallArgs so we don't need to
2967// reconstruct it here.
2968static unsigned getPackIndexForParam(Sema &S,
2969 FunctionTemplateDecl *FunctionTemplate,
2970 const MultiLevelTemplateArgumentList &Args,
2971 unsigned ParamIdx) {
2972 unsigned Idx = 0;
2973 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2974 if (PD->isParameterPack()) {
2975 unsigned NumExpansions =
2976 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2977 if (Idx + NumExpansions > ParamIdx)
2978 return ParamIdx - Idx;
2979 Idx += NumExpansions;
2980 } else {
2981 if (Idx == ParamIdx)
2982 return -1; // Not a pack expansion
2983 ++Idx;
2984 }
2985 }
2986
2987 llvm_unreachable("parameter index would not be produced from template");
2988}
2989
Mike Stump11289f42009-09-09 15:08:12 +00002990/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002991/// checking the deduced template arguments for completeness and forming
2992/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002993///
2994/// \param OriginalCallArgs If non-NULL, the original call arguments against
2995/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00002996Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
2997 FunctionTemplateDecl *FunctionTemplate,
2998 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2999 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3000 TemplateDeductionInfo &Info,
3001 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3002 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003003 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003004 EnterExpressionEvaluationContext Unevaluated(
3005 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003006 SFINAETrap Trap(*this);
3007
Douglas Gregor9b146582009-07-08 20:55:45 +00003008 // Enter a new template instantiation context while we instantiate the
3009 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003010 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003011 InstantiatingTemplate Inst(
3012 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3013 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003014 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003015 return TDK_InstantiationDepth;
3016
John McCalle23b8712010-04-29 01:18:58 +00003017 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003018
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003019 // C++ [temp.deduct.type]p2:
3020 // [...] or if any template argument remains neither deduced nor
3021 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003022 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003023 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003024 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003025 CurrentInstantiationScope, NumExplicitlySpecified,
3026 PartialOverloading))
3027 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003028
Richard Smith6eedfe72017-01-09 08:01:21 +00003029 // C++ [temp.deduct.call]p10: [DR1391]
3030 // If deduction succeeds for all parameters that contain
3031 // template-parameters that participate in template argument deduction,
3032 // and all template arguments are explicitly specified, deduced, or
3033 // obtained from default template arguments, remaining parameters are then
3034 // compared with the corresponding arguments. For each remaining parameter
3035 // P with a type that was non-dependent before substitution of any
3036 // explicitly-specified template arguments, if the corresponding argument
3037 // A cannot be implicitly converted to P, deduction fails.
3038 if (CheckNonDependent())
3039 return TDK_NonDependentConversionFailure;
3040
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003041 // Form the template argument list from the deduced template arguments.
3042 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003043 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003044 Info.reset(DeducedArgumentList);
3045
Mike Stump11289f42009-09-09 15:08:12 +00003046 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003047 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003048 DeclContext *Owner = FunctionTemplate->getDeclContext();
3049 if (FunctionTemplate->getFriendObjectKind())
3050 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003051 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003052 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003053 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003054 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003055 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003056
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003058 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
Mike Stump11289f42009-09-09 15:08:12 +00003060 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003061 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003062 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3063 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003064 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003065
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003066 // There may have been an error that did not prevent us from constructing a
3067 // declaration. Mark the declaration invalid and return with a substitution
3068 // failure.
3069 if (Trap.hasErrorOccurred()) {
3070 Specialization->setInvalidDecl(true);
3071 return TDK_SubstitutionFailure;
3072 }
3073
Douglas Gregore65aacb2011-06-16 16:50:48 +00003074 if (OriginalCallArgs) {
3075 // C++ [temp.deduct.call]p4:
3076 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003077 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003078 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003079 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003080 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3081 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003082
Richard Smithc92d2062017-01-05 23:02:44 +00003083 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003084 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003085 // FIXME: This presumably means a pack ended up smaller than we
3086 // expected while deducing. Should this not result in deduction
3087 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003088 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003089
Richard Smithc92d2062017-01-05 23:02:44 +00003090 QualType DeducedA;
3091 if (!OriginalArg.DecomposedParam) {
3092 // P is one of the function parameters, just look up its substituted
3093 // type.
3094 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3095 } else {
3096 // P is a decomposed element of a parameter corresponding to a
3097 // braced-init-list argument. Substitute back into P to find the
3098 // deduced A.
3099 QualType &CacheEntry =
3100 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3101 if (CacheEntry.isNull()) {
3102 ArgumentPackSubstitutionIndexRAII PackIndex(
3103 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3104 ParamIdx));
3105 CacheEntry =
3106 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3107 Specialization->getTypeSpecStartLoc(),
3108 Specialization->getDeclName());
3109 }
3110 DeducedA = CacheEntry;
3111 }
3112
Richard Smith9b534542015-12-31 02:02:54 +00003113 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3114 Info.FirstArg = TemplateArgument(DeducedA);
3115 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3116 Info.CallArgIndex = OriginalArg.ArgIdx;
Richard Smithc92d2062017-01-05 23:02:44 +00003117 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3118 : TDK_DeducedMismatch;
Richard Smith9b534542015-12-31 02:02:54 +00003119 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003120 }
3121 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003122
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003123 // If we suppressed any diagnostics while performing template argument
3124 // deduction, and if we haven't already instantiated this declaration,
3125 // keep track of these diagnostics. They'll be emitted if this specialization
3126 // is actually used.
3127 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003128 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003129 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3130 if (Pos == SuppressedDiagnostics.end())
3131 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3132 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003134
Mike Stump11289f42009-09-09 15:08:12 +00003135 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003136}
3137
John McCall8d08b9b2010-08-27 09:08:28 +00003138/// Gets the type of a function for template-argument-deducton
3139/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003140static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003141 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003142 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003143 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003144 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003145 return QualType();
3146
John McCallc1f69982010-02-02 02:21:27 +00003147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003148 if (Method->isInstance()) {
3149 // An instance method that's referenced in a form that doesn't
3150 // look like a member pointer is just invalid.
3151 if (!R.HasFormOfMemberPointer) return QualType();
3152
Richard Smith2a7d4812013-05-04 07:00:32 +00003153 return S.Context.getMemberPointerType(Fn->getType(),
3154 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003155 }
3156
3157 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003158 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003159}
3160
3161/// Apply the deduction rules for overload sets.
3162///
3163/// \return the null type if this argument should be treated as an
3164/// undeduced context
3165static QualType
3166ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003167 Expr *Arg, QualType ParamType,
3168 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003169
John McCall8d08b9b2010-08-27 09:08:28 +00003170 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003171
John McCall8d08b9b2010-08-27 09:08:28 +00003172 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003173
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003174 // C++0x [temp.deduct.call]p4
3175 unsigned TDF = 0;
3176 if (ParamWasReference)
3177 TDF |= TDF_ParamWithReferenceType;
3178 if (R.IsAddressOfOperand)
3179 TDF |= TDF_IgnoreQualifiers;
3180
John McCallc1f69982010-02-02 02:21:27 +00003181 // C++0x [temp.deduct.call]p6:
3182 // When P is a function type, pointer to function type, or pointer
3183 // to member function type:
3184
3185 if (!ParamType->isFunctionType() &&
3186 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003187 !ParamType->isMemberFunctionPointerType()) {
3188 if (Ovl->hasExplicitTemplateArgs()) {
3189 // But we can still look for an explicit specialization.
3190 if (FunctionDecl *ExplicitSpec
3191 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003192 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003193 }
John McCallc1f69982010-02-02 02:21:27 +00003194
George Burgess IVcc2f3552016-03-19 21:51:45 +00003195 DeclAccessPair DAP;
3196 if (FunctionDecl *Viable =
3197 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3198 return GetTypeOfFunction(S, R, Viable);
3199
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003200 return QualType();
3201 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003202
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003203 // Gather the explicit template arguments, if any.
3204 TemplateArgumentListInfo ExplicitTemplateArgs;
3205 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003206 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003207 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003208 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3209 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003210 NamedDecl *D = (*I)->getUnderlyingDecl();
3211
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003212 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3213 // - If the argument is an overload set containing one or more
3214 // function templates, the parameter is treated as a
3215 // non-deduced context.
3216 if (!Ovl->hasExplicitTemplateArgs())
3217 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003218
3219 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003220 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003221 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003222 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3223 Specialization, Info))
3224 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003225
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003226 D = Specialization;
3227 }
John McCallc1f69982010-02-02 02:21:27 +00003228
3229 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003230 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003231 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003232
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003233 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003234 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003235 ArgType->isFunctionType())
3236 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
John McCallc1f69982010-02-02 02:21:27 +00003238 // - If the argument is an overload set (not containing function
3239 // templates), trial argument deduction is attempted using each
3240 // of the members of the set. If deduction succeeds for only one
3241 // of the overload set members, that member is used as the
3242 // argument value for the deduction. If deduction succeeds for
3243 // more than one member of the overload set the parameter is
3244 // treated as a non-deduced context.
3245
3246 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3247 // Type deduction is done independently for each P/A pair, and
3248 // the deduced template argument values are then combined.
3249 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003250 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003251 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003252 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003253 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003254 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3255 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003256 if (Result) continue;
3257 if (!Match.isNull()) return QualType();
3258 Match = ArgType;
3259 }
3260
3261 return Match;
3262}
3263
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003265/// described in C++ [temp.deduct.call].
3266///
3267/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003268/// argument deduction based on this P/A pair because the argument is an
3269/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003270static bool AdjustFunctionParmAndArgTypesForDeduction(
3271 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3272 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003273 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003274 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003275 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003276 if (ParamType.hasQualifiers())
3277 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003278
3279 // [...] If P is a reference type, the type referred to by P is
3280 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003281 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003282 if (ParamRefType)
3283 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003284
Nathan Sidwell96090022015-01-16 15:20:14 +00003285 // Overload sets usually make this parameter an undeduced context,
3286 // but there are sometimes special circumstances. Typically
3287 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003288 if (ArgType == S.Context.OverloadTy) {
3289 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3290 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003291 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003292 if (ArgType.isNull())
3293 return true;
3294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003295
Douglas Gregor7825bf32011-01-06 22:09:01 +00003296 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003297 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003298 if (ArgType->isIncompleteArrayType()) {
3299 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003300 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003301 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003302
Richard Smith32918772017-02-14 00:25:28 +00003303 // C++1z [temp.deduct.call]p3:
3304 // If P is a forwarding reference and the argument is an lvalue, the type
3305 // "lvalue reference to A" is used in place of A for type deduction.
3306 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003307 Arg->isLValue())
3308 ArgType = S.Context.getLValueReferenceType(ArgType);
3309 } else {
3310 // C++ [temp.deduct.call]p2:
3311 // If P is not a reference type:
3312 // - If A is an array type, the pointer type produced by the
3313 // array-to-pointer standard conversion (4.2) is used in place of
3314 // A for type deduction; otherwise,
3315 if (ArgType->isArrayType())
3316 ArgType = S.Context.getArrayDecayedType(ArgType);
3317 // - If A is a function type, the pointer type produced by the
3318 // function-to-pointer standard conversion (4.3) is used in place
3319 // of A for type deduction; otherwise,
3320 else if (ArgType->isFunctionType())
3321 ArgType = S.Context.getPointerType(ArgType);
3322 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003323 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003324 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003325 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003326 }
3327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328
Douglas Gregor7825bf32011-01-06 22:09:01 +00003329 // C++0x [temp.deduct.call]p4:
3330 // In general, the deduction process attempts to find template argument
3331 // values that will make the deduced A identical to A (after the type A
3332 // is transformed as described above). [...]
3333 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334
Douglas Gregor7825bf32011-01-06 22:09:01 +00003335 // - If the original P is a reference type, the deduced A (i.e., the
3336 // type referred to by the reference) can be more cv-qualified than
3337 // the transformed A.
3338 if (ParamRefType)
3339 TDF |= TDF_ParamWithReferenceType;
3340 // - The transformed A can be another pointer or pointer to member
3341 // type that can be converted to the deduced A via a qualification
3342 // conversion (4.4).
3343 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3344 ArgType->isObjCObjectPointerType())
3345 TDF |= TDF_IgnoreQualifiers;
3346 // - If P is a class and P has the form simple-template-id, then the
3347 // transformed A can be a derived class of the deduced A. Likewise,
3348 // if P is a pointer to a class of the form simple-template-id, the
3349 // transformed A can be a pointer to a derived class pointed to by
3350 // the deduced A.
3351 if (isSimpleTemplateIdType(ParamType) ||
3352 (isa<PointerType>(ParamType) &&
3353 isSimpleTemplateIdType(
3354 ParamType->getAs<PointerType>()->getPointeeType())))
3355 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356
Douglas Gregor7825bf32011-01-06 22:09:01 +00003357 return false;
3358}
3359
Richard Smithf0393bf2017-02-16 04:22:56 +00003360static bool
3361hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3362 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003363
Richard Smith707eab62017-01-05 04:08:31 +00003364static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003365 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3366 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003367 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3368 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003369 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003370
3371/// \brief Attempt template argument deduction from an initializer list
3372/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003373static Sema::TemplateDeductionResult DeduceFromInitializerList(
3374 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3375 InitListExpr *ILE, TemplateDeductionInfo &Info,
3376 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003377 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3378 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003379 // C++ [temp.deduct.call]p1: (CWG 1591)
3380 // If removing references and cv-qualifiers from P gives
3381 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3382 // a non-empty initializer list, then deduction is performed instead for
3383 // each element of the initializer list, taking P0 as a function template
3384 // parameter type and the initializer element as its argument
3385 //
Richard Smith707eab62017-01-05 04:08:31 +00003386 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003387 if (!ILE->getNumInits())
3388 return Sema::TDK_Success;
3389
Richard Smitha7d5ec92017-01-04 19:47:19 +00003390 QualType ElTy;
3391 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3392 if (ArrTy)
3393 ElTy = ArrTy->getElementType();
3394 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3395 // Otherwise, an initializer list argument causes the parameter to be
3396 // considered a non-deduced context
3397 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003398 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003399
Faisal Valif6dfdb32015-12-10 05:36:39 +00003400 // Deduction only needs to be done for dependent types.
3401 if (ElTy->isDependentType()) {
3402 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003403 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003404 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003405 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003406 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003407 }
3408 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003409
3410 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3411 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003412 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003413 // Determine the array bound is something we can deduce.
3414 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003415 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003416 // We can perform template argument deduction for the given non-type
3417 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003418 // C++ [temp.deduct.type]p13:
3419 // The type of N in the type T[N] is std::size_t.
3420 QualType T = S.Context.getSizeType();
3421 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003422 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003423 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003424 /*ArrayBound=*/true, Info, Deduced))
3425 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003426 }
3427 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003428
3429 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003430}
3431
Richard Smith707eab62017-01-05 04:08:31 +00003432/// \brief Perform template argument deduction per [temp.deduct.call] for a
3433/// single parameter / argument pair.
3434static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003435 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3436 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003437 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3438 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003439 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003440 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003441 QualType OrigParamType = ParamType;
3442
3443 // If P is a reference type [...]
3444 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003445 if (AdjustFunctionParmAndArgTypesForDeduction(
3446 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003447 return Sema::TDK_Success;
3448
Richard Smith707eab62017-01-05 04:08:31 +00003449 // If [...] the argument is a non-empty initializer list [...]
3450 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3451 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003452 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003453
3454 // [...] the deduction process attempts to find template argument values
3455 // that will make the deduced A identical to A
3456 //
3457 // Keep track of the argument type and corresponding parameter index,
3458 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003459 OriginalCallArgs.push_back(
3460 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003461 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003462 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003463}
3464
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003465/// \brief Perform template argument deduction from a function call
3466/// (C++ [temp.deduct.call]).
3467///
3468/// \param FunctionTemplate the function template for which we are performing
3469/// template argument deduction.
3470///
James Dennett18348b62012-06-22 08:52:37 +00003471/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003472/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003473///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003474/// \param Args the function call arguments
3475///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003476/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003477/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003478/// template argument deduction.
3479///
3480/// \param Info the argument will be updated to provide additional information
3481/// about template argument deduction.
3482///
Richard Smith6eedfe72017-01-09 08:01:21 +00003483/// \param CheckNonDependent A callback to invoke to check conversions for
3484/// non-dependent parameters, between deduction and substitution, per DR1391.
3485/// If this returns true, substitution will be skipped and we return
3486/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3487/// types (after substituting explicit template arguments).
3488///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003489/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003490Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3491 FunctionTemplateDecl *FunctionTemplate,
3492 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003493 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003494 bool PartialOverloading,
3495 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003496 if (FunctionTemplate->isInvalidDecl())
3497 return TDK_Invalid;
3498
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003499 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003500 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003501
Richard Smith32918772017-02-14 00:25:28 +00003502 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3503
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003504 // C++ [temp.deduct.call]p1:
3505 // Template argument deduction is done by comparing each function template
3506 // parameter type (call it P) with the type of the corresponding argument
3507 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003508 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003509 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003510 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003511 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003512 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003513 if (Proto->isTemplateVariadic())
3514 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003515 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003516 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003517 }
Mike Stump11289f42009-09-09 15:08:12 +00003518
Douglas Gregor89026b52009-06-30 23:57:56 +00003519 // The types of the parameters from which we will perform template argument
3520 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003521 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003522 TemplateParameterList *TemplateParams
3523 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003524 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003525 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003526 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003527 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003528 TemplateDeductionResult Result =
3529 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003530 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003531 Deduced,
3532 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003533 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003534 Info);
3535 if (Result)
3536 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003537
3538 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003539 } else {
3540 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003541 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003542 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3543 }
Mike Stump11289f42009-09-09 15:08:12 +00003544
Richard Smith6eedfe72017-01-09 08:01:21 +00003545 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003546
3547 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3548 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003549 // C++ [demp.deduct.call]p1: (DR1391)
3550 // Template argument deduction is done by comparing each function template
3551 // parameter that contains template-parameters that participate in
3552 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003553 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003554 return Sema::TDK_Success;
3555
Richard Smith707eab62017-01-05 04:08:31 +00003556 // ... with the type of the corresponding argument
3557 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003558 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003559 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003560 };
3561
Douglas Gregor89026b52009-06-30 23:57:56 +00003562 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003563 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003564 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003565 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003566 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003567 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003568
Richard Smitha7d5ec92017-01-04 19:47:19 +00003569 const PackExpansionType *ParamExpansion =
3570 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003571 if (!ParamExpansion) {
3572 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003573 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003574 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Richard Smith6eedfe72017-01-09 08:01:21 +00003576 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003577 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003578 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003579
Douglas Gregor7825bf32011-01-06 22:09:01 +00003580 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582
Richard Smithde0d34a2017-01-09 07:14:40 +00003583 QualType ParamPattern = ParamExpansion->getPattern();
3584 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3585 ParamPattern);
3586
Douglas Gregor7825bf32011-01-06 22:09:01 +00003587 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588 // For a function parameter pack that occurs at the end of the
3589 // parameter-declaration-list, the type A of each remaining argument of
3590 // the call is compared with the type P of the declarator-id of the
3591 // function parameter pack. Each comparison deduces template arguments
3592 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003593 // the function parameter pack. When a function parameter pack appears
3594 // in a non-deduced context [not at the end of the list], the type of
3595 // that parameter pack is never deduced.
3596 //
3597 // FIXME: The above rule allows the size of the parameter pack to change
3598 // after we skip it (in the non-deduced case). That makes no sense, so
3599 // we instead notionally deduce the pack against N arguments, where N is
3600 // the length of the explicitly-specified pack if it's expanded by the
3601 // parameter pack and 0 otherwise, and we treat each deduction as a
3602 // non-deduced context.
3603 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003604 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3605 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003606 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3607 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003608 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003609 } else {
3610 // If the parameter type contains an explicitly-specified pack that we
3611 // could not expand, skip the number of parameters notionally created
3612 // by the expansion.
3613 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003614 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003615 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003616 ++I, ++ArgIdx) {
3617 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003618 // FIXME: Should we add OriginalCallArgs for these? What if the
3619 // corresponding argument is a list?
3620 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003621 }
3622 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624
Douglas Gregor7825bf32011-01-06 22:09:01 +00003625 // Build argument packs for each of the parameter packs expanded by this
3626 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003627 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003629 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003630
Richard Smith6eedfe72017-01-09 08:01:21 +00003631 return FinishTemplateArgumentDeduction(
3632 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3633 &OriginalCallArgs, PartialOverloading,
3634 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003635}
3636
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003637QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003638 QualType FunctionType,
3639 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003640 if (ArgFunctionType.isNull())
3641 return ArgFunctionType;
3642
3643 const FunctionProtoType *FunctionTypeP =
3644 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003645 const FunctionProtoType *ArgFunctionTypeP =
3646 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003647
3648 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3649 bool Rebuild = false;
3650
3651 CallingConv CC = FunctionTypeP->getCallConv();
3652 if (EPI.ExtInfo.getCC() != CC) {
3653 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3654 Rebuild = true;
3655 }
3656
3657 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3658 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3659 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3660 Rebuild = true;
3661 }
3662
3663 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3664 ArgFunctionTypeP->hasExceptionSpec())) {
3665 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3666 Rebuild = true;
3667 }
3668
3669 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003670 return ArgFunctionType;
3671
Richard Smithbaa47832016-12-01 02:11:49 +00003672 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3673 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003674}
3675
Douglas Gregor9b146582009-07-08 20:55:45 +00003676/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003677/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3678/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003679///
3680/// \param FunctionTemplate the function template for which we are performing
3681/// template argument deduction.
3682///
James Dennett18348b62012-06-22 08:52:37 +00003683/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003684/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003685///
3686/// \param ArgFunctionType the function type that will be used as the
3687/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003688/// function template's function type. This type may be NULL, if there is no
3689/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003690///
3691/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003692/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003693/// template argument deduction.
3694///
3695/// \param Info the argument will be updated to provide additional information
3696/// about template argument deduction.
3697///
Richard Smithbaa47832016-12-01 02:11:49 +00003698/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3699/// the address of a function template per [temp.deduct.funcaddr] and
3700/// [over.over]. If \c false, we are looking up a function template
3701/// specialization based on its signature, per [temp.deduct.decl].
3702///
Douglas Gregor9b146582009-07-08 20:55:45 +00003703/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003704Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3705 FunctionTemplateDecl *FunctionTemplate,
3706 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3707 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3708 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003709 if (FunctionTemplate->isInvalidDecl())
3710 return TDK_Invalid;
3711
Douglas Gregor9b146582009-07-08 20:55:45 +00003712 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3713 TemplateParameterList *TemplateParams
3714 = FunctionTemplate->getTemplateParameters();
3715 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003716
3717 // When taking the address of a function, we require convertibility of
3718 // the resulting function type. Otherwise, we allow arbitrary mismatches
3719 // of calling convention, noreturn, and noexcept.
3720 if (!IsAddressOfFunction)
3721 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3722 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003723
Douglas Gregor9b146582009-07-08 20:55:45 +00003724 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003725 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003726 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003727 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003728 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003729 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003730 if (TemplateDeductionResult Result
3731 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003732 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003733 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003734 &FunctionType, Info))
3735 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003736
3737 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003738 }
3739
Eli Friedman77dcc722012-02-08 03:07:05 +00003740 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003741 EnterExpressionEvaluationContext Unevaluated(
3742 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003743 SFINAETrap Trap(*this);
3744
John McCallc1f69982010-02-02 02:21:27 +00003745 Deduced.resize(TemplateParams->size());
3746
Richard Smith2a7d4812013-05-04 07:00:32 +00003747 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003748 // type so that we treat it as a non-deduced context in what follows. If we
3749 // are looking up by signature, the signature type should also have a deduced
3750 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003751 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003752 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003753 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003754 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003755 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003756 }
3757
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003758 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003759 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003760 if (IsAddressOfFunction)
3761 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003762 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003763 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003764 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003765 FunctionType, ArgFunctionType,
3766 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003767 return Result;
3768 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003769
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003771 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3772 NumExplicitlySpecified,
3773 Specialization, Info))
3774 return Result;
3775
Richard Smith2a7d4812013-05-04 07:00:32 +00003776 // If the function has a deduced return type, deduce it now, so we can check
3777 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003778 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003779 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003780 DeduceReturnType(Specialization, Info.getLocation(), false))
3781 return TDK_MiscellaneousDeductionFailure;
3782
Richard Smith9095e5b2016-11-01 01:31:23 +00003783 // If the function has a dependent exception specification, resolve it now,
3784 // so we can check that the exception specification matches.
3785 auto *SpecializationFPT =
3786 Specialization->getType()->castAs<FunctionProtoType>();
3787 if (getLangOpts().CPlusPlus1z &&
3788 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3789 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3790 return TDK_MiscellaneousDeductionFailure;
3791
Richard Smithbaa47832016-12-01 02:11:49 +00003792 // Adjust the exception specification of the argument again to match the
3793 // substituted and resolved type we just formed. (Calling convention and
3794 // noreturn can't be dependent, so we don't actually need this for them
3795 // right now.)
3796 QualType SpecializationType = Specialization->getType();
3797 if (!IsAddressOfFunction)
3798 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3799 /*AdjustExceptionSpec*/true);
3800
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003801 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003802 // specialization with respect to arguments of compatible pointer to function
3803 // types, template argument deduction fails.
3804 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003805 if (IsAddressOfFunction &&
3806 !isSameOrCompatibleFunctionType(
3807 Context.getCanonicalType(SpecializationType),
3808 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003809 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003810
3811 if (!IsAddressOfFunction &&
3812 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003813 return TDK_MiscellaneousDeductionFailure;
3814 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003815
3816 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003817}
3818
Simon Pilgrim728134c2016-08-12 11:43:57 +00003819/// \brief Given a function declaration (e.g. a generic lambda conversion
3820/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003821/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3822/// to replace 'auto' with and not the actual result type you want
3823/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003824static inline void
3825SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003826 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003827 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003828 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003829 assert(AutoResultType->getContainedAutoType());
3830 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003831 TypeToReplaceAutoWith);
3832 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3833}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003834
Simon Pilgrim728134c2016-08-12 11:43:57 +00003835/// \brief Given a specialized conversion operator of a generic lambda
3836/// create the corresponding specializations of the call operator and
3837/// the static-invoker. If the return type of the call operator is auto,
3838/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003839/// return type of the destination function ptr.
3840
Simon Pilgrim728134c2016-08-12 11:43:57 +00003841static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003842SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3843 CXXConversionDecl *ConversionSpecialized,
3844 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3845 QualType ReturnTypeOfDestFunctionPtr,
3846 TemplateDeductionInfo &TDInfo,
3847 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003848
Faisal Vali2b3a3012013-10-24 23:40:02 +00003849 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003850 assert(LambdaClass && LambdaClass->isGenericLambda());
3851
Faisal Vali2b3a3012013-10-24 23:40:02 +00003852 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003853 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003854 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003855 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003856
3857 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003858 CallOpGeneric->getDescribedFunctionTemplate();
3859
Craig Topperc3ec1492014-05-26 06:22:03 +00003860 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003861 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003862 // generic lambda's call operator.
3863 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003864 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3865 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003866 0, CallOpSpecialized, TDInfo))
3867 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003868
Faisal Vali2b3a3012013-10-24 23:40:02 +00003869 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003870 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3871 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003872 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003873 CallOpSpecialized->getPointOfInstantiation(),
3874 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003875
Faisal Vali2b3a3012013-10-24 23:40:02 +00003876 // Check to see if the return type of the destination ptr-to-function
3877 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003878 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003879 ReturnTypeOfDestFunctionPtr))
3880 return Sema::TDK_NonDeducedMismatch;
3881 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003882 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003883 // specialized our corresponding call operator, we are ready to
3884 // specialize the static invoker with the deduced arguments of our
3885 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003886 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003887 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3888 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3889
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003890#ifndef NDEBUG
3891 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3892#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003893 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003894 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003895 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003896 "If the call operator succeeded so should the invoker!");
3897 // Set the result type to match the corresponding call operator
3898 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003899 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3900 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003901 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003902 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003903 // to substitute into the 'auto' of the invoker and conversion
3904 // function.
3905 // For e.g.
3906 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3907 // We don't want to subst 'int*' into 'auto' to get int**.
3908
Alp Toker314cc812014-01-25 16:55:45 +00003909 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3910 ->getContainedAutoType()
3911 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003912 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3913 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003914 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003915 TypeToReplaceAutoWith, S);
3916 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003917
Faisal Vali2b3a3012013-10-24 23:40:02 +00003918 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003919 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003920 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003921 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003922 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3923 getType().getTypePtr()->castAs<FunctionProtoType>();
3924 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3925 EPI.TypeQuals = 0;
3926 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003927 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003928 return Sema::TDK_Success;
3929}
Douglas Gregor05155d82009-08-21 23:19:43 +00003930/// \brief Deduce template arguments for a templated conversion
3931/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3932/// conversion function template specialization.
3933Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003934Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003935 QualType ToType,
3936 CXXConversionDecl *&Specialization,
3937 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003938 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003939 return TDK_Invalid;
3940
Faisal Vali2b3a3012013-10-24 23:40:02 +00003941 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003942 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3943
Faisal Vali2b3a3012013-10-24 23:40:02 +00003944 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003945
3946 // Canonicalize the types for deduction.
3947 QualType P = Context.getCanonicalType(FromType);
3948 QualType A = Context.getCanonicalType(ToType);
3949
Douglas Gregord99609a2011-03-06 09:03:20 +00003950 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003951 // If P is a reference type, the type referred to by P is used for
3952 // type deduction.
3953 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3954 P = PRef->getPointeeType();
3955
Douglas Gregord99609a2011-03-06 09:03:20 +00003956 // C++0x [temp.deduct.conv]p4:
3957 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003958 // for type deduction.
3959 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003960 A = ARef->getPointeeType().getUnqualifiedType();
3961 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003962 //
Mike Stump11289f42009-09-09 15:08:12 +00003963 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003964 else {
3965 assert(!A->isReferenceType() && "Reference types were handled above");
3966
3967 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003968 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003969 // of P for type deduction; otherwise,
3970 if (P->isArrayType())
3971 P = Context.getArrayDecayedType(P);
3972 // - If P is a function type, the pointer type produced by the
3973 // function-to-pointer standard conversion (4.3) is used in
3974 // place of P for type deduction; otherwise,
3975 else if (P->isFunctionType())
3976 P = Context.getPointerType(P);
3977 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003978 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003979 else
3980 P = P.getUnqualifiedType();
3981
Douglas Gregord99609a2011-03-06 09:03:20 +00003982 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003983 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003984 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003985 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003986 A = A.getUnqualifiedType();
3987 }
3988
Eli Friedman77dcc722012-02-08 03:07:05 +00003989 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003990 EnterExpressionEvaluationContext Unevaluated(
3991 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003992 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003993
3994 // C++ [temp.deduct.conv]p1:
3995 // Template argument deduction is done by comparing the return
3996 // type of the template conversion function (call it P) with the
3997 // type that is required as the result of the conversion (call it
3998 // A) as described in 14.8.2.4.
3999 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004000 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004001 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004002 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004003
4004 // C++0x [temp.deduct.conv]p4:
4005 // In general, the deduction process attempts to find template
4006 // argument values that will make the deduced A identical to
4007 // A. However, there are two cases that allow a difference:
4008 unsigned TDF = 0;
4009 // - If the original A is a reference type, A can be more
4010 // cv-qualified than the deduced A (i.e., the type referred to
4011 // by the reference)
4012 if (ToType->isReferenceType())
4013 TDF |= TDF_ParamWithReferenceType;
4014 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004015 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004016 // conversion.
4017 //
4018 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4019 // both P and A are pointers or member pointers. In this case, we
4020 // just ignore cv-qualifiers completely).
4021 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004022 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004023 TDF |= TDF_IgnoreQualifiers;
4024 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004025 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4026 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004027 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004028
4029 // Create an Instantiation Scope for finalizing the operator.
4030 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004031 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004032 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004033 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004034 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004035 ConversionSpecialized, Info);
4036 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4037
4038 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00004039 // to a ptr-to-function, use the deduced arguments from the conversion
4040 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00004041 // e.g., int (*fp)(int) = [](auto a) { return a; };
4042 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00004043
Faisal Vali2b3a3012013-10-24 23:40:02 +00004044 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00004045 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00004046 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00004047 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00004048 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00004049 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00004050 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00004051 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
4052
Simon Pilgrim728134c2016-08-12 11:43:57 +00004053 // Create the corresponding specializations of the call operator and
4054 // the static-invoker; and if the return type is auto,
4055 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00004056 // DestFunctionPtrReturnType.
4057 // For instance:
4058 // auto L = [](auto a) { return f(a); };
4059 // int (*fp)(int) = L;
4060 // char (*fp2)(int) = L; <-- Not OK.
4061
4062 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00004063 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004064 Info, *this);
4065 }
Douglas Gregor05155d82009-08-21 23:19:43 +00004066 return Result;
4067}
4068
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004069/// \brief Deduce template arguments for a function template when there is
4070/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4071///
4072/// \param FunctionTemplate the function template for which we are performing
4073/// template argument deduction.
4074///
James Dennett18348b62012-06-22 08:52:37 +00004075/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004076/// arguments.
4077///
4078/// \param Specialization if template argument deduction was successful,
4079/// this will be set to the function template specialization produced by
4080/// template argument deduction.
4081///
4082/// \param Info the argument will be updated to provide additional information
4083/// about template argument deduction.
4084///
Richard Smithbaa47832016-12-01 02:11:49 +00004085/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4086/// the address of a function template in a context where we do not have a
4087/// target type, per [over.over]. If \c false, we are looking up a function
4088/// template specialization based on its signature, which only happens when
4089/// deducing a function parameter type from an argument that is a template-id
4090/// naming a function template specialization.
4091///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004092/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004093Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4094 FunctionTemplateDecl *FunctionTemplate,
4095 TemplateArgumentListInfo *ExplicitTemplateArgs,
4096 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4097 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004098 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004099 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004100 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004101}
4102
Richard Smith30482bc2011-02-20 03:19:35 +00004103namespace {
Richard Smith60437622017-02-09 19:17:44 +00004104 /// Substitute the 'auto' specifier or deduced template specialization type
4105 /// specifier within a type for a given replacement type.
4106 class SubstituteDeducedTypeTransform :
4107 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004108 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004109 bool UseTypeSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00004110 public:
Richard Smith60437622017-02-09 19:17:44 +00004111 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4112 bool UseTypeSugar = true)
4113 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4114 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4115
4116 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4117 assert(isa<TemplateTypeParmType>(Replacement) &&
4118 "unexpected unsugared replacement kind");
4119 QualType Result = Replacement;
4120 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4121 NewTL.setNameLoc(TL.getNameLoc());
4122 return Result;
4123 }
Nico Weberc153d242014-07-28 00:02:09 +00004124
Richard Smith30482bc2011-02-20 03:19:35 +00004125 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4126 // If we're building the type pattern to deduce against, don't wrap the
4127 // substituted type in an AutoType. Certain template deduction rules
4128 // apply only when a template type parameter appears directly (and not if
4129 // the parameter is found through desugaring). For instance:
4130 // auto &&lref = lvalue;
4131 // must transform into "rvalue reference to T" not "rvalue reference to
4132 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004133 //
4134 // FIXME: Is this still necessary?
4135 if (!UseTypeSugar)
4136 return TransformDesugared(TLB, TL);
4137
4138 QualType Result = SemaRef.Context.getAutoType(
4139 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4140 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4141 NewTL.setNameLoc(TL.getNameLoc());
4142 return Result;
4143 }
4144
4145 QualType TransformDeducedTemplateSpecializationType(
4146 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4147 if (!UseTypeSugar)
4148 return TransformDesugared(TLB, TL);
4149
4150 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4151 TL.getTypePtr()->getTemplateName(),
4152 Replacement, Replacement.isNull());
4153 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4154 NewTL.setNameLoc(TL.getNameLoc());
4155 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004156 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004157
4158 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4159 // Lambdas never need to be transformed.
4160 return E;
4161 }
Richard Smith061f1e22013-04-30 21:23:01 +00004162
Richard Smith2a7d4812013-05-04 07:00:32 +00004163 QualType Apply(TypeLoc TL) {
4164 // Create some scratch storage for the transformed type locations.
4165 // FIXME: We're just going to throw this information away. Don't build it.
4166 TypeLocBuilder TLB;
4167 TLB.reserve(TL.getFullDataSize());
4168 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004169 }
Richard Smith30482bc2011-02-20 03:19:35 +00004170 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004171}
Richard Smith30482bc2011-02-20 03:19:35 +00004172
Richard Smith2a7d4812013-05-04 07:00:32 +00004173Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004174Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4175 Optional<unsigned> DependentDeductionDepth) {
4176 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4177 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004178}
4179
Richard Smith061f1e22013-04-30 21:23:01 +00004180/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004181///
Richard Smith87d263e2016-12-25 08:05:23 +00004182/// Note that this is done even if the initializer is dependent. (This is
4183/// necessary to support partial ordering of templates using 'auto'.)
4184/// A dependent type will be produced when deducing from a dependent type.
4185///
Richard Smith30482bc2011-02-20 03:19:35 +00004186/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004187/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004188/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004189/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004190/// \param DependentDeductionDepth Set if we should permit deduction in
4191/// dependent cases. This is necessary for template partial ordering with
4192/// 'auto' template parameters. The value specified is the template
4193/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004194Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004195Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4196 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004197 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004198 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4199 if (NonPlaceholder.isInvalid())
4200 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004201 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004202 }
4203
Richard Smith87d263e2016-12-25 08:05:23 +00004204 if (!DependentDeductionDepth &&
4205 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004206 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004207 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004208 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004209 }
4210
Richard Smith87d263e2016-12-25 08:05:23 +00004211 // Find the depth of template parameter to synthesize.
4212 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4213
Richard Smith74aeef52013-04-26 16:15:35 +00004214 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4215 // Since 'decltype(auto)' can only occur at the top of the type, we
4216 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004217 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004218 if (AT->isDecltypeAuto()) {
4219 if (isa<InitListExpr>(Init)) {
4220 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4221 return DAR_FailedAlreadyDiagnosed;
4222 }
4223
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004224 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004225 if (Deduced.isNull())
4226 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004227 // FIXME: Support a non-canonical deduced type for 'auto'.
4228 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004229 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004230 if (Result.isNull())
4231 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004232 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004233 } else if (!getLangOpts().CPlusPlus) {
4234 if (isa<InitListExpr>(Init)) {
4235 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4236 return DAR_FailedAlreadyDiagnosed;
4237 }
Richard Smith74aeef52013-04-26 16:15:35 +00004238 }
4239 }
4240
Richard Smith30482bc2011-02-20 03:19:35 +00004241 SourceLocation Loc = Init->getExprLoc();
4242
4243 LocalInstantiationScope InstScope(*this);
4244
4245 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004246 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4247 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004248 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4249 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004250 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4251 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004252
Richard Smith87d263e2016-12-25 08:05:23 +00004253 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004254 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004255 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004256 assert(!FuncParam.isNull() &&
4257 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004258
4259 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004260 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004261 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004262
Richard Smith87d263e2016-12-25 08:05:23 +00004263 TemplateDeductionInfo Info(Loc, Depth);
4264
4265 // If deduction failed, don't diagnose if the initializer is dependent; it
4266 // might acquire a matching type in the instantiation.
4267 auto DeductionFailed = [&]() -> DeduceAutoResult {
4268 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004269 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004270 assert(!Result.isNull() && "substituting DependentTy can't fail");
4271 return DAR_Succeeded;
4272 }
4273 return DAR_Failed;
4274 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004275
Richard Smith707eab62017-01-05 04:08:31 +00004276 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4277
Richard Smith74801c82012-07-08 04:13:07 +00004278 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004279 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004280 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4281 // against that. Such deduction only succeeds if removing cv-qualifiers and
4282 // references results in std::initializer_list<T>.
4283 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4284 return DAR_Failed;
4285
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004286 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004287 if (DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004288 *this, TemplateParamsSt.get(), 0, TemplArg, InitList->getInit(i),
Richard Smithc92d2062017-01-05 23:02:44 +00004289 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4290 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004291 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004292 }
4293 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004294 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4295 Diag(Loc, diag::err_auto_bitfield);
4296 return DAR_FailedAlreadyDiagnosed;
4297 }
4298
Richard Smith707eab62017-01-05 04:08:31 +00004299 if (DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004300 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004301 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004302 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004303 }
Richard Smith30482bc2011-02-20 03:19:35 +00004304
Richard Smith87d263e2016-12-25 08:05:23 +00004305 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004306 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004307 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004308
Eli Friedmane4310952012-11-06 23:56:42 +00004309 QualType DeducedType = Deduced[0].getAsType();
4310
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004311 if (InitList) {
4312 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4313 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004314 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004315 }
4316
Richard Smith60437622017-02-09 19:17:44 +00004317 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004318 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004319 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004320
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004321 // Check that the deduced argument type is compatible with the original
4322 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004323 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004324 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004325 assert((bool)InitList == OriginalArg.DecomposedParam &&
4326 "decomposed non-init-list in auto deduction?");
4327 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004328 Result = QualType();
4329 return DeductionFailed();
4330 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004331 }
4332
Sebastian Redl09edce02012-01-23 22:09:39 +00004333 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004334}
4335
Simon Pilgrim728134c2016-08-12 11:43:57 +00004336QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004337 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004338 if (TypeToReplaceAuto->isDependentType())
4339 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004340 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004341 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004342}
4343
Richard Smith60437622017-02-09 19:17:44 +00004344TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4345 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004346 if (TypeToReplaceAuto->isDependentType())
4347 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004348 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004349 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004350}
4351
Richard Smith33c33c32017-02-04 01:28:01 +00004352QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4353 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004354 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4355 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004356 .TransformType(TypeWithAuto);
4357}
4358
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004359void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4360 if (isa<InitListExpr>(Init))
4361 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004362 VDecl->isInitCapture()
4363 ? diag::err_init_capture_deduction_failure_from_init_list
4364 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004365 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4366 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004367 Diag(VDecl->getLocation(),
4368 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4369 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004370 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4371 << Init->getSourceRange();
4372}
4373
Richard Smith2a7d4812013-05-04 07:00:32 +00004374bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4375 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004376 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004377
4378 if (FD->getTemplateInstantiationPattern())
4379 InstantiateFunctionDefinition(Loc, FD);
4380
Alp Toker314cc812014-01-25 16:55:45 +00004381 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004382 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4383 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4384 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4385 }
4386
4387 return StillUndeduced;
4388}
4389
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004391static void
4392AddImplicitObjectParameterType(ASTContext &Context,
4393 CXXMethodDecl *Method,
4394 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004395 // C++11 [temp.func.order]p3:
4396 // [...] The new parameter is of type "reference to cv A," where cv are
4397 // the cv-qualifiers of the function template (if any) and A is
4398 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004399 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004400 // The standard doesn't say explicitly, but we pick the appropriate kind of
4401 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004402 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4403 ArgTy = Context.getQualifiedType(ArgTy,
4404 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004405 if (Method->getRefQualifier() == RQ_RValue)
4406 ArgTy = Context.getRValueReferenceType(ArgTy);
4407 else
4408 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004409 ArgTypes.push_back(ArgTy);
4410}
4411
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004412/// \brief Determine whether the function template \p FT1 is at least as
4413/// specialized as \p FT2.
4414static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004415 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004416 FunctionTemplateDecl *FT1,
4417 FunctionTemplateDecl *FT2,
4418 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004419 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004420 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004422 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4423 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004425 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4426 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004427 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004428 Deduced.resize(TemplateParams->size());
4429
4430 // C++0x [temp.deduct.partial]p3:
4431 // The types used to determine the ordering depend on the context in which
4432 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004433 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004434 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004435 switch (TPOC) {
4436 case TPOC_Call: {
4437 // - In the context of a function call, the function parameter types are
4438 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004439 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4440 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004441
Eli Friedman3b5774a2012-09-19 23:27:04 +00004442 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004443 // [...] If only one of the function templates is a non-static
4444 // member, that function template is considered to have a new
4445 // first parameter inserted in its function parameter list. The
4446 // new parameter is of type "reference to cv A," where cv are
4447 // the cv-qualifiers of the function template (if any) and A is
4448 // the class of which the function template is a member.
4449 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004450 // Note that we interpret this to mean "if one of the function
4451 // templates is a non-static member and the other is a non-member";
4452 // otherwise, the ordering rules for static functions against non-static
4453 // functions don't make any sense.
4454 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004455 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4456 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004457 SmallVector<QualType, 4> Args1;
4458
Richard Smithe5b52202013-09-11 00:52:39 +00004459 unsigned NumComparedArguments = NumCallArguments1;
4460
4461 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004462 // Compare 'this' from Method1 against first parameter from Method2.
4463 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4464 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004465 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004466 // Compare 'this' from Method2 against first parameter from Method1.
4467 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004468 }
4469
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004470 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004471 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004472 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004473 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474
Douglas Gregorb837ea42011-01-11 17:34:58 +00004475 // C++ [temp.func.order]p5:
4476 // The presence of unused ellipsis and default arguments has no effect on
4477 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004478 if (Args1.size() > NumComparedArguments)
4479 Args1.resize(NumComparedArguments);
4480 if (Args2.size() > NumComparedArguments)
4481 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004482 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4483 Args1.data(), Args1.size(), Info, Deduced,
4484 TDF_None, /*PartialOrdering=*/true))
4485 return false;
4486
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004487 break;
4488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004490 case TPOC_Conversion:
4491 // - In the context of a call to a conversion operator, the return types
4492 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004493 if (DeduceTemplateArgumentsByTypeMatch(
4494 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4495 Info, Deduced, TDF_None,
4496 /*PartialOrdering=*/true))
4497 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004498 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004500 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004501 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004502 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004503 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4504 FD2->getType(), FD1->getType(),
4505 Info, Deduced, TDF_None,
4506 /*PartialOrdering=*/true))
4507 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004508 break;
4509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004511 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004512 // In most cases, all template parameters must have values in order for
4513 // deduction to succeed, but for partial ordering purposes a template
4514 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004515 // types being used for partial ordering. [ Note: a template parameter used
4516 // in a non-deduced context is considered used. -end note]
4517 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4518 for (; ArgIdx != NumArgs; ++ArgIdx)
4519 if (Deduced[ArgIdx].isNull())
4520 break;
4521
Richard Smithf0393bf2017-02-16 04:22:56 +00004522 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4523 // to substitute the deduced arguments back into the template and check that
4524 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004525
Richard Smithf0393bf2017-02-16 04:22:56 +00004526 if (ArgIdx == NumArgs) {
4527 // All template arguments were deduced. FT1 is at least as specialized
4528 // as FT2.
4529 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004530 }
4531
Richard Smithf0393bf2017-02-16 04:22:56 +00004532 // Figure out which template parameters were used.
4533 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4534 switch (TPOC) {
4535 case TPOC_Call:
4536 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4537 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4538 TemplateParams->getDepth(),
4539 UsedParameters);
4540 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Richard Smithf0393bf2017-02-16 04:22:56 +00004542 case TPOC_Conversion:
4543 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4544 TemplateParams->getDepth(), UsedParameters);
4545 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
Richard Smithf0393bf2017-02-16 04:22:56 +00004547 case TPOC_Other:
4548 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4549 TemplateParams->getDepth(),
4550 UsedParameters);
4551 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004552 }
4553
Richard Smithf0393bf2017-02-16 04:22:56 +00004554 for (; ArgIdx != NumArgs; ++ArgIdx)
4555 // If this argument had no value deduced but was used in one of the types
4556 // used for partial ordering, then deduction fails.
4557 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4558 return false;
4559
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004560 return true;
4561}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562
Douglas Gregorcef1a032011-01-16 16:03:23 +00004563/// \brief Determine whether this a function template whose parameter-type-list
4564/// ends with a function parameter pack.
4565static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4566 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4567 unsigned NumParams = Function->getNumParams();
4568 if (NumParams == 0)
4569 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
Douglas Gregorcef1a032011-01-16 16:03:23 +00004571 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4572 if (!Last->isParameterPack())
4573 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Douglas Gregorcef1a032011-01-16 16:03:23 +00004575 // Make sure that no previous parameter is a parameter pack.
4576 while (--NumParams > 0) {
4577 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4578 return false;
4579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580
Douglas Gregorcef1a032011-01-16 16:03:23 +00004581 return true;
4582}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583
Douglas Gregorbe999392009-09-15 16:23:51 +00004584/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004585/// to the rules of function template partial ordering (C++ [temp.func.order]).
4586///
4587/// \param FT1 the first function template
4588///
4589/// \param FT2 the second function template
4590///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004591/// \param TPOC the context in which we are performing partial ordering of
4592/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004593///
Richard Smithe5b52202013-09-11 00:52:39 +00004594/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4595/// only when \c TPOC is \c TPOC_Call.
4596///
4597/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4598/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004599///
Douglas Gregorbe999392009-09-15 16:23:51 +00004600/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004601/// template is more specialized, returns NULL.
4602FunctionTemplateDecl *
4603Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4604 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004605 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004606 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004607 unsigned NumCallArguments1,
4608 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004610 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004612 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004614 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004615 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004617 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004618 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004619
Douglas Gregorcef1a032011-01-16 16:03:23 +00004620 // FIXME: This mimics what GCC implements, but doesn't match up with the
4621 // proposed resolution for core issue 692. This area needs to be sorted out,
4622 // but for now we attempt to maintain compatibility.
4623 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4624 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4625 if (Variadic1 != Variadic2)
4626 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627
Craig Topperc3ec1492014-05-26 06:22:03 +00004628 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004629}
Douglas Gregor9b146582009-07-08 20:55:45 +00004630
Douglas Gregor450f00842009-09-25 18:43:00 +00004631/// \brief Determine if the two templates are equivalent.
4632static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4633 if (T1 == T2)
4634 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor450f00842009-09-25 18:43:00 +00004636 if (!T1 || !T2)
4637 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638
Douglas Gregor450f00842009-09-25 18:43:00 +00004639 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4640}
4641
4642/// \brief Retrieve the most specialized of the given function template
4643/// specializations.
4644///
John McCall58cc69d2010-01-27 01:50:18 +00004645/// \param SpecBegin the start iterator of the function template
4646/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004647///
John McCall58cc69d2010-01-27 01:50:18 +00004648/// \param SpecEnd the end iterator of the function template
4649/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004650///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004651/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004652/// diagnostic should occur.
4653///
4654/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4655/// no matching candidates.
4656///
4657/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4658/// occurs.
4659///
4660/// \param CandidateDiag partial diagnostic used for each function template
4661/// specialization that is a candidate in the ambiguous ordering. One parameter
4662/// in this diagnostic should be unbound, which will correspond to the string
4663/// describing the template arguments for the function template specialization.
4664///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004666/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004667UnresolvedSetIterator Sema::getMostSpecialized(
4668 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4669 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004670 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4671 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4672 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004673 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004674 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004675 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004676 FailedCandidates.NoteCandidates(*this, Loc);
4677 }
John McCall58cc69d2010-01-27 01:50:18 +00004678 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
4681 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004682 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Douglas Gregor450f00842009-09-25 18:43:00 +00004684 // Find the function template that is better than all of the templates it
4685 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004686 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004688 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004689 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004690 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4691 FunctionTemplateDecl *Challenger
4692 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004693 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004694 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004695 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004696 Challenger)) {
4697 Best = I;
4698 BestTemplate = Challenger;
4699 }
4700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Douglas Gregor450f00842009-09-25 18:43:00 +00004702 // Make sure that the "best" function template is more specialized than all
4703 // of the others.
4704 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004705 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4706 FunctionTemplateDecl *Challenger
4707 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004708 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004709 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004710 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004711 BestTemplate)) {
4712 Ambiguous = true;
4713 break;
4714 }
4715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716
Douglas Gregor450f00842009-09-25 18:43:00 +00004717 if (!Ambiguous) {
4718 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004719 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721
Douglas Gregor450f00842009-09-25 18:43:00 +00004722 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004723 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004724 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725
Richard Smithb875c432013-05-04 01:51:08 +00004726 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004727 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4728 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004729 const auto *FD = cast<FunctionDecl>(*I);
4730 PD << FD << getTemplateArgumentBindingsText(
4731 FD->getPrimaryTemplate()->getTemplateParameters(),
4732 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004733 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004734 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004735 Diag((*I)->getLocation(), PD);
4736 }
Richard Smithb875c432013-05-04 01:51:08 +00004737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
John McCall58cc69d2010-01-27 01:50:18 +00004739 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004740}
4741
Richard Smith0da6dc42016-12-24 16:40:51 +00004742/// Determine whether one partial specialization, P1, is at least as
4743/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004744///
Richard Smith26b86ea2016-12-31 21:41:23 +00004745/// \tparam TemplateLikeDecl The kind of P2, which must be a
4746/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004747/// \param T1 The injected-class-name of P1 (faked for a variable template).
4748/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004749template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004750static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004751 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004752 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004753 // C++ [temp.class.order]p1:
4754 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755 // specialized as the second if, given the following rewrite to two
4756 // function templates, the first function template is at least as
4757 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004758 // templates (14.6.6.2):
4759 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 // first partial specialization and has a single function parameter
4761 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004762 // arguments of the first partial specialization, and
4763 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764 // second partial specialization and has a single function parameter
4765 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004766 // arguments of the second partial specialization.
4767 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004768 // Rather than synthesize function templates, we merely perform the
4769 // equivalent partial ordering by performing deduction directly on
4770 // the template arguments of the class template partial
4771 // specializations. This computation is slightly simpler than the
4772 // general problem of function template partial ordering, because
4773 // class template partial specializations are more constrained. We
4774 // know that every template parameter is deducible from the class
4775 // template partial specialization's template arguments, for
4776 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004777 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004778
Richard Smith0da6dc42016-12-24 16:40:51 +00004779 // Determine whether P1 is at least as specialized as P2.
4780 Deduced.resize(P2->getTemplateParameters()->size());
4781 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4782 T2, T1, Info, Deduced, TDF_None,
4783 /*PartialOrdering=*/true))
4784 return false;
4785
4786 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4787 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004788 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4789 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004790 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4791 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004792 S, P2, /*PartialOrdering=*/true,
4793 TemplateArgumentList(TemplateArgumentList::OnStack,
4794 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004795 Deduced, Info))
4796 return false;
4797
4798 return true;
4799}
4800
4801/// \brief Returns the more specialized class template partial specialization
4802/// according to the rules of partial ordering of class template partial
4803/// specializations (C++ [temp.class.order]).
4804///
4805/// \param PS1 the first class template partial specialization
4806///
4807/// \param PS2 the second class template partial specialization
4808///
4809/// \returns the more specialized class template partial specialization. If
4810/// neither partial specialization is more specialized, returns NULL.
4811ClassTemplatePartialSpecializationDecl *
4812Sema::getMoreSpecializedPartialSpecialization(
4813 ClassTemplatePartialSpecializationDecl *PS1,
4814 ClassTemplatePartialSpecializationDecl *PS2,
4815 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004816 QualType PT1 = PS1->getInjectedSpecializationType();
4817 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Richard Smith0e617ec2016-12-27 07:56:27 +00004819 TemplateDeductionInfo Info(Loc);
4820 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4821 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004822
4823 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004824 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004825
4826 return Better1 ? PS1 : PS2;
4827}
4828
Richard Smith0e617ec2016-12-27 07:56:27 +00004829bool Sema::isMoreSpecializedThanPrimary(
4830 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4831 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4832 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4833 QualType PartialT = Spec->getInjectedSpecializationType();
4834 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4835 return false;
4836 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4837 Info.clearSFINAEDiagnostic();
4838 return false;
4839 }
4840 return true;
4841}
4842
Larisse Voufo39a1e502013-08-06 01:03:05 +00004843VarTemplatePartialSpecializationDecl *
4844Sema::getMoreSpecializedPartialSpecialization(
4845 VarTemplatePartialSpecializationDecl *PS1,
4846 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004847 // Pretend the variable template specializations are class template
4848 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004849 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004850 "the partial specializations being compared should specialize"
4851 " the same template.");
4852 TemplateName Name(PS1->getSpecializedTemplate());
4853 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4854 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004855 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004856 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004857 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004858
Richard Smith0e617ec2016-12-27 07:56:27 +00004859 TemplateDeductionInfo Info(Loc);
4860 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4861 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
Douglas Gregorbe999392009-09-15 16:23:51 +00004863 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004864 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Richard Smith0da6dc42016-12-24 16:40:51 +00004866 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004867}
4868
Richard Smith0e617ec2016-12-27 07:56:27 +00004869bool Sema::isMoreSpecializedThanPrimary(
4870 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4871 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4872 // FIXME: Cache the injected template arguments rather than recomputing
4873 // them for each partial specialization.
4874 SmallVector<TemplateArgument, 8> PrimaryArgs;
4875 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4876 PrimaryArgs);
4877
4878 TemplateName CanonTemplate =
4879 Context.getCanonicalTemplateName(TemplateName(Primary));
4880 QualType PrimaryT = Context.getTemplateSpecializationType(
4881 CanonTemplate, PrimaryArgs);
4882 QualType PartialT = Context.getTemplateSpecializationType(
4883 CanonTemplate, Spec->getTemplateArgs().asArray());
4884 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4885 return false;
4886 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4887 Info.clearSFINAEDiagnostic();
4888 return false;
4889 }
4890 return true;
4891}
4892
Richard Smith26b86ea2016-12-31 21:41:23 +00004893bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4894 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4895 // C++1z [temp.arg.template]p4: (DR 150)
4896 // A template template-parameter P is at least as specialized as a
4897 // template template-argument A if, given the following rewrite to two
4898 // function templates...
4899
4900 // Rather than synthesize function templates, we merely perform the
4901 // equivalent partial ordering by performing deduction directly on
4902 // the template parameter lists of the template template parameters.
4903 //
4904 // Given an invented class template X with the template parameter list of
4905 // A (including default arguments):
4906 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4907 TemplateParameterList *A = AArg->getTemplateParameters();
4908
4909 // - Each function template has a single function parameter whose type is
4910 // a specialization of X with template arguments corresponding to the
4911 // template parameters from the respective function template
4912 SmallVector<TemplateArgument, 8> AArgs;
4913 Context.getInjectedTemplateArgs(A, AArgs);
4914
4915 // Check P's arguments against A's parameter list. This will fill in default
4916 // template arguments as needed. AArgs are already correct by construction.
4917 // We can't just use CheckTemplateIdType because that will expand alias
4918 // templates.
4919 SmallVector<TemplateArgument, 4> PArgs;
4920 {
4921 SFINAETrap Trap(*this);
4922
4923 Context.getInjectedTemplateArgs(P, PArgs);
4924 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4925 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4926 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4927 // expansions, to form an "as written" argument list.
4928 TemplateArgument Arg = PArgs[I];
4929 if (Arg.getKind() == TemplateArgument::Pack) {
4930 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4931 Arg = *Arg.pack_begin();
4932 }
4933 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4934 Arg, QualType(), P->getParam(I)->getLocation()));
4935 }
4936 PArgs.clear();
4937
4938 // C++1z [temp.arg.template]p3:
4939 // If the rewrite produces an invalid type, then P is not at least as
4940 // specialized as A.
4941 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4942 Trap.hasErrorOccurred())
4943 return false;
4944 }
4945
4946 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4947 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4948
Richard Smith26b86ea2016-12-31 21:41:23 +00004949 // ... the function template corresponding to P is at least as specialized
4950 // as the function template corresponding to A according to the partial
4951 // ordering rules for function templates.
4952 TemplateDeductionInfo Info(Loc, A->getDepth());
4953 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4954}
4955
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004956/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004957/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004958static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004959MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004960 const Expr *E,
4961 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004962 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004963 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004964 // We can deduce from a pack expansion.
4965 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4966 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004967
Richard Smith34349002012-07-09 03:07:20 +00004968 // Skip through any implicit casts we added while type-checking, and any
4969 // substitutions performed by template alias expansion.
4970 while (1) {
4971 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4972 E = ICE->getSubExpr();
4973 else if (const SubstNonTypeTemplateParmExpr *Subst =
4974 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4975 E = Subst->getReplacement();
4976 else
4977 break;
4978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
4980 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004981 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004982 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004983 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004984 return;
4985
Mike Stump11289f42009-09-09 15:08:12 +00004986 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004987 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4988 if (!NTTP)
4989 return;
4990
Douglas Gregor21610382009-10-29 00:04:11 +00004991 if (NTTP->getDepth() == Depth)
4992 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004993
4994 // In C++1z mode, additional arguments may be deduced from the type of a
4995 // non-type argument.
4996 if (Ctx.getLangOpts().CPlusPlus1z)
4997 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004998}
4999
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005000/// \brief Mark the template parameters that are used by the given
5001/// nested name specifier.
5002static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005003MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005004 NestedNameSpecifier *NNS,
5005 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005006 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005007 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005008 if (!NNS)
5009 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005010
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005011 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005012 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005013 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005014 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005015}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005016
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005017/// \brief Mark the template parameters that are used by the given
5018/// template name.
5019static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005020MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005021 TemplateName Name,
5022 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005023 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005024 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005025 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5026 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005027 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5028 if (TTP->getDepth() == Depth)
5029 Used[TTP->getIndex()] = true;
5030 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005031 return;
5032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005034 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005035 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005036 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005037 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005038 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005039 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005040}
5041
5042/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005043/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005044static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005045MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005046 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005047 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005048 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005049 if (T.isNull())
5050 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051
Douglas Gregor91772d12009-06-13 00:26:55 +00005052 // Non-dependent types have nothing deducible
5053 if (!T->isDependentType())
5054 return;
5055
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005056 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005057 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005058 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005059 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005060 cast<PointerType>(T)->getPointeeType(),
5061 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005062 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005063 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005064 break;
5065
5066 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005067 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005068 cast<BlockPointerType>(T)->getPointeeType(),
5069 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005070 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005071 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005072 break;
5073
5074 case Type::LValueReference:
5075 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005076 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005077 cast<ReferenceType>(T)->getPointeeType(),
5078 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005079 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005080 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005081 break;
5082
5083 case Type::MemberPointer: {
5084 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005085 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005086 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005087 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005088 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005089 break;
5090 }
5091
5092 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005093 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005094 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005095 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005096 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005097 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005098
5099 case Type::ConstantArray:
5100 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005101 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005102 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005103 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005104 break;
5105
5106 case Type::Vector:
5107 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005108 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005109 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005110 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005111 break;
5112
Douglas Gregor758a8692009-06-17 21:51:59 +00005113 case Type::DependentSizedExtVector: {
5114 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005115 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005116 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005117 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005118 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005119 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005120 break;
5121 }
5122
Douglas Gregor91772d12009-06-13 00:26:55 +00005123 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005124 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005125 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5126 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005127 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5128 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005129 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005130 break;
5131 }
5132
Douglas Gregor21610382009-10-29 00:04:11 +00005133 case Type::TemplateTypeParm: {
5134 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5135 if (TTP->getDepth() == Depth)
5136 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005137 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005138 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005139
Douglas Gregorfb322d82011-01-14 05:11:40 +00005140 case Type::SubstTemplateTypeParmPack: {
5141 const SubstTemplateTypeParmPackType *Subst
5142 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005143 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005144 QualType(Subst->getReplacedParameter(), 0),
5145 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005146 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005147 OnlyDeduced, Depth, Used);
5148 break;
5149 }
5150
John McCall2408e322010-04-27 00:57:59 +00005151 case Type::InjectedClassName:
5152 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5153 // fall through
5154
Douglas Gregor91772d12009-06-13 00:26:55 +00005155 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005156 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005157 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005158 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005159 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160
Douglas Gregord0ad2942010-12-23 01:24:45 +00005161 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005162 // If the template argument list of P contains a pack expansion that is
5163 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005164 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005165 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005166 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005167 break;
5168
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005169 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005170 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005171 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005172 break;
5173 }
5174
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005175 case Type::Complex:
5176 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005177 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005178 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005179 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005180 break;
5181
Eli Friedman0dfb8892011-10-06 23:00:33 +00005182 case Type::Atomic:
5183 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005184 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005185 cast<AtomicType>(T)->getValueType(),
5186 OnlyDeduced, Depth, Used);
5187 break;
5188
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005189 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005190 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005191 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005192 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005193 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005194 break;
5195
John McCallc392f372010-06-11 00:33:02 +00005196 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005197 // C++14 [temp.deduct.type]p5:
5198 // The non-deduced contexts are:
5199 // -- The nested-name-specifier of a type that was specified using a
5200 // qualified-id
5201 //
5202 // C++14 [temp.deduct.type]p6:
5203 // When a type name is specified in a way that includes a non-deduced
5204 // context, all of the types that comprise that type name are also
5205 // non-deduced.
5206 if (OnlyDeduced)
5207 break;
5208
John McCallc392f372010-06-11 00:33:02 +00005209 const DependentTemplateSpecializationType *Spec
5210 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Richard Smith50d5b972015-12-30 20:56:05 +00005212 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5213 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005214
John McCallc392f372010-06-11 00:33:02 +00005215 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005216 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005217 Used);
5218 break;
5219 }
5220
John McCallbd8d9bd2010-03-01 23:49:17 +00005221 case Type::TypeOf:
5222 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005223 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005224 cast<TypeOfType>(T)->getUnderlyingType(),
5225 OnlyDeduced, Depth, Used);
5226 break;
5227
5228 case Type::TypeOfExpr:
5229 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005230 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005231 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5232 OnlyDeduced, Depth, Used);
5233 break;
5234
5235 case Type::Decltype:
5236 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005237 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005238 cast<DecltypeType>(T)->getUnderlyingExpr(),
5239 OnlyDeduced, Depth, Used);
5240 break;
5241
Alexis Hunte852b102011-05-24 22:41:36 +00005242 case Type::UnaryTransform:
5243 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005244 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005245 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005246 OnlyDeduced, Depth, Used);
5247 break;
5248
Douglas Gregord2fa7662010-12-20 02:24:11 +00005249 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005250 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005251 cast<PackExpansionType>(T)->getPattern(),
5252 OnlyDeduced, Depth, Used);
5253 break;
5254
Richard Smith30482bc2011-02-20 03:19:35 +00005255 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005256 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005257 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005258 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005259 OnlyDeduced, Depth, Used);
5260
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005261 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005262 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005263 case Type::VariableArray:
5264 case Type::FunctionNoProto:
5265 case Type::Record:
5266 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005267 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005268 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005269 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005270 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005271 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005272#define TYPE(Class, Base)
5273#define ABSTRACT_TYPE(Class, Base)
5274#define DEPENDENT_TYPE(Class, Base)
5275#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5276#include "clang/AST/TypeNodes.def"
5277 break;
5278 }
5279}
5280
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005281/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005282/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005283static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005284MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005285 const TemplateArgument &TemplateArg,
5286 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005287 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005288 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005289 switch (TemplateArg.getKind()) {
5290 case TemplateArgument::Null:
5291 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005292 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005293 break;
Mike Stump11289f42009-09-09 15:08:12 +00005294
Eli Friedmanb826a002012-09-26 02:36:12 +00005295 case TemplateArgument::NullPtr:
5296 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5297 Depth, Used);
5298 break;
5299
Douglas Gregor91772d12009-06-13 00:26:55 +00005300 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005301 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005302 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005303 break;
5304
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005305 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005306 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005307 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005308 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005309 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005310 break;
5311
5312 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005313 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005314 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005315 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005316
Anders Carlssonbc343912009-06-15 17:04:53 +00005317 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005318 for (const auto &P : TemplateArg.pack_elements())
5319 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005320 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005321 }
5322}
5323
James Dennett41725122012-06-22 10:16:05 +00005324/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005325/// template argument list.
5326///
5327/// \param TemplateArgs the template argument list from which template
5328/// parameters will be deduced.
5329///
James Dennett41725122012-06-22 10:16:05 +00005330/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005331/// to indicate when the corresponding template parameter will be
5332/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005333void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005334Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005335 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005336 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005337 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338 // If the template argument list of P contains a pack expansion that is not
5339 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005340 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005341 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005342 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005343 return;
5344
Douglas Gregor91772d12009-06-13 00:26:55 +00005345 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005346 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005347 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005348}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005349
5350/// \brief Marks all of the template parameters that will be deduced by a
5351/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005352void Sema::MarkDeducedTemplateParameters(
5353 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5354 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005355 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005356 = FunctionTemplate->getTemplateParameters();
5357 Deduced.clear();
5358 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005359
Douglas Gregorce23bae2009-09-18 23:21:38 +00005360 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5361 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005362 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005363 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005364}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005365
Richard Smithf0393bf2017-02-16 04:22:56 +00005366bool hasDeducibleTemplateParameters(Sema &S,
5367 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005368 QualType T) {
5369 if (!T->isDependentType())
5370 return false;
5371
Richard Smithf0393bf2017-02-16 04:22:56 +00005372 TemplateParameterList *TemplateParams
5373 = FunctionTemplate->getTemplateParameters();
5374 llvm::SmallBitVector Deduced(TemplateParams->size());
5375 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5376 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005377
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005378 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005379}