blob: 760207fece572762373f8bf327beb61754ea07e7 [file] [log] [blame]
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002//
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.
Douglas Gregor55ca8f62009-06-04 00:03:07 +00007//
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00008//===----------------------------------------------------------------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +00009//
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000010// This file implements C++ template argument deduction.
11//
12//===----------------------------------------------------------------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +000013
John McCall19c1bfd2010-08-25 05:32:35 +000014#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "TreeTransform.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000016#include "TypeLocBuilder.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000017#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000018#include "clang/AST/ASTLambda.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000023#include "clang/AST/DeclTemplate.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000024#include "clang/AST/DeclarationName.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000025#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000027#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/AST/TemplateBase.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/AddressSpaces.h"
34#include "clang/Basic/ExceptionSpecificationType.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/LangOptions.h"
37#include "clang/Basic/PartialDiagnostic.h"
38#include "clang/Basic/SourceLocation.h"
39#include "clang/Basic/Specifiers.h"
40#include "clang/Sema/Ownership.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Sema/Sema.h"
42#include "clang/Sema/Template.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000043#include "llvm/ADT/APInt.h"
44#include "llvm/ADT/APSInt.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/DenseMap.h"
47#include "llvm/ADT/FoldingSet.h"
48#include "llvm/ADT/Optional.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000049#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000050#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000055#include <algorithm>
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000056#include <cassert>
57#include <tuple>
58#include <utility>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000059
60namespace clang {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000061
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000062 /// Various flags that control template argument deduction.
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000063 ///
64 /// These flags can be bitwise-OR'd together.
65 enum TemplateDeductionFlags {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000066 /// No template argument deduction flags, which indicates the
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000067 /// strictest results for template argument deduction (as used for, e.g.,
68 /// matching class template partial specializations).
69 TDF_None = 0,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Within template argument deduction from a function call, we are
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000072 /// matching with a parameter type for which the original parameter was
73 /// a reference.
74 TDF_ParamWithReferenceType = 0x1,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000076 /// Within template argument deduction from a function call, we
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000077 /// are matching in a case where we ignore cv-qualifiers.
78 TDF_IgnoreQualifiers = 0x02,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Within template argument deduction from a function call,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000081 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000082 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000083 TDF_DerivedClass = 0x04,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000084
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Allow non-dependent types to differ, e.g., when performing
Douglas Gregor406f6342009-09-14 20:00:47 +000086 /// template argument deduction from a function call where conversions
87 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000088 TDF_SkipNonDependent = 0x08,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000090 /// Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000091 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000092 TDF_TopLevelParameterTypeList = 0x10,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000094 /// Within template argument deduction from overload resolution per
Douglas Gregor19a41f12013-04-17 08:45:07 +000095 /// C++ [over.over] allow matching function types that are compatible in
Richard Smithcd198152017-06-07 21:46:22 +000096 /// terms of noreturn and default calling convention adjustments, or
97 /// similarly matching a declared template specialization against a
98 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
99 /// deduction where the parameter is a function type that can be converted
100 /// to the argument type.
101 TDF_AllowCompatibleFunctionType = 0x20,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000102 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000103}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000104
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000105using namespace clang;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000106using namespace sema;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000107
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000108/// Compare two APSInts, extending and switching the sign as
Douglas Gregor0a29a052010-03-26 05:50:28 +0000109/// necessary to compare their values regardless of underlying type.
110static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
111 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000112 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000113 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000114 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000115
116 // If there is a signedness mismatch, correct it.
117 if (X.isSigned() != Y.isSigned()) {
118 // If the signed value is negative, then the values cannot be the same.
119 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
120 return false;
121
122 Y.setIsSigned(true);
123 X.setIsSigned(true);
124 }
125
126 return X == Y;
127}
128
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000129static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000130DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000131 TemplateParameterList *TemplateParams,
132 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000133 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000134 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000135 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000136
Douglas Gregor7baabef2010-12-22 18:17:10 +0000137static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000138DeduceTemplateArgumentsByTypeMatch(Sema &S,
139 TemplateParameterList *TemplateParams,
140 QualType Param,
141 QualType Arg,
142 TemplateDeductionInfo &Info,
143 SmallVectorImpl<DeducedTemplateArgument> &
144 Deduced,
145 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000146 bool PartialOrdering = false,
147 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000148
149static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000150DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000151 ArrayRef<TemplateArgument> Params,
152 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000153 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000154 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
155 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000156
Richard Smith130cc442017-02-21 23:49:18 +0000157static void MarkUsedTemplateParameters(ASTContext &Ctx,
158 const TemplateArgument &TemplateArg,
159 bool OnlyDeduced, unsigned Depth,
160 llvm::SmallBitVector &Used);
161
162static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
163 bool OnlyDeduced, unsigned Level,
164 llvm::SmallBitVector &Deduced);
165
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000166/// If the given expression is of a form that permits the deduction
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000167/// of a non-type template parameter, return the declaration of that
168/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000169static NonTypeTemplateParmDecl *
170getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000171 // If we are within an alias template, the expression may have undergone
172 // any number of parameter substitutions already.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000173 while (true) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000174 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
175 E = IC->getSubExpr();
176 else if (SubstNonTypeTemplateParmExpr *Subst =
177 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
178 E = Subst->getReplacement();
179 else
180 break;
181 }
Mike Stump11289f42009-09-09 15:08:12 +0000182
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000183 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000184 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
185 if (NTTP->getDepth() == Info.getDeducedDepth())
186 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000187
Craig Topperc3ec1492014-05-26 06:22:03 +0000188 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000189}
190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000191/// Determine whether two declaration pointers refer to the same
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000192/// declaration.
193static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000194 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
195 X = NX->getUnderlyingDecl();
196 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
197 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000198
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000199 return X->getCanonicalDecl() == Y->getCanonicalDecl();
200}
201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000202/// Verify that the given, deduced template arguments are compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000203///
204/// \returns The deduced template argument, or a NULL template argument if
205/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000206static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000207checkDeducedTemplateArguments(ASTContext &Context,
208 const DeducedTemplateArgument &X,
209 const DeducedTemplateArgument &Y) {
210 // We have no deduction for one or both of the arguments; they're compatible.
211 if (X.isNull())
212 return Y;
213 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000214 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000215
Richard Smith593d6a12016-12-23 01:30:39 +0000216 // If we have two non-type template argument values deduced for the same
217 // parameter, they must both match the type of the parameter, and thus must
218 // match each other's type. As we're only keeping one of them, we must check
219 // for that now. The exception is that if either was deduced from an array
220 // bound, the type is permitted to differ.
221 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
222 QualType XType = X.getNonTypeTemplateArgumentType();
223 if (!XType.isNull()) {
224 QualType YType = Y.getNonTypeTemplateArgumentType();
225 if (YType.isNull() || !Context.hasSameType(XType, YType))
226 return DeducedTemplateArgument();
227 }
228 }
229
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000230 switch (X.getKind()) {
231 case TemplateArgument::Null:
232 llvm_unreachable("Non-deduced template arguments handled above");
233
234 case TemplateArgument::Type:
235 // If two template type arguments have the same type, they're compatible.
236 if (Y.getKind() == TemplateArgument::Type &&
237 Context.hasSameType(X.getAsType(), Y.getAsType()))
238 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000239
Richard Smith5f274382016-09-28 23:55:27 +0000240 // If one of the two arguments was deduced from an array bound, the other
241 // supersedes it.
242 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
243 return X.wasDeducedFromArrayBound() ? Y : X;
244
245 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000246 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000247
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000248 case TemplateArgument::Integral:
249 // If we deduced a constant in one case and either a dependent expression or
250 // declaration in another case, keep the integral constant.
251 // If both are integral constants with the same value, keep that value.
252 if (Y.getKind() == TemplateArgument::Expression ||
253 Y.getKind() == TemplateArgument::Declaration ||
254 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000255 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000256 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000257
258 // All other combinations are incompatible.
259 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000260
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000261 case TemplateArgument::Template:
262 if (Y.getKind() == TemplateArgument::Template &&
263 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
264 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000265
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000266 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000267 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000268
269 case TemplateArgument::TemplateExpansion:
270 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000271 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000272 Y.getAsTemplateOrTemplatePattern()))
273 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000275 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000277
Richard Smith593d6a12016-12-23 01:30:39 +0000278 case TemplateArgument::Expression: {
279 if (Y.getKind() != TemplateArgument::Expression)
280 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281
Richard Smith593d6a12016-12-23 01:30:39 +0000282 // Compare the expressions for equality
283 llvm::FoldingSetNodeID ID1, ID2;
284 X.getAsExpr()->Profile(ID1, Context, true);
285 Y.getAsExpr()->Profile(ID2, Context, true);
286 if (ID1 == ID2)
287 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Richard Smith593d6a12016-12-23 01:30:39 +0000289 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000290 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000293 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000294 assert(!X.wasDeducedFromArrayBound());
295
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000296 // If we deduced a declaration and a dependent expression, keep the
297 // declaration.
298 if (Y.getKind() == TemplateArgument::Expression)
299 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000300
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000301 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000302 // integral constant and whichever type did not come from an array
303 // bound.
304 if (Y.getKind() == TemplateArgument::Integral) {
305 if (Y.wasDeducedFromArrayBound())
306 return TemplateArgument(Context, Y.getAsIntegral(),
307 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000311 // If we deduced two declarations, make sure that they refer to the
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000312 // same declaration.
313 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000314 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000315 return X;
316
317 // All other combinations are incompatible.
318 return DeducedTemplateArgument();
319
320 case TemplateArgument::NullPtr:
321 // If we deduced a null pointer and a dependent expression, keep the
322 // null pointer.
323 if (Y.getKind() == TemplateArgument::Expression)
324 return X;
325
326 // If we deduced a null pointer and an integral constant, keep the
327 // integral constant.
328 if (Y.getKind() == TemplateArgument::Integral)
329 return Y;
330
Richard Smith593d6a12016-12-23 01:30:39 +0000331 // If we deduced two null pointers, they are the same.
332 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000335 // All other combinations are incompatible.
336 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000337
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000338 case TemplateArgument::Pack: {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000339 if (Y.getKind() != TemplateArgument::Pack ||
340 X.pack_size() != Y.pack_size())
341 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000342
Richard Smith539e8e32017-01-04 01:48:55 +0000343 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000345 XAEnd = X.pack_end(),
346 YA = Y.pack_begin();
347 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000348 TemplateArgument Merged = checkDeducedTemplateArguments(
349 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
350 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
351 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000352 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000353 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
Richard Smith539e8e32017-01-04 01:48:55 +0000356 return DeducedTemplateArgument(
357 TemplateArgument::CreatePackCopy(Context, NewPack),
358 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000359 }
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
David Blaikiee4d798f2012-01-20 21:50:17 +0000362 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000363}
364
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000365/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000366/// as the given deduced template argument. All non-type template parameter
367/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000368static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000369 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000370 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
371 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000372 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000373 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
374 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000375
Richard Smith5d102892016-12-27 03:59:58 +0000376 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
377 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000378 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000379 Info.Param = NTTP;
380 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000381 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000385 Deduced[NTTP->getIndex()] = Result;
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000386 if (!S.getLangOpts().CPlusPlus17)
Richard Smithd92eddf2016-12-27 06:14:37 +0000387 return Sema::TDK_Success;
388
Richard Smith130cc442017-02-21 23:49:18 +0000389 if (NTTP->isExpandedParameterPack())
390 // FIXME: We may still need to deduce parts of the type here! But we
391 // don't have any way to find which slice of the type to use, and the
392 // type stored on the NTTP itself is nonsense. Perhaps the type of an
393 // expanded NTTP should be a pack expansion type?
394 return Sema::TDK_Success;
395
Richard Smith7bfcc052017-12-01 21:24:36 +0000396 // Get the type of the parameter for deduction. If it's a (dependent) array
397 // or function type, we will not have decayed it yet, so do that now.
398 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
Richard Smith130cc442017-02-21 23:49:18 +0000399 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
400 ParamType = Expansion->getPattern();
401
Richard Smithd92eddf2016-12-27 06:14:37 +0000402 // FIXME: It's not clear how deduction of a parameter of reference
403 // type from an argument (of non-reference type) should be performed.
404 // For now, we just remove reference types from both sides and let
405 // the final check for matching types sort out the mess.
406 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000407 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000408 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
409 /*PartialOrdering=*/false,
410 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000411}
412
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000413/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000414/// from the given integral constant.
415static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
416 Sema &S, TemplateParameterList *TemplateParams,
417 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
418 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
419 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
420 return DeduceNonTypeTemplateArgument(
421 S, TemplateParams, NTTP,
422 DeducedTemplateArgument(S.Context, Value, ValueType,
423 DeducedFromArrayBound),
424 ValueType, Info, Deduced);
425}
426
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000427/// Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000428/// from the given null pointer template argument type.
429static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000430 Sema &S, TemplateParameterList *TemplateParams,
431 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000432 TemplateDeductionInfo &Info,
433 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
434 Expr *Value =
435 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
436 S.Context.NullPtrTy, NTTP->getLocation()),
437 NullPtrType, CK_NullToPointer)
438 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000439 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
440 DeducedTemplateArgument(Value),
441 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000442}
443
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000444/// Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000445/// from the given type- or value-dependent expression.
446///
447/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000448static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
449 Sema &S, TemplateParameterList *TemplateParams,
450 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
451 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000452 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
453 DeducedTemplateArgument(Value),
454 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000455}
456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000457/// Deduce the value of the given non-type template parameter
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000458/// from the given declaration.
459///
460/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000461static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
462 Sema &S, TemplateParameterList *TemplateParams,
463 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
464 TemplateDeductionInfo &Info,
465 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000466 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000467 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000468 return DeduceNonTypeTemplateArgument(
469 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000470}
471
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000472static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000473DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000474 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000475 TemplateName Param,
476 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000477 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000478 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000479 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000480 if (!ParamDecl) {
481 // The parameter type is dependent and is not a template template parameter,
482 // so there is nothing that we can deduce.
483 return Sema::TDK_Success;
484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485
Douglas Gregoradee3e32009-11-11 23:06:43 +0000486 if (TemplateTemplateParmDecl *TempParam
487 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000488 // If we're not deducing at this depth, there's nothing to deduce.
489 if (TempParam->getDepth() != Info.getDeducedDepth())
490 return Sema::TDK_Success;
491
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000492 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000494 Deduced[TempParam->getIndex()],
495 NewDeduced);
496 if (Result.isNull()) {
497 Info.Param = TempParam;
498 Info.FirstArg = Deduced[TempParam->getIndex()];
499 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000503 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
Douglas Gregoradee3e32009-11-11 23:06:43 +0000507 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000508 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000509 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510
Douglas Gregoradee3e32009-11-11 23:06:43 +0000511 // Mismatch of non-dependent template parameter to argument.
512 Info.FirstArg = TemplateArgument(Param);
513 Info.SecondArg = TemplateArgument(Arg);
514 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000515}
516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000517/// Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000518/// type (which is a template-id) with the template argument type.
519///
Chandler Carruthc1263112010-02-07 21:33:28 +0000520/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000521///
522/// \param TemplateParams the template parameters that we are deducing
523///
524/// \param Param the parameter type
525///
526/// \param Arg the argument type
527///
528/// \param Info information about the template argument deduction itself
529///
530/// \param Deduced the deduced template arguments
531///
532/// \returns the result of template argument deduction so far. Note that a
533/// "success" result means that template argument deduction has not yet failed,
534/// but it may still fail, later, for other reasons.
535static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000536DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000537 TemplateParameterList *TemplateParams,
538 const TemplateSpecializationType *Param,
539 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000540 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000541 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000542 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000543
Richard Smith13373182018-01-04 01:24:17 +0000544 // Treat an injected-class-name as its underlying template-id.
545 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
546 Arg = Injected->getInjectedSpecializationType();
547
Douglas Gregore81f3e72009-07-07 23:09:34 +0000548 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000549 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000550 = dyn_cast<TemplateSpecializationType>(Arg)) {
551 // Perform template argument deduction for the template name.
552 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000553 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000554 Param->getTemplateName(),
555 SpecArg->getTemplateName(),
556 Info, Deduced))
557 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000558
Mike Stump11289f42009-09-09 15:08:12 +0000559
Douglas Gregore81f3e72009-07-07 23:09:34 +0000560 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000561 // argument. Ignore any missing/extra arguments, since they could be
562 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000563 return DeduceTemplateArguments(S, TemplateParams,
564 Param->template_arguments(),
565 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000566 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Douglas Gregore81f3e72009-07-07 23:09:34 +0000569 // If the argument type is a class template specialization, we
570 // perform template argument deduction using its template
571 // arguments.
572 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000573 if (!RecordArg) {
574 Info.FirstArg = TemplateArgument(QualType(Param, 0));
575 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000576 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000577 }
Mike Stump11289f42009-09-09 15:08:12 +0000578
579 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000580 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000581 if (!SpecArg) {
582 Info.FirstArg = TemplateArgument(QualType(Param, 0));
583 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000584 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000585 }
Mike Stump11289f42009-09-09 15:08:12 +0000586
Douglas Gregore81f3e72009-07-07 23:09:34 +0000587 // Perform template argument deduction for the template name.
588 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000589 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000590 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000591 Param->getTemplateName(),
592 TemplateName(SpecArg->getSpecializedTemplate()),
593 Info, Deduced))
594 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregor7baabef2010-12-22 18:17:10 +0000596 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000597 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
598 SpecArg->getTemplateArgs().asArray(), Info,
599 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000600}
601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000602/// Determines whether the given type is an opaque type that
John McCall08569062010-08-28 22:14:41 +0000603/// might be more qualified when instantiated.
604static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
605 switch (T->getTypeClass()) {
606 case Type::TypeOfExpr:
607 case Type::TypeOf:
608 case Type::DependentName:
609 case Type::Decltype:
610 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000611 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000612 return true;
613
614 case Type::ConstantArray:
615 case Type::IncompleteArray:
616 case Type::VariableArray:
617 case Type::DependentSizedArray:
618 return IsPossiblyOpaquelyQualifiedType(
619 cast<ArrayType>(T)->getElementType());
620
621 default:
622 return false;
623 }
624}
625
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000626/// Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000628getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000629 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
630 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Douglas Gregor5499af42011-01-05 23:12:31 +0000632 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
633 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor5499af42011-01-05 23:12:31 +0000635 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
636 return std::make_pair(TTP->getDepth(), TTP->getIndex());
637}
638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000639/// Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000641getDepthAndIndex(UnexpandedParameterPack UPP) {
642 if (const TemplateTypeParmType *TTP
643 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
644 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000646 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
647}
648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000649/// Helper function to build a TemplateParameter when we don't
Douglas Gregor5499af42011-01-05 23:12:31 +0000650/// know its type statically.
651static TemplateParameter makeTemplateParameter(Decl *D) {
652 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
653 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000654 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000655 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor5499af42011-01-05 23:12:31 +0000657 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
658}
659
Richard Smith0a80d572014-05-29 01:12:14 +0000660/// A pack that we're currently deducing.
661struct clang::DeducedPack {
Richard Smith0a80d572014-05-29 01:12:14 +0000662 // The index of the pack.
663 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Richard Smith0a80d572014-05-29 01:12:14 +0000665 // The old value of the pack before we started deducing it.
666 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000667
Richard Smith0a80d572014-05-29 01:12:14 +0000668 // A deferred value of this pack from an inner deduction, that couldn't be
669 // deduced because this deduction hadn't happened yet.
670 DeducedTemplateArgument DeferredDeduction;
671
672 // The new value of the pack.
673 SmallVector<DeducedTemplateArgument, 4> New;
674
675 // The outer deduction for this pack, if any.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000676 DeducedPack *Outer = nullptr;
677
678 DeducedPack(unsigned Index) : Index(Index) {}
Richard Smith0a80d572014-05-29 01:12:14 +0000679};
680
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000681namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000682
Richard Smith0a80d572014-05-29 01:12:14 +0000683/// A scope in which we're performing pack deduction.
684class PackDeductionScope {
685public:
686 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
687 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
688 TemplateDeductionInfo &Info, TemplateArgument Pattern)
689 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith130cc442017-02-21 23:49:18 +0000690 // Dig out the partially-substituted pack, if there is one.
691 const TemplateArgument *PartialPackArgs = nullptr;
692 unsigned NumPartialPackArgs = 0;
693 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
694 if (auto *Scope = S.CurrentInstantiationScope)
695 if (auto *Partial = Scope->getPartiallySubstitutedPack(
696 &PartialPackArgs, &NumPartialPackArgs))
697 PartialPackDepthIndex = getDepthAndIndex(Partial);
698
Richard Smith0a80d572014-05-29 01:12:14 +0000699 // Compute the set of template parameter indices that correspond to
700 // parameter packs expanded by the pack expansion.
701 {
702 llvm::SmallBitVector SawIndices(TemplateParams->size());
Richard Smith130cc442017-02-21 23:49:18 +0000703
704 auto AddPack = [&](unsigned Index) {
705 if (SawIndices[Index])
706 return;
707 SawIndices[Index] = true;
708
709 // Save the deduced template argument for the parameter pack expanded
710 // by this pack expansion, then clear out the deduction.
711 DeducedPack Pack(Index);
712 Pack.Saved = Deduced[Index];
713 Deduced[Index] = TemplateArgument();
714
715 Packs.push_back(Pack);
716 };
717
718 // First look for unexpanded packs in the pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000719 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
720 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
721 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
722 unsigned Depth, Index;
723 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith130cc442017-02-21 23:49:18 +0000724 if (Depth == Info.getDeducedDepth())
725 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000726 }
Richard Smith130cc442017-02-21 23:49:18 +0000727 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
728
729 // This pack expansion will have been partially expanded iff the only
730 // unexpanded parameter pack within it is the partially-substituted pack.
731 IsPartiallyExpanded =
732 Packs.size() == 1 &&
733 PartialPackDepthIndex ==
734 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
735
736 // Skip over the pack elements that were expanded into separate arguments.
737 if (IsPartiallyExpanded)
738 PackElements += NumPartialPackArgs;
739
740 // We can also have deduced template parameters that do not actually
741 // appear in the pattern, but can be deduced by it (the type of a non-type
742 // template parameter pack, in particular). These won't have prevented us
743 // from partially expanding the pack.
744 llvm::SmallBitVector Used(TemplateParams->size());
745 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
746 Info.getDeducedDepth(), Used);
747 for (int Index = Used.find_first(); Index != -1;
748 Index = Used.find_next(Index))
749 if (TemplateParams->getParam(Index)->isParameterPack())
750 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000751 }
Richard Smith0a80d572014-05-29 01:12:14 +0000752
753 for (auto &Pack : Packs) {
754 if (Info.PendingDeducedPacks.size() > Pack.Index)
755 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
756 else
757 Info.PendingDeducedPacks.resize(Pack.Index + 1);
758 Info.PendingDeducedPacks[Pack.Index] = &Pack;
759
Richard Smith130cc442017-02-21 23:49:18 +0000760 if (PartialPackDepthIndex ==
761 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
762 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
763 // We pre-populate the deduced value of the partially-substituted
764 // pack with the specified value. This is not entirely correct: the
765 // value is supposed to have been substituted, not deduced, but the
766 // cases where this is observable require an exact type match anyway.
767 //
768 // FIXME: If we could represent a "depth i, index j, pack elem k"
769 // parameter, we could substitute the partially-substituted pack
770 // everywhere and avoid this.
771 if (Pack.New.size() > PackElements)
772 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000773 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000774 }
775 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000776
Richard Smith0a80d572014-05-29 01:12:14 +0000777 ~PackDeductionScope() {
778 for (auto &Pack : Packs)
779 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781
Richard Smithde0d34a2017-01-09 07:14:40 +0000782 /// Determine whether this pack has already been partially expanded into a
783 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000784 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000785
Richard Smith0a80d572014-05-29 01:12:14 +0000786 /// Move to deducing the next element in each pack that is being deduced.
787 void nextPackElement() {
788 // Capture the deduced template arguments for each parameter pack expanded
789 // by this pack expansion, add them to the list of arguments we've deduced
790 // for that pack, then clear out the deduced argument.
791 for (auto &Pack : Packs) {
792 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000793 if (!Pack.New.empty() || !DeducedArg.isNull()) {
794 while (Pack.New.size() < PackElements)
795 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000796 if (Pack.New.size() == PackElements)
797 Pack.New.push_back(DeducedArg);
798 else
799 Pack.New[PackElements] = DeducedArg;
800 DeducedArg = Pack.New.size() > PackElements + 1
801 ? Pack.New[PackElements + 1]
802 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000803 }
804 }
Richard Smith539e8e32017-01-04 01:48:55 +0000805 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000806 }
807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000808 /// Finish template argument deduction for a set of argument packs,
Richard Smith0a80d572014-05-29 01:12:14 +0000809 /// producing the argument packs and checking for consistency with prior
810 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000811 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000812 // Build argument packs for each of the parameter packs expanded by this
813 // pack expansion.
814 for (auto &Pack : Packs) {
815 // Put back the old value for this pack.
816 Deduced[Pack.Index] = Pack.Saved;
817
818 // Build or find a new value for this pack.
819 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000820 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000821 if (Pack.DeferredDeduction.isNull()) {
822 // We were not able to deduce anything for this parameter pack
823 // (because it only appeared in non-deduced contexts), so just
824 // restore the saved argument pack.
825 continue;
826 }
827
828 NewPack = Pack.DeferredDeduction;
829 Pack.DeferredDeduction = TemplateArgument();
830 } else if (Pack.New.empty()) {
831 // If we deduced an empty argument pack, create it now.
832 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
833 } else {
834 TemplateArgument *ArgumentPack =
835 new (S.Context) TemplateArgument[Pack.New.size()];
836 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
837 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000838 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000839 // FIXME: This is wrong, it's possible that some pack elements are
840 // deduced from an array bound and others are not:
841 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
842 // g({1, 2, 3}, {{}, {}});
843 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000844 Pack.New[0].wasDeducedFromArrayBound());
845 }
846
847 // Pick where we're going to put the merged pack.
848 DeducedTemplateArgument *Loc;
849 if (Pack.Outer) {
850 if (Pack.Outer->DeferredDeduction.isNull()) {
851 // Defer checking this pack until we have a complete pack to compare
852 // it against.
853 Pack.Outer->DeferredDeduction = NewPack;
854 continue;
855 }
856 Loc = &Pack.Outer->DeferredDeduction;
857 } else {
858 Loc = &Deduced[Pack.Index];
859 }
860
861 // Check the new pack matches any previous value.
862 DeducedTemplateArgument OldPack = *Loc;
863 DeducedTemplateArgument Result =
864 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
865
866 // If we deferred a deduction of this pack, check that one now too.
867 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
868 OldPack = Result;
869 NewPack = Pack.DeferredDeduction;
870 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
871 }
872
873 if (Result.isNull()) {
874 Info.Param =
875 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
876 Info.FirstArg = OldPack;
877 Info.SecondArg = NewPack;
878 return Sema::TDK_Inconsistent;
879 }
880
881 *Loc = Result;
882 }
883
884 return Sema::TDK_Success;
885 }
886
887private:
888 Sema &S;
889 TemplateParameterList *TemplateParams;
890 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
891 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000892 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000893 bool IsPartiallyExpanded = false;
Richard Smith0a80d572014-05-29 01:12:14 +0000894
895 SmallVector<DeducedPack, 2> Packs;
896};
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000897
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000898} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000899
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000900/// Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901/// types to the list of argument types, as in the parameter-type-lists of
902/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000903///
904/// \param S The semantic analysis object within which we are deducing
905///
906/// \param TemplateParams The template parameters that we are deducing
907///
908/// \param Params The list of parameter types
909///
910/// \param NumParams The number of types in \c Params
911///
912/// \param Args The list of argument types
913///
914/// \param NumArgs The number of types in \c Args
915///
916/// \param Info information about the template argument deduction itself
917///
918/// \param Deduced the deduced template arguments
919///
920/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
921/// how template argument deduction is performed.
922///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000923/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000925/// (C++0x [temp.deduct.partial]).
926///
Douglas Gregor5499af42011-01-05 23:12:31 +0000927/// \returns the result of template argument deduction so far. Note that a
928/// "success" result means that template argument deduction has not yet failed,
929/// but it may still fail, later, for other reasons.
930static Sema::TemplateDeductionResult
931DeduceTemplateArguments(Sema &S,
932 TemplateParameterList *TemplateParams,
933 const QualType *Params, unsigned NumParams,
934 const QualType *Args, unsigned NumArgs,
935 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000936 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000937 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000938 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000939 // Fast-path check to see if we have too many/too few arguments.
940 if (NumParams != NumArgs &&
941 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
942 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000943 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000944
Douglas Gregor5499af42011-01-05 23:12:31 +0000945 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946 // Similarly, if P has a form that contains (T), then each parameter type
947 // Pi of the respective parameter-type- list of P is compared with the
948 // corresponding parameter type Ai of the corresponding parameter-type-list
949 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000950 unsigned ArgIdx = 0, ParamIdx = 0;
951 for (; ParamIdx != NumParams; ++ParamIdx) {
952 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000954 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
955 if (!Expansion) {
956 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000957
Douglas Gregor5499af42011-01-05 23:12:31 +0000958 // Make sure we have an argument.
959 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000960 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000962 if (isa<PackExpansionType>(Args[ArgIdx])) {
963 // C++0x [temp.deduct.type]p22:
964 // If the original function parameter associated with A is a function
965 // parameter pack and the function parameter associated with P is not
966 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000967 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000968 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregor5499af42011-01-05 23:12:31 +0000970 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000971 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
972 Params[ParamIdx], Args[ArgIdx],
973 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000974 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000975 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000976
Douglas Gregor5499af42011-01-05 23:12:31 +0000977 ++ArgIdx;
978 continue;
979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000980
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000981 // C++0x [temp.deduct.type]p5:
982 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000984 // parameter-declaration-clause.
985 if (ParamIdx + 1 < NumParams)
986 return Sema::TDK_Success;
987
Douglas Gregor5499af42011-01-05 23:12:31 +0000988 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000990 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000992 // comparison deduces template arguments for subsequent positions in the
993 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000994
Douglas Gregor5499af42011-01-05 23:12:31 +0000995 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000996 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000997
Douglas Gregor5499af42011-01-05 23:12:31 +0000998 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000999 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001001 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1002 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00001003 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +00001004 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005
Richard Smith0a80d572014-05-29 01:12:14 +00001006 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +00001007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008
Douglas Gregor5499af42011-01-05 23:12:31 +00001009 // Build argument packs for each of the parameter packs expanded by this
1010 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001011 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +00001013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014
Douglas Gregor5499af42011-01-05 23:12:31 +00001015 // Make sure we don't have any extra arguments.
1016 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +00001017 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001018
Douglas Gregor5499af42011-01-05 23:12:31 +00001019 return Sema::TDK_Success;
1020}
1021
Richard Smith34c32502018-07-11 21:07:04 +00001022/// Determine whether the parameter has qualifiers that the argument
1023/// lacks. Put another way, determine whether there is no way to add
1024/// a deduced set of qualifiers to the ParamType that would result in
1025/// its qualifiers matching those of the ArgType.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001026static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1027 QualType ArgType) {
1028 Qualifiers ParamQs = ParamType.getQualifiers();
1029 Qualifiers ArgQs = ArgType.getQualifiers();
1030
1031 if (ParamQs == ArgQs)
1032 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001033
Douglas Gregor1d684c22011-04-28 00:56:09 +00001034 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +00001035 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +00001036 ParamQs.hasObjCGCAttr())
1037 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001038
Douglas Gregor1d684c22011-04-28 00:56:09 +00001039 // Mismatched (but not missing) address spaces.
1040 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1041 ParamQs.hasAddressSpace())
1042 return true;
1043
John McCall31168b02011-06-15 23:02:42 +00001044 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1045 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1046 ParamQs.hasObjCLifetime())
1047 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001048
Richard Smith34c32502018-07-11 21:07:04 +00001049 // CVR qualifiers inconsistent or a superset.
1050 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
Douglas Gregor1d684c22011-04-28 00:56:09 +00001051}
1052
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001053/// Compare types for equality with respect to possibly compatible
Douglas Gregor19a41f12013-04-17 08:45:07 +00001054/// function types (noreturn adjustment, implicit calling conventions). If any
1055/// of parameter and argument is not a function, just perform type comparison.
1056///
1057/// \param Param the template parameter type.
1058///
1059/// \param Arg the argument type.
1060bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1061 CanQualType Arg) {
1062 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1063 *ArgFunction = Arg->getAs<FunctionType>();
1064
1065 // Just compare if not functions.
1066 if (!ParamFunction || !ArgFunction)
1067 return Param == Arg;
1068
Richard Smith3c4f8d22016-10-16 17:54:23 +00001069 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001070 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001071 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001072 return Arg == Context.getCanonicalType(AdjustedParam);
1073
1074 // FIXME: Compatible calling conventions.
1075
1076 return Param == Arg;
1077}
1078
Richard Smith32918772017-02-14 00:25:28 +00001079/// Get the index of the first template parameter that was originally from the
1080/// innermost template-parameter-list. This is 0 except when we concatenate
1081/// the template parameter lists of a class template and a constructor template
1082/// when forming an implicit deduction guide.
1083static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001084 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1085 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001086 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001087 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001088}
1089
1090/// Determine whether a type denotes a forwarding reference.
1091static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1092 // C++1z [temp.deduct.call]p3:
1093 // A forwarding reference is an rvalue reference to a cv-unqualified
1094 // template parameter that does not represent a template parameter of a
1095 // class template.
1096 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1097 if (ParamRef->getPointeeType().getQualifiers())
1098 return false;
1099 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1100 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1101 }
1102 return false;
1103}
1104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001105/// Deduce the template arguments by comparing the parameter type and
Douglas Gregorcceb9752009-06-26 18:27:22 +00001106/// the argument type (C++ [temp.deduct.type]).
1107///
Chandler Carruthc1263112010-02-07 21:33:28 +00001108/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001109///
1110/// \param TemplateParams the template parameters that we are deducing
1111///
1112/// \param ParamIn the parameter type
1113///
1114/// \param ArgIn the argument type
1115///
1116/// \param Info information about the template argument deduction itself
1117///
1118/// \param Deduced the deduced template arguments
1119///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001120/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001121/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001122///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001123/// \param PartialOrdering Whether we're performing template argument deduction
1124/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1125///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001126/// \returns the result of template argument deduction so far. Note that a
1127/// "success" result means that template argument deduction has not yet failed,
1128/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001129static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001130DeduceTemplateArgumentsByTypeMatch(Sema &S,
1131 TemplateParameterList *TemplateParams,
1132 QualType ParamIn, QualType ArgIn,
1133 TemplateDeductionInfo &Info,
1134 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1135 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001136 bool PartialOrdering,
1137 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001138 // We only want to look at the canonical types, since typedefs and
1139 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001140 QualType Param = S.Context.getCanonicalType(ParamIn);
1141 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001142
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001143 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001145 if (const PackExpansionType *ArgExpansion
1146 = dyn_cast<PackExpansionType>(Arg))
1147 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148
Douglas Gregorb837ea42011-01-11 17:34:58 +00001149 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001150 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001151 // Before the partial ordering is done, certain transformations are
1152 // performed on the types used for partial ordering:
1153 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001154 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1155 if (ParamRef)
1156 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
Douglas Gregorb837ea42011-01-11 17:34:58 +00001158 // - If A is a reference type, A is replaced by the type referred to.
1159 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1160 if (ArgRef)
1161 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001162
Richard Smithed563c22015-02-20 04:45:22 +00001163 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1164 // C++11 [temp.deduct.partial]p9:
1165 // If, for a given type, deduction succeeds in both directions (i.e.,
1166 // the types are identical after the transformations above) and both
1167 // P and A were reference types [...]:
1168 // - if [one type] was an lvalue reference and [the other type] was
1169 // not, [the other type] is not considered to be at least as
1170 // specialized as [the first type]
1171 // - if [one type] is more cv-qualified than [the other type],
1172 // [the other type] is not considered to be at least as specialized
1173 // as [the first type]
1174 // Objective-C ARC adds:
1175 // - [one type] has non-trivial lifetime, [the other type] has
1176 // __unsafe_unretained lifetime, and the types are otherwise
1177 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001178 //
Richard Smithed563c22015-02-20 04:45:22 +00001179 // A is "considered to be at least as specialized" as P iff deduction
1180 // succeeds, so we model this as a deduction failure. Note that
1181 // [the first type] is P and [the other type] is A here; the standard
1182 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001183 Qualifiers ParamQuals = Param.getQualifiers();
1184 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001185 if ((ParamRef->isLValueReferenceType() &&
1186 !ArgRef->isLValueReferenceType()) ||
1187 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1188 (ParamQuals.hasNonTrivialObjCLifetime() &&
1189 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1190 ParamQuals.withoutObjCLifetime() ==
1191 ArgQuals.withoutObjCLifetime())) {
1192 Info.FirstArg = TemplateArgument(ParamIn);
1193 Info.SecondArg = TemplateArgument(ArgIn);
1194 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001195 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197
Richard Smithed563c22015-02-20 04:45:22 +00001198 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001199 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001200 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001201 // version of P.
1202 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001203 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001204 // version of A.
1205 Arg = Arg.getUnqualifiedType();
1206 } else {
1207 // C++0x [temp.deduct.call]p4 bullet 1:
1208 // - If the original P is a reference type, the deduced A (i.e., the type
1209 // referred to by the reference) can be more cv-qualified than the
1210 // transformed A.
1211 if (TDF & TDF_ParamWithReferenceType) {
1212 Qualifiers Quals;
1213 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1214 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001215 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001216 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1217 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
Douglas Gregor85f240c2011-01-25 17:19:08 +00001219 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1220 // C++0x [temp.deduct.type]p10:
1221 // If P and A are function types that originated from deduction when
1222 // taking the address of a function template (14.8.2.2) or when deducing
1223 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001224 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001225 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1226 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001228 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1229 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001230 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001231 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001232 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1233 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001234 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001237 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001238 // A template type argument T, a template template argument TT or a
1239 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001240 // the following forms:
1241 //
1242 // T
1243 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001244 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001245 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001246 // Just skip any attempts to deduce from a placeholder type or a parameter
1247 // at a different depth.
1248 if (Arg->isPlaceholderType() ||
1249 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001250 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001251
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001252 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001253 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001254
Douglas Gregor60454822009-07-22 20:02:25 +00001255 // If the argument type is an array type, move the qualifiers up to the
1256 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001257 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001258 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001259 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001260 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001261 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001262 RecanonicalizeArg = true;
1263 }
1264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001266 // The argument type can not be less qualified than the parameter
1267 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001268 if (!(TDF & TDF_IgnoreQualifiers) &&
1269 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001270 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001271 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001272 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001273 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001274 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001275
Lei Liu413f3c52018-05-03 01:43:23 +00001276 // Do not match a function type with a cv-qualified type.
1277 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1278 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1279 return Sema::TDK_NonDeducedMismatch;
1280 }
1281
Richard Smith87d263e2016-12-25 08:05:23 +00001282 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1283 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001284 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001285 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001286
Douglas Gregor1d684c22011-04-28 00:56:09 +00001287 // Remove any qualifiers on the parameter from the deduced type.
1288 // We checked the qualifiers for consistency above.
1289 Qualifiers DeducedQs = DeducedType.getQualifiers();
1290 Qualifiers ParamQs = Param.getQualifiers();
1291 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1292 if (ParamQs.hasObjCGCAttr())
1293 DeducedQs.removeObjCGCAttr();
1294 if (ParamQs.hasAddressSpace())
1295 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001296 if (ParamQs.hasObjCLifetime())
1297 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001298
Douglas Gregore46db902011-06-17 22:11:49 +00001299 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001300 // If template deduction would produce a lifetime qualifier on a type
1301 // that is not a lifetime type, template argument deduction fails.
1302 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1303 !DeducedType->isDependentType()) {
1304 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1305 Info.FirstArg = TemplateArgument(Param);
1306 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001307 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001308 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001309
Douglas Gregora4f2b432011-07-26 14:53:44 +00001310 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001311 // If template deduction would produce an argument type with lifetime type
1312 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001313 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001314 DeducedType->isObjCLifetimeType() &&
1315 !DeducedQs.hasObjCLifetime())
1316 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001317
Douglas Gregor1d684c22011-04-28 00:56:09 +00001318 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1319 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001320
Douglas Gregord6605db2009-07-22 21:30:48 +00001321 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001322 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001323
Richard Smith5f274382016-09-28 23:55:27 +00001324 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001326 Deduced[Index],
1327 NewDeduced);
1328 if (Result.isNull()) {
1329 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1330 Info.FirstArg = Deduced[Index];
1331 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001335 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001337 }
1338
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001339 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001340 Info.FirstArg = TemplateArgument(ParamIn);
1341 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001342
Douglas Gregorfb322d82011-01-14 05:11:40 +00001343 // If the parameter is an already-substituted template parameter
1344 // pack, do nothing: we don't know which of its arguments to look
1345 // at, so we have to wait until all of the parameter packs in this
1346 // expansion have arguments.
1347 if (isa<SubstTemplateTypeParmPackType>(Param))
1348 return Sema::TDK_Success;
1349
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001350 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001351 CanQualType CanParam = S.Context.getCanonicalType(Param);
1352 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001353 if (!(TDF & TDF_IgnoreQualifiers)) {
1354 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001355 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001356 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001357 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001358 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001359 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001360 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001361
Douglas Gregor194ea692012-03-11 03:29:50 +00001362 // If the parameter type is not dependent, there is nothing to deduce.
1363 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001364 if (!(TDF & TDF_SkipNonDependent)) {
Richard Smithcd198152017-06-07 21:46:22 +00001365 bool NonDeduced =
1366 (TDF & TDF_AllowCompatibleFunctionType)
1367 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1368 : Param != Arg;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001369 if (NonDeduced) {
1370 return Sema::TDK_NonDeducedMismatch;
1371 }
1372 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001373 return Sema::TDK_Success;
1374 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001375 } else if (!Param->isDependentType()) {
1376 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1377 ArgUnqualType = CanArg.getUnqualifiedType();
Richard Smithcd198152017-06-07 21:46:22 +00001378 bool Success =
1379 (TDF & TDF_AllowCompatibleFunctionType)
1380 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1381 : ParamUnqualType == ArgUnqualType;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001382 if (Success)
1383 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001384 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001385
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001386 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001387 // Non-canonical types cannot appear here.
1388#define NON_CANONICAL_TYPE(Class, Base) \
1389 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1390#define TYPE(Class, Base)
1391#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001392
Douglas Gregor39c02722011-06-15 16:02:29 +00001393 case Type::TemplateTypeParm:
1394 case Type::SubstTemplateTypeParmPack:
1395 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001396
1397 // These types cannot be dependent, so simply check whether the types are
1398 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001399 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001400 case Type::VariableArray:
1401 case Type::Vector:
1402 case Type::FunctionNoProto:
1403 case Type::Record:
1404 case Type::Enum:
1405 case Type::ObjCObject:
1406 case Type::ObjCInterface:
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001407 case Type::ObjCObjectPointer:
Douglas Gregor194ea692012-03-11 03:29:50 +00001408 if (TDF & TDF_SkipNonDependent)
1409 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001410
Douglas Gregor194ea692012-03-11 03:29:50 +00001411 if (TDF & TDF_IgnoreQualifiers) {
1412 Param = Param.getUnqualifiedType();
1413 Arg = Arg.getUnqualifiedType();
1414 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001415
Douglas Gregor194ea692012-03-11 03:29:50 +00001416 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001417
1418 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001419 case Type::Complex:
1420 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001421 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1422 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001423 ComplexArg->getElementType(),
1424 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001425
1426 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001427
1428 // _Atomic T [extension]
1429 case Type::Atomic:
1430 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001431 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001432 cast<AtomicType>(Param)->getValueType(),
1433 AtomicArg->getValueType(),
1434 Info, Deduced, TDF);
1435
1436 return Sema::TDK_NonDeducedMismatch;
1437
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001438 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001439 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001440 QualType PointeeType;
1441 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1442 PointeeType = PointerArg->getPointeeType();
1443 } else if (const ObjCObjectPointerType *PointerArg
1444 = Arg->getAs<ObjCObjectPointerType>()) {
1445 PointeeType = PointerArg->getPointeeType();
1446 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001447 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
Douglas Gregorfc516c92009-06-26 23:27:24 +00001450 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001451 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1452 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001453 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001454 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001457 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001458 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001459 const LValueReferenceType *ReferenceArg =
1460 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001461 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001462 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001463
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001464 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001465 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001466 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001467 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001468
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001469 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001470 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001471 const RValueReferenceType *ReferenceArg =
1472 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001473 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001474 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001475
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001476 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1477 cast<RValueReferenceType>(Param)->getPointeeType(),
1478 ReferenceArg->getPointeeType(),
1479 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001482 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001483 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001484 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001485 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001486 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001487 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001488
John McCallf7332682010-08-19 00:20:19 +00001489 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001490 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1491 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1492 IncompleteArrayArg->getElementType(),
1493 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001494 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001495
1496 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001497 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001498 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001499 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001500 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001501 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001502
1503 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001504 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001505 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001506 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001507
John McCallf7332682010-08-19 00:20:19 +00001508 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001509 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1510 ConstantArrayParm->getElementType(),
1511 ConstantArrayArg->getElementType(),
1512 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001513 }
1514
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001515 // type [i]
1516 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001517 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001518 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001519 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001520
John McCallf7332682010-08-19 00:20:19 +00001521 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1522
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001523 // Check the element type of the arrays
1524 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001525 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001526 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001527 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1528 DependentArrayParm->getElementType(),
1529 ArrayArg->getElementType(),
1530 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001531 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001533 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001534 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001535 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001536 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001537 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001538
1539 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001540 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001541 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1542 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001543 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001544 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1545 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001546 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001547 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001548 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001549 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001550 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001551 if (const DependentSizedArrayType *DependentArrayArg
1552 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001553 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001554 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001555 DependentArrayArg->getSizeExpr(),
1556 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001557
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001558 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001559 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001560 }
Mike Stump11289f42009-09-09 15:08:12 +00001561
1562 // type(*)(T)
1563 // T(*)()
1564 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001565 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001566 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001567 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001568 dyn_cast<FunctionProtoType>(Arg);
1569 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001570 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001571
1572 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001573 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001576 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001578 != FunctionProtoArg->getRefQualifier() ||
1579 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001580 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001581
Anders Carlsson2128ec72009-06-08 15:19:08 +00001582 // Check return types.
Richard Smithcd198152017-06-07 21:46:22 +00001583 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1584 S, TemplateParams, FunctionProtoParam->getReturnType(),
1585 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001586 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001587
Richard Smithcd198152017-06-07 21:46:22 +00001588 // Check parameter types.
1589 if (auto Result = DeduceTemplateArguments(
1590 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1591 FunctionProtoParam->getNumParams(),
1592 FunctionProtoArg->param_type_begin(),
1593 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1594 return Result;
1595
1596 if (TDF & TDF_AllowCompatibleFunctionType)
1597 return Sema::TDK_Success;
1598
1599 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1600 // deducing through the noexcept-specifier if it's part of the canonical
1601 // type. libstdc++ relies on this.
1602 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1603 if (NonTypeTemplateParmDecl *NTTP =
1604 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1605 : nullptr) {
1606 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1607 "saw non-type template parameter with wrong depth");
1608
1609 llvm::APSInt Noexcept(1);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001610 switch (FunctionProtoArg->canThrow()) {
Richard Smithcd198152017-06-07 21:46:22 +00001611 case CT_Cannot:
1612 Noexcept = 1;
1613 LLVM_FALLTHROUGH;
1614
1615 case CT_Can:
1616 // We give E in noexcept(E) the "deduced from array bound" treatment.
1617 // FIXME: Should we?
1618 return DeduceNonTypeTemplateArgument(
1619 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1620 /*ArrayBound*/true, Info, Deduced);
1621
1622 case CT_Dependent:
1623 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1624 return DeduceNonTypeTemplateArgument(
1625 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1626 // Can't deduce anything from throw(T...).
1627 break;
1628 }
1629 }
1630 // FIXME: Detect non-deduced exception specification mismatches?
1631
1632 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +00001633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001635 case Type::InjectedClassName:
John McCalle78aac42010-03-10 03:28:59 +00001636 // Treat a template's injected-class-name as if the template
1637 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001638 Param = cast<InjectedClassNameType>(Param)
1639 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001640 assert(isa<TemplateSpecializationType>(Param) &&
1641 "injected class name is not a template specialization type");
Richard Smithcd198152017-06-07 21:46:22 +00001642 LLVM_FALLTHROUGH;
John McCalle78aac42010-03-10 03:28:59 +00001643
Douglas Gregor705c9002009-06-26 20:57:09 +00001644 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001645 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001646 // TT<T>
1647 // TT<i>
1648 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001649 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001650 const TemplateSpecializationType *SpecParam =
1651 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001652
Richard Smith9b296e32016-04-25 19:09:05 +00001653 // When Arg cannot be a derived class, we can just try to deduce template
1654 // arguments from the template-id.
1655 const RecordType *RecordT = Arg->getAs<RecordType>();
1656 if (!(TDF & TDF_DerivedClass) || !RecordT)
1657 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1658 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001659
Richard Smith9b296e32016-04-25 19:09:05 +00001660 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1661 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001662
Richard Smith9b296e32016-04-25 19:09:05 +00001663 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1664 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001665
Richard Smith9b296e32016-04-25 19:09:05 +00001666 if (Result == Sema::TDK_Success)
1667 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001668
Richard Smith9b296e32016-04-25 19:09:05 +00001669 // We cannot inspect base classes as part of deduction when the type
1670 // is incomplete, so either instantiate any templates necessary to
1671 // complete the type, or skip over it if it cannot be completed.
1672 if (!S.isCompleteType(Info.getLocation(), Arg))
1673 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001674
Richard Smith9b296e32016-04-25 19:09:05 +00001675 // C++14 [temp.deduct.call] p4b3:
1676 // If P is a class and P has the form simple-template-id, then the
1677 // transformed A can be a derived class of the deduced A. Likewise if
1678 // P is a pointer to a class of the form simple-template-id, the
1679 // transformed A can be a pointer to a derived class pointed to by the
1680 // deduced A.
1681 //
1682 // These alternatives are considered only if type deduction would
1683 // otherwise fail. If they yield more than one possible deduced A, the
1684 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001685
Faisal Vali683b0742016-05-19 02:28:21 +00001686 // Reset the incorrectly deduced argument from above.
1687 Deduced = DeducedOrig;
1688
1689 // Use data recursion to crawl through the list of base classes.
1690 // Visited contains the set of nodes we have already visited, while
1691 // ToVisit is our stack of records that we still need to visit.
1692 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1693 SmallVector<const RecordType *, 8> ToVisit;
1694 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001695 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001696 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001697 while (!ToVisit.empty()) {
1698 // Retrieve the next class in the inheritance hierarchy.
1699 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001700
Faisal Vali683b0742016-05-19 02:28:21 +00001701 // If we have already seen this type, skip it.
1702 if (!Visited.insert(NextT).second)
1703 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001704
Faisal Vali683b0742016-05-19 02:28:21 +00001705 // If this is a base class, try to perform template argument
1706 // deduction from it.
1707 if (NextT != RecordT) {
1708 TemplateDeductionInfo BaseInfo(Info.getLocation());
1709 Sema::TemplateDeductionResult BaseResult =
1710 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1711 QualType(NextT, 0), BaseInfo, Deduced);
1712
1713 // If template argument deduction for this base was successful,
1714 // note that we had some success. Otherwise, ignore any deductions
1715 // from this base class.
1716 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001717 // If we've already seen some success, then deduction fails due to
1718 // an ambiguity (temp.deduct.call p5).
1719 if (Successful)
1720 return Sema::TDK_MiscellaneousDeductionFailure;
1721
Faisal Vali683b0742016-05-19 02:28:21 +00001722 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001723 std::swap(SuccessfulDeduced, Deduced);
1724
Faisal Vali683b0742016-05-19 02:28:21 +00001725 Info.Param = BaseInfo.Param;
1726 Info.FirstArg = BaseInfo.FirstArg;
1727 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001728 }
1729
1730 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001731 }
Mike Stump11289f42009-09-09 15:08:12 +00001732
Faisal Vali683b0742016-05-19 02:28:21 +00001733 // Visit base classes
1734 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1735 for (const auto &Base : Next->bases()) {
1736 assert(Base.getType()->isRecordType() &&
1737 "Base class that isn't a record?");
1738 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1739 }
1740 }
Mike Stump11289f42009-09-09 15:08:12 +00001741
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001742 if (Successful) {
1743 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001744 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001745 }
Richard Smith9b296e32016-04-25 19:09:05 +00001746
Douglas Gregore81f3e72009-07-07 23:09:34 +00001747 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001748 }
1749
Douglas Gregor637d9982009-06-10 23:47:09 +00001750 // T type::*
1751 // T T::*
1752 // T (type::*)()
1753 // type (T::*)()
1754 // type (type::*)(T)
1755 // type (T::*)(T)
1756 // T (type::*)(T)
1757 // T (T::*)()
1758 // T (T::*)(T)
1759 case Type::MemberPointer: {
1760 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1761 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1762 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001763 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001764
David Majnemera381cda2015-11-30 20:34:28 +00001765 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1766 if (ParamPointeeType->isFunctionType())
1767 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1768 /*IsCtorOrDtor=*/false, Info.getLocation());
1769 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1770 if (ArgPointeeType->isFunctionType())
1771 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1772 /*IsCtorOrDtor=*/false, Info.getLocation());
1773
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001774 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001775 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001776 ParamPointeeType,
1777 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001778 Info, Deduced,
1779 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001780 return Result;
1781
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001782 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1783 QualType(MemPtrParam->getClass(), 0),
1784 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001785 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001786 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001787 }
1788
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001789 // (clang extension)
1790 //
Mike Stump11289f42009-09-09 15:08:12 +00001791 // type(^)(T)
1792 // T(^)()
1793 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001794 case Type::BlockPointer: {
1795 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1796 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001797
Anders Carlssona767eee2009-06-12 16:23:10 +00001798 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001799 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001800
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001801 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1802 BlockPtrParam->getPointeeType(),
1803 BlockPtrArg->getPointeeType(),
1804 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001805 }
1806
Douglas Gregor39c02722011-06-15 16:02:29 +00001807 // (clang extension)
1808 //
1809 // T __attribute__(((ext_vector_type(<integral constant>))))
1810 case Type::ExtVector: {
1811 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1812 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1813 // Make sure that the vectors have the same number of elements.
1814 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1815 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001816
Douglas Gregor39c02722011-06-15 16:02:29 +00001817 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001818 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1819 VectorParam->getElementType(),
1820 VectorArg->getElementType(),
1821 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001822 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001823
1824 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001825 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1826 // We can't check the number of elements, since the argument has a
1827 // dependent number of elements. This can only occur during partial
1828 // ordering.
1829
1830 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001831 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1832 VectorParam->getElementType(),
1833 VectorArg->getElementType(),
1834 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001835 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001836
Douglas Gregor39c02722011-06-15 16:02:29 +00001837 return Sema::TDK_NonDeducedMismatch;
1838 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001839
Douglas Gregor39c02722011-06-15 16:02:29 +00001840 // (clang extension)
1841 //
1842 // T __attribute__(((ext_vector_type(N))))
1843 case Type::DependentSizedExtVector: {
1844 const DependentSizedExtVectorType *VectorParam
1845 = cast<DependentSizedExtVectorType>(Param);
1846
1847 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1848 // Perform deduction on the element types.
1849 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001850 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1851 VectorParam->getElementType(),
1852 VectorArg->getElementType(),
1853 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001854 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001855
Douglas Gregor39c02722011-06-15 16:02:29 +00001856 // Perform deduction on the vector size, if we can.
1857 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001858 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001859 if (!NTTP)
1860 return Sema::TDK_Success;
1861
1862 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1863 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001864 // Note that we use the "array bound" rules here; just like in that
1865 // case, we don't have any particular type for the vector size, but
1866 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001867 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001868 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001869 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001870 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001871
1872 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001873 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1874 // Perform deduction on the element types.
1875 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001876 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1877 VectorParam->getElementType(),
1878 VectorArg->getElementType(),
1879 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001880 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001881
Douglas Gregor39c02722011-06-15 16:02:29 +00001882 // Perform deduction on the vector size, if we can.
1883 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001884 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001885 if (!NTTP)
1886 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001887
Richard Smith5f274382016-09-28 23:55:27 +00001888 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1889 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001890 Info, Deduced);
1891 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001892
Douglas Gregor39c02722011-06-15 16:02:29 +00001893 return Sema::TDK_NonDeducedMismatch;
1894 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001895
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001896 // (clang extension)
1897 //
1898 // T __attribute__(((address_space(N))))
1899 case Type::DependentAddressSpace: {
1900 const DependentAddressSpaceType *AddressSpaceParam =
1901 cast<DependentAddressSpaceType>(Param);
1902
1903 if (const DependentAddressSpaceType *AddressSpaceArg =
1904 dyn_cast<DependentAddressSpaceType>(Arg)) {
1905 // Perform deduction on the pointer type.
1906 if (Sema::TemplateDeductionResult Result =
1907 DeduceTemplateArgumentsByTypeMatch(
1908 S, TemplateParams, AddressSpaceParam->getPointeeType(),
1909 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
1910 return Result;
1911
1912 // Perform deduction on the address space, if we can.
1913 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1914 Info, AddressSpaceParam->getAddrSpaceExpr());
1915 if (!NTTP)
1916 return Sema::TDK_Success;
1917
1918 return DeduceNonTypeTemplateArgument(
1919 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
1920 Deduced);
1921 }
1922
Alexander Richardson6d989432017-10-15 18:48:14 +00001923 if (isTargetAddressSpace(Arg.getAddressSpace())) {
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001924 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
1925 false);
Alexander Richardson6d989432017-10-15 18:48:14 +00001926 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001927
1928 // Perform deduction on the pointer types.
1929 if (Sema::TemplateDeductionResult Result =
1930 DeduceTemplateArgumentsByTypeMatch(
1931 S, TemplateParams, AddressSpaceParam->getPointeeType(),
1932 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
1933 return Result;
1934
1935 // Perform deduction on the address space, if we can.
1936 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1937 Info, AddressSpaceParam->getAddrSpaceExpr());
1938 if (!NTTP)
1939 return Sema::TDK_Success;
1940
1941 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1942 ArgAddressSpace, S.Context.IntTy,
1943 true, Info, Deduced);
1944 }
1945
1946 return Sema::TDK_NonDeducedMismatch;
1947 }
1948
Douglas Gregor637d9982009-06-10 23:47:09 +00001949 case Type::TypeOfExpr:
1950 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001951 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001952 case Type::UnresolvedUsing:
1953 case Type::Decltype:
1954 case Type::UnaryTransform:
1955 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001956 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00001957 case Type::DependentTemplateSpecialization:
1958 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001959 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001960 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001961 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001962 }
1963
David Blaikiee4d798f2012-01-20 21:50:17 +00001964 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001965}
1966
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001967static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001968DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001969 TemplateParameterList *TemplateParams,
1970 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001971 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001972 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001973 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001974 // If the template argument is a pack expansion, perform template argument
1975 // deduction against the pattern of that expansion. This only occurs during
1976 // partial ordering.
1977 if (Arg.isPackExpansion())
1978 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001980 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001981 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001982 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001983
1984 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001985 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001986 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1987 Param.getAsType(),
1988 Arg.getAsType(),
1989 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001990 Info.FirstArg = Param;
1991 Info.SecondArg = Arg;
1992 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001993
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001994 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001995 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001997 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001998 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001999 Info.FirstArg = Param;
2000 Info.SecondArg = Arg;
2001 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002002
2003 case TemplateArgument::TemplateExpansion:
2004 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002006 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002007 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00002008 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00002009 return Sema::TDK_Success;
2010
2011 Info.FirstArg = Param;
2012 Info.SecondArg = Arg;
2013 return Sema::TDK_NonDeducedMismatch;
2014
2015 case TemplateArgument::NullPtr:
2016 if (Arg.getKind() == TemplateArgument::NullPtr &&
2017 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002018 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002019
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002020 Info.FirstArg = Param;
2021 Info.SecondArg = Arg;
2022 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002024 case TemplateArgument::Integral:
2025 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002026 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002027 return Sema::TDK_Success;
2028
2029 Info.FirstArg = Param;
2030 Info.SecondArg = Arg;
2031 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002032 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002033
2034 if (Arg.getKind() == TemplateArgument::Expression) {
2035 Info.FirstArg = Param;
2036 Info.SecondArg = Arg;
2037 return Sema::TDK_NonDeducedMismatch;
2038 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002039
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002040 Info.FirstArg = Param;
2041 Info.SecondArg = Arg;
2042 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002043
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002044 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00002045 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002046 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002047 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00002048 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002049 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00002050 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002051 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002052 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00002053 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00002054 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2055 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00002056 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002057 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00002058 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2059 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002060 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00002061 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2062 Arg.getAsDecl(),
2063 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002064 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002066 Info.FirstArg = Param;
2067 Info.SecondArg = Arg;
2068 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002071 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002072 return Sema::TDK_Success;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002073
Anders Carlssonbc343912009-06-15 17:04:53 +00002074 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00002075 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
David Blaikiee4d798f2012-01-20 21:50:17 +00002078 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002079}
2080
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002081/// Determine whether there is a template argument to be used for
Douglas Gregor7baabef2010-12-22 18:17:10 +00002082/// deduction.
2083///
2084/// This routine "expands" argument packs in-place, overriding its input
2085/// parameters so that \c Args[ArgIdx] will be the available template argument.
2086///
2087/// \returns true if there is another template argument (which will be at
2088/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00002089static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2090 unsigned &ArgIdx) {
2091 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00002092 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093
Douglas Gregor7baabef2010-12-22 18:17:10 +00002094 const TemplateArgument &Arg = Args[ArgIdx];
2095 if (Arg.getKind() != TemplateArgument::Pack)
2096 return true;
2097
Richard Smith0bda5b52016-12-23 23:46:56 +00002098 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2099 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002100 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002101 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002102}
2103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002104/// Determine whether the given set of template arguments has a pack
Douglas Gregord0ad2942010-12-23 01:24:45 +00002105/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00002106static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2107 bool FoundPackExpansion = false;
2108 for (const auto &A : Args) {
2109 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00002110 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00002111
2112 if (A.getKind() == TemplateArgument::Pack)
2113 return hasPackExpansionBeforeEnd(A.pack_elements());
2114
2115 if (A.isPackExpansion())
2116 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00002117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118
Douglas Gregord0ad2942010-12-23 01:24:45 +00002119 return false;
2120}
2121
Douglas Gregor7baabef2010-12-22 18:17:10 +00002122static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002123DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00002124 ArrayRef<TemplateArgument> Params,
2125 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002126 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002127 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2128 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002129 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130 // If the template argument list of P contains a pack expansion that is not
2131 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002132 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00002133 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00002134 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002136 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 // If P has a form that contains <T> or <i>, then each argument Pi of the
2138 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002139 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002140 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002141 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00002142 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002143 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Douglas Gregor7baabef2010-12-22 18:17:10 +00002145 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00002146 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002147 return NumberOfArgumentsMustMatch
2148 ? Sema::TDK_MiscellaneousDeductionFailure
2149 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150
Richard Smith26b86ea2016-12-31 21:41:23 +00002151 // C++1z [temp.deduct.type]p9:
2152 // During partial ordering, if Ai was originally a pack expansion [and]
2153 // Pi is not a pack expansion, template argument deduction fails.
2154 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002155 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002157 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002158 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002159 = DeduceTemplateArguments(S, TemplateParams,
2160 Params[ParamIdx], Args[ArgIdx],
2161 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162 return Result;
2163
Douglas Gregor7baabef2010-12-22 18:17:10 +00002164 // Move to the next argument.
2165 ++ArgIdx;
2166 continue;
2167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002169 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002171 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002172 // If Pi is a pack expansion, then the pattern of Pi is compared with
2173 // each remaining argument in the template argument list of A. Each
2174 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002175 // template parameter packs expanded by Pi.
2176 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002178 // FIXME: If there are no remaining arguments, we can bail out early
2179 // and set any deduced parameter packs to an empty argument pack.
2180 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002181
Richard Smith0a80d572014-05-29 01:12:14 +00002182 // Prepare to deduce the packs within the pattern.
2183 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002184
2185 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002187 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00002188 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002189 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002190 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002191 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2192 Info, Deduced))
2193 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002194
Richard Smith0a80d572014-05-29 01:12:14 +00002195 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002198 // Build argument packs for each of the parameter packs expanded by this
2199 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002200 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203
Douglas Gregor7baabef2010-12-22 18:17:10 +00002204 return Sema::TDK_Success;
2205}
2206
Mike Stump11289f42009-09-09 15:08:12 +00002207static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002208DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002209 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002210 const TemplateArgumentList &ParamList,
2211 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002212 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002213 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002214 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002215 ArgList.asArray(), Info, Deduced,
2216 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002217}
2218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002219/// Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002220static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002221 TemplateArgument X,
2222 const TemplateArgument &Y,
2223 bool PackExpansionMatchesPack = false) {
2224 // If we're checking deduced arguments (X) against original arguments (Y),
2225 // we will have flattened packs to non-expansions in X.
2226 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2227 X = X.getPackExpansionPattern();
2228
Douglas Gregor705c9002009-06-26 20:57:09 +00002229 if (X.getKind() != Y.getKind())
2230 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002231
Douglas Gregor705c9002009-06-26 20:57:09 +00002232 switch (X.getKind()) {
2233 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002234 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002235
Douglas Gregor705c9002009-06-26 20:57:09 +00002236 case TemplateArgument::Type:
2237 return Context.getCanonicalType(X.getAsType()) ==
2238 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002239
Douglas Gregor705c9002009-06-26 20:57:09 +00002240 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002241 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002242
2243 case TemplateArgument::NullPtr:
2244 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002245
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002246 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002247 case TemplateArgument::TemplateExpansion:
2248 return Context.getCanonicalTemplateName(
2249 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2250 Context.getCanonicalTemplateName(
2251 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252
Douglas Gregor705c9002009-06-26 20:57:09 +00002253 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002254 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002255
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002256 case TemplateArgument::Expression: {
2257 llvm::FoldingSetNodeID XID, YID;
2258 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002259 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002260 return XID == YID;
2261 }
Mike Stump11289f42009-09-09 15:08:12 +00002262
Douglas Gregor705c9002009-06-26 20:57:09 +00002263 case TemplateArgument::Pack:
2264 if (X.pack_size() != Y.pack_size())
2265 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002266
2267 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2268 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002269 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002270 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002271 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002272 return false;
2273
2274 return true;
2275 }
2276
David Blaikiee4d798f2012-01-20 21:50:17 +00002277 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002278}
2279
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002280/// Allocate a TemplateArgumentLoc where all locations have
Douglas Gregorca4686d2011-01-04 23:35:54 +00002281/// been initialized to the given location.
2282///
James Dennett634962f2012-06-14 21:40:34 +00002283/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002284/// location information for.
2285///
2286/// \param NTTPType For a declaration template argument, the type of
2287/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002288/// argument. Can be null if no type sugar is available to add to the
2289/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002290///
2291/// \param Loc The source location to use for the resulting template
2292/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002293TemplateArgumentLoc
2294Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2295 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002296 switch (Arg.getKind()) {
2297 case TemplateArgument::Null:
2298 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299
Douglas Gregorca4686d2011-01-04 23:35:54 +00002300 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002301 return TemplateArgumentLoc(
2302 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
Douglas Gregorca4686d2011-01-04 23:35:54 +00002304 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002305 if (NTTPType.isNull())
2306 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002307 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2308 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002309 return TemplateArgumentLoc(TemplateArgument(E), E);
2310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311
Eli Friedmanb826a002012-09-26 02:36:12 +00002312 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002313 if (NTTPType.isNull())
2314 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002315 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2316 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002317 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2318 E);
2319 }
2320
Douglas Gregorca4686d2011-01-04 23:35:54 +00002321 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002322 Expr *E =
2323 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002324 return TemplateArgumentLoc(TemplateArgument(E), E);
2325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002326
Douglas Gregor9d802122011-03-02 17:09:35 +00002327 case TemplateArgument::Template:
2328 case TemplateArgument::TemplateExpansion: {
2329 NestedNameSpecifierLocBuilder Builder;
2330 TemplateName Template = Arg.getAsTemplate();
2331 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002332 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002333 else if (QualifiedTemplateName *QTN =
2334 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002335 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002336
Douglas Gregor9d802122011-03-02 17:09:35 +00002337 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002338 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002339 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002340
2341 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002342 Loc, Loc);
2343 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002344
Douglas Gregorca4686d2011-01-04 23:35:54 +00002345 case TemplateArgument::Expression:
2346 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347
Douglas Gregorca4686d2011-01-04 23:35:54 +00002348 case TemplateArgument::Pack:
2349 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002351
David Blaikiee4d798f2012-01-20 21:50:17 +00002352 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002353}
2354
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002355/// Convert the given deduced template argument and add it to the set of
Douglas Gregorca4686d2011-01-04 23:35:54 +00002356/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002357static bool
2358ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2359 DeducedTemplateArgument Arg,
2360 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002361 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002362 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002363 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002364 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2365 unsigned ArgumentPackIndex) {
2366 // Convert the deduced template argument into a template
2367 // argument that we can check, almost as if the user had written
2368 // the template argument explicitly.
2369 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002370 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002371
2372 // Check the template argument, converting it as necessary.
2373 return S.CheckTemplateArgument(
2374 Param, ArgLoc, Template, Template->getLocation(),
2375 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002376 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002377 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2378 : Sema::CTAK_Deduced)
2379 : Sema::CTAK_Specified);
2380 };
2381
Douglas Gregorca4686d2011-01-04 23:35:54 +00002382 if (Arg.getKind() == TemplateArgument::Pack) {
2383 // This is a template argument pack, so check each of its arguments against
2384 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002385 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002386 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002387 // When converting the deduced template argument, append it to the
2388 // general output list. We need to do this so that the template argument
2389 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002390 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002391 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002392 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2393 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002394 if (P.isNull()) {
2395 // We deduced arguments for some elements of this pack, but not for
2396 // all of them. This happens if we get a conditionally-non-deduced
2397 // context in a pack expansion (such as an overload set in one of the
2398 // arguments).
2399 S.Diag(Param->getLocation(),
2400 diag::err_template_arg_deduced_incomplete_pack)
2401 << Arg << Param;
2402 return true;
2403 }
Richard Smith37acb792016-02-03 20:15:01 +00002404 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002405 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406
Douglas Gregor51bc5712011-01-05 20:52:18 +00002407 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002408 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410
Richard Smithdf18ee92016-02-03 20:40:30 +00002411 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002412 // itself, in case that substitution fails.
2413 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002414 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002415 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002416 MultiLevelTemplateArgumentList Args(TemplateArgs);
2417
2418 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2419 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2420 NTTP, Output,
2421 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002422 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002423 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2424 NTTP->getDeclName()).isNull())
2425 return true;
2426 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2427 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2428 TTP, Output,
2429 Template->getSourceRange());
2430 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2431 return true;
2432 }
2433 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002434 }
Richard Smith37acb792016-02-03 20:15:01 +00002435
Douglas Gregorca4686d2011-01-04 23:35:54 +00002436 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002437 Output.push_back(
2438 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002439 return false;
2440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002441
Richard Smith37acb792016-02-03 20:15:01 +00002442 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002443}
2444
Richard Smith1f5be4d2016-12-21 01:10:31 +00002445// FIXME: This should not be a template, but
2446// ClassTemplatePartialSpecializationDecl sadly does not derive from
2447// TemplateDecl.
2448template<typename TemplateDeclT>
2449static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002450 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002451 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2452 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2453 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002454 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002455 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2456
2457 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2458 NamedDecl *Param = TemplateParams->getParam(I);
2459
2460 if (!Deduced[I].isNull()) {
2461 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002462 // We may have had explicitly-specified template arguments for a
2463 // template parameter pack (that may or may not have been extended
2464 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002465 if (Param->isParameterPack() && CurrentInstantiationScope &&
2466 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2467 // Forget the partially-substituted pack; its substitution is now
2468 // complete.
2469 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2470 // We still need to check the argument in case it was extended by
2471 // deduction.
2472 } else {
2473 // We have already fully type-checked and converted this
2474 // argument, because it was explicitly-specified. Just record the
2475 // presence of this argument.
2476 Builder.push_back(Deduced[I]);
2477 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002478 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002479 }
2480
Richard Smith9c0c9862017-01-05 20:27:28 +00002481 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002482 // checked and converted.
2483 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002484 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002485 Info.Param = makeTemplateParameter(Param);
2486 // FIXME: These template arguments are temporary. Free them!
2487 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2488 return Sema::TDK_SubstitutionFailure;
2489 }
2490
2491 continue;
2492 }
2493
2494 // C++0x [temp.arg.explicit]p3:
2495 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2496 // be deduced to an empty sequence of template arguments.
2497 // FIXME: Where did the word "trailing" come from?
2498 if (Param->isTemplateParameterPack()) {
2499 // We may have had explicitly-specified template arguments for this
2500 // template parameter pack. If so, our empty deduction extends the
2501 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2502 const TemplateArgument *ExplicitArgs;
2503 unsigned NumExplicitArgs;
2504 if (CurrentInstantiationScope &&
2505 CurrentInstantiationScope->getPartiallySubstitutedPack(
2506 &ExplicitArgs, &NumExplicitArgs) == Param) {
2507 Builder.push_back(TemplateArgument(
2508 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2509
2510 // Forget the partially-substituted pack; its substitution is now
2511 // complete.
2512 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2513 } else {
2514 // Go through the motions of checking the empty argument pack against
2515 // the parameter pack.
2516 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002517 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2518 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002519 Info.Param = makeTemplateParameter(Param);
2520 // FIXME: These template arguments are temporary. Free them!
2521 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2522 return Sema::TDK_SubstitutionFailure;
2523 }
2524 }
2525 continue;
2526 }
2527
2528 // Substitute into the default template argument, if available.
2529 bool HasDefaultArg = false;
2530 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2531 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002532 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2533 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002534 return Sema::TDK_Incomplete;
2535 }
2536
2537 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2538 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2539 HasDefaultArg);
2540
2541 // If there was no default argument, deduction is incomplete.
2542 if (DefArg.getArgument().isNull()) {
2543 Info.Param = makeTemplateParameter(
2544 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2545 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002546 if (PartialOverloading) break;
2547
Richard Smith1f5be4d2016-12-21 01:10:31 +00002548 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2549 : Sema::TDK_Incomplete;
2550 }
2551
2552 // Check whether we can actually use the default argument.
2553 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2554 TD->getSourceRange().getEnd(), 0, Builder,
2555 Sema::CTAK_Specified)) {
2556 Info.Param = makeTemplateParameter(
2557 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2558 // FIXME: These template arguments are temporary. Free them!
2559 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2560 return Sema::TDK_SubstitutionFailure;
2561 }
2562
2563 // If we get here, we successfully used the default template argument.
2564 }
2565
2566 return Sema::TDK_Success;
2567}
2568
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002569static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002570 if (auto *DC = dyn_cast<DeclContext>(D))
2571 return DC;
2572 return D->getDeclContext();
2573}
2574
2575template<typename T> struct IsPartialSpecialization {
2576 static constexpr bool value = false;
2577};
2578template<>
2579struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2580 static constexpr bool value = true;
2581};
2582template<>
2583struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2584 static constexpr bool value = true;
2585};
2586
2587/// Complete template argument deduction for a partial specialization.
2588template <typename T>
2589static typename std::enable_if<IsPartialSpecialization<T>::value,
2590 Sema::TemplateDeductionResult>::type
2591FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002592 Sema &S, T *Partial, bool IsPartialOrdering,
2593 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002594 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2595 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002596 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002597 EnterExpressionEvaluationContext Unevaluated(
2598 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002599 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002600
Richard Smith0da6dc42016-12-24 16:40:51 +00002601 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002602
2603 // C++ [temp.deduct.type]p2:
2604 // [...] or if any template argument remains neither deduced nor
2605 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002606 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002607 if (auto Result = ConvertDeducedTemplateArguments(
2608 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002609 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002610
Douglas Gregor684268d2010-04-29 06:21:43 +00002611 // Form the template argument list from the deduced template arguments.
2612 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002613 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002614
Douglas Gregor684268d2010-04-29 06:21:43 +00002615 Info.reset(DeducedArgumentList);
2616
2617 // Substitute the deduced template arguments into the template
2618 // arguments of the class template partial specialization, and
2619 // verify that the instantiated template arguments are both valid
2620 // and are equivalent to the template arguments originally provided
2621 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002622 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002623 auto *Template = Partial->getSpecializedTemplate();
2624 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2625 Partial->getTemplateArgsAsWritten();
2626 const TemplateArgumentLoc *PartialTemplateArgs =
2627 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002628
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002629 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2630 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002631
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002632 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002633 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2634 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2635 if (ParamIdx >= Partial->getTemplateParameters()->size())
2636 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2637
Richard Smith0da6dc42016-12-24 16:40:51 +00002638 Decl *Param = const_cast<NamedDecl *>(
2639 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002640 Info.Param = makeTemplateParameter(Param);
2641 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2642 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002643 }
2644
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002645 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002646 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2647 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002648 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649
Richard Smith0da6dc42016-12-24 16:40:51 +00002650 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002651 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002652 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002653 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002654 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002655 Info.FirstArg = TemplateArgs[I];
2656 Info.SecondArg = InstArg;
2657 return Sema::TDK_NonDeducedMismatch;
2658 }
2659 }
2660
2661 if (Trap.hasErrorOccurred())
2662 return Sema::TDK_SubstitutionFailure;
2663
2664 return Sema::TDK_Success;
2665}
2666
Richard Smith0e617ec2016-12-27 07:56:27 +00002667/// Complete template argument deduction for a class or variable template,
2668/// when partial ordering against a partial specialization.
2669// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002670static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002671 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2672 const TemplateArgumentList &TemplateArgs,
2673 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2674 TemplateDeductionInfo &Info) {
2675 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002676 EnterExpressionEvaluationContext Unevaluated(
2677 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002678 Sema::SFINAETrap Trap(S);
2679
2680 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2681
2682 // C++ [temp.deduct.type]p2:
2683 // [...] or if any template argument remains neither deduced nor
2684 // explicitly specified, template argument deduction fails.
2685 SmallVector<TemplateArgument, 4> Builder;
2686 if (auto Result = ConvertDeducedTemplateArguments(
2687 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2688 return Result;
2689
2690 // Check that we produced the correct argument list.
2691 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2692 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2693 TemplateArgument InstArg = Builder[I];
2694 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2695 /*PackExpansionMatchesPack*/true)) {
2696 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2697 Info.FirstArg = TemplateArgs[I];
2698 Info.SecondArg = InstArg;
2699 return Sema::TDK_NonDeducedMismatch;
2700 }
2701 }
2702
2703 if (Trap.hasErrorOccurred())
2704 return Sema::TDK_SubstitutionFailure;
2705
2706 return Sema::TDK_Success;
2707}
2708
2709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002710/// Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002711/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002712/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002713Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002714Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002715 const TemplateArgumentList &TemplateArgs,
2716 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002717 if (Partial->isInvalidDecl())
2718 return TDK_Invalid;
2719
Douglas Gregor170bc422009-06-12 22:31:52 +00002720 // C++ [temp.class.spec.match]p2:
2721 // A partial specialization matches a given actual template
2722 // argument list if the template arguments of the partial
2723 // specialization can be deduced from the actual template argument
2724 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002725
2726 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002727 EnterExpressionEvaluationContext Unevaluated(
2728 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002729 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002730
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002731 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002732 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002733 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002734 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002735 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002736 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002737 TemplateArgs, Info, Deduced))
2738 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002739
Richard Smith80934652012-07-16 01:09:10 +00002740 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002741 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2742 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002743 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002744 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002745
Douglas Gregore1416332009-06-14 08:02:22 +00002746 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002747 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002748
Richard Smith87d263e2016-12-25 08:05:23 +00002749 return ::FinishTemplateArgumentDeduction(
2750 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002751}
Douglas Gregor91772d12009-06-13 00:26:55 +00002752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002753/// Perform template argument deduction to determine whether
Larisse Voufo39a1e502013-08-06 01:03:05 +00002754/// the given template arguments match the given variable template
2755/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002756Sema::TemplateDeductionResult
2757Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2758 const TemplateArgumentList &TemplateArgs,
2759 TemplateDeductionInfo &Info) {
2760 if (Partial->isInvalidDecl())
2761 return TDK_Invalid;
2762
2763 // C++ [temp.class.spec.match]p2:
2764 // A partial specialization matches a given actual template
2765 // argument list if the template arguments of the partial
2766 // specialization can be deduced from the actual template argument
2767 // list (14.8.2).
2768
2769 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002770 EnterExpressionEvaluationContext Unevaluated(
2771 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002772 SFINAETrap Trap(*this);
2773
2774 SmallVector<DeducedTemplateArgument, 4> Deduced;
2775 Deduced.resize(Partial->getTemplateParameters()->size());
2776 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2777 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2778 TemplateArgs, Info, Deduced))
2779 return Result;
2780
2781 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002782 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2783 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002784 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002785 return TDK_InstantiationDepth;
2786
2787 if (Trap.hasErrorOccurred())
2788 return Sema::TDK_SubstitutionFailure;
2789
Richard Smith87d263e2016-12-25 08:05:23 +00002790 return ::FinishTemplateArgumentDeduction(
2791 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002792}
2793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002794/// Determine whether the given type T is a simple-template-id type.
Douglas Gregorfc516c92009-06-26 23:27:24 +00002795static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002796 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002797 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002798 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Richard Smith1363e8f2017-09-07 07:22:36 +00002800 // C++17 [temp.local]p2:
2801 // the injected-class-name [...] is equivalent to the template-name followed
2802 // by the template-arguments of the class template specialization or partial
2803 // specialization enclosed in <>
2804 // ... which means it's equivalent to a simple-template-id.
2805 //
2806 // This only arises during class template argument deduction for a copy
2807 // deduction candidate, where it permits slicing.
2808 if (T->getAs<InjectedClassNameType>())
2809 return true;
2810
Douglas Gregorfc516c92009-06-26 23:27:24 +00002811 return false;
2812}
Douglas Gregor9b146582009-07-08 20:55:45 +00002813
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002814/// Substitute the explicitly-provided template arguments into the
Douglas Gregor9b146582009-07-08 20:55:45 +00002815/// given function template according to C++ [temp.arg.explicit].
2816///
2817/// \param FunctionTemplate the function template into which the explicit
2818/// template arguments will be substituted.
2819///
James Dennett634962f2012-06-14 21:40:34 +00002820/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002821/// arguments.
2822///
Mike Stump11289f42009-09-09 15:08:12 +00002823/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002824/// with the converted and checked explicit template arguments.
2825///
Mike Stump11289f42009-09-09 15:08:12 +00002826/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002827/// parameters.
2828///
2829/// \param FunctionType if non-NULL, the result type of the function template
2830/// will also be instantiated and the pointed-to value will be updated with
2831/// the instantiated function type.
2832///
2833/// \param Info if substitution fails for any reason, this object will be
2834/// populated with more information about the failure.
2835///
2836/// \returns TDK_Success if substitution was successful, or some failure
2837/// condition.
2838Sema::TemplateDeductionResult
2839Sema::SubstituteExplicitTemplateArguments(
2840 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002841 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002842 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2843 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002844 QualType *FunctionType,
2845 TemplateDeductionInfo &Info) {
2846 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2847 TemplateParameterList *TemplateParams
2848 = FunctionTemplate->getTemplateParameters();
2849
John McCall6b51f282009-11-23 01:53:49 +00002850 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002851 // No arguments to substitute; just copy over the parameter types and
2852 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002853 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002854 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002855
Douglas Gregor9b146582009-07-08 20:55:45 +00002856 if (FunctionType)
2857 *FunctionType = Function->getType();
2858 return TDK_Success;
2859 }
Mike Stump11289f42009-09-09 15:08:12 +00002860
Eli Friedman77dcc722012-02-08 03:07:05 +00002861 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002862 EnterExpressionEvaluationContext Unevaluated(
2863 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002864 SFINAETrap Trap(*this);
2865
Douglas Gregor9b146582009-07-08 20:55:45 +00002866 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002867 // Template arguments that are present shall be specified in the
2868 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002869 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002870 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002871 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002872
2873 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002874 // explicitly-specified template arguments against this function template,
2875 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002876 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00002877 InstantiatingTemplate Inst(
2878 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
2879 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002880 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002881 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002882
Richard Smith11255ec2017-01-18 19:19:22 +00002883 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2884 ExplicitTemplateArgs, true, Builder, false) ||
2885 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002886 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002887 if (Index >= TemplateParams->size())
2888 Index = TemplateParams->size() - 1;
2889 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002890 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002891 }
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregor9b146582009-07-08 20:55:45 +00002893 // Form the template argument list from the explicitly-specified
2894 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002895 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002896 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002897 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898
John McCall036855a2010-10-12 19:40:14 +00002899 // Template argument deduction and the final substitution should be
2900 // done in the context of the templated declaration. Explicit
2901 // argument substitution, on the other hand, needs to happen in the
2902 // calling context.
2903 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2904
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002906 // note that the template argument pack is partially substituted and record
2907 // the explicit template arguments. They'll be used as part of deduction
2908 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002909 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2910 const TemplateArgument &Arg = Builder[I];
2911 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002912 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002914 Arg.pack_begin(),
2915 Arg.pack_size());
2916 break;
2917 }
2918 }
2919
Richard Smith5e580292012-02-10 09:58:53 +00002920 const FunctionProtoType *Proto
2921 = Function->getType()->getAs<FunctionProtoType>();
2922 assert(Proto && "Function template does not have a prototype?");
2923
Richard Smith70b13042015-01-09 01:19:56 +00002924 // Isolate our substituted parameters from our caller.
2925 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2926
John McCallc8e321d2016-03-01 02:09:25 +00002927 ExtParameterInfoBuilder ExtParamInfos;
2928
Douglas Gregor9b146582009-07-08 20:55:45 +00002929 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002930 // explicitly-specified template arguments. If the function has a trailing
2931 // return type, substitute it after the arguments to ensure we substitute
2932 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002933 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002934 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002935 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002936 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002937 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002938 return TDK_SubstitutionFailure;
2939 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002940
Richard Smith5e580292012-02-10 09:58:53 +00002941 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002942 QualType ResultType;
2943 {
2944 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002945 // If a declaration declares a member function or member function
2946 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002947 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002948 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002949 // declarator.
2950 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002951 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2953 ThisContext = Method->getParent();
2954 ThisTypeQuals = Method->getTypeQualifiers();
2955 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002956
Douglas Gregor3024f072012-04-16 07:05:22 +00002957 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002958 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002959
2960 ResultType =
2961 SubstType(Proto->getReturnType(),
2962 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2963 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002964 if (ResultType.isNull() || Trap.hasErrorOccurred())
2965 return TDK_SubstitutionFailure;
2966 }
John McCallc8e321d2016-03-01 02:09:25 +00002967
Richard Smith5e580292012-02-10 09:58:53 +00002968 // Instantiate the types of each of the function parameters given the
2969 // explicitly-specified template arguments if we didn't do so earlier.
2970 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002971 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002972 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002973 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002974 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002975 return TDK_SubstitutionFailure;
2976
Douglas Gregor9b146582009-07-08 20:55:45 +00002977 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002978 auto EPI = Proto->getExtProtoInfo();
2979 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Richard Smithcd198152017-06-07 21:46:22 +00002980
2981 // In C++1z onwards, exception specifications are part of the function type,
2982 // so substitution into the type must also substitute into the exception
2983 // specification.
2984 SmallVector<QualType, 4> ExceptionStorage;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002985 if (getLangOpts().CPlusPlus17 &&
Richard Smithcd198152017-06-07 21:46:22 +00002986 SubstExceptionSpec(
2987 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
2988 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
2989 return TDK_SubstitutionFailure;
2990
Jordan Rose5c382722013-03-08 21:51:21 +00002991 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002992 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002993 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002994 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002995 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2996 return TDK_SubstitutionFailure;
2997 }
Mike Stump11289f42009-09-09 15:08:12 +00002998
Douglas Gregor9b146582009-07-08 20:55:45 +00002999 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003000 // Trailing template arguments that can be deduced (14.8.2) may be
3001 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00003002 // template arguments can be deduced, they may all be omitted; in this
3003 // case, the empty template argument list <> itself may also be omitted.
3004 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003005 // Take all of the explicitly-specified arguments and put them into
3006 // the set of deduced template arguments. Explicitly-specified
3007 // parameter packs, however, will be set to NULL since the deduction
3008 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00003009 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003010 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3011 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
3012 if (Arg.getKind() == TemplateArgument::Pack)
3013 Deduced.push_back(DeducedTemplateArgument());
3014 else
3015 Deduced.push_back(Arg);
3016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
Douglas Gregor9b146582009-07-08 20:55:45 +00003018 return TDK_Success;
3019}
3020
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003021/// Check whether the deduced argument type for a call to a function
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003022/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Richard Smithb1efc9b2017-08-30 00:44:08 +00003023static Sema::TemplateDeductionResult
3024CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3025 Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003026 QualType DeducedA) {
3027 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003028
Richard Smithb1efc9b2017-08-30 00:44:08 +00003029 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3030 Info.FirstArg = TemplateArgument(DeducedA);
3031 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3032 Info.CallArgIndex = OriginalArg.ArgIdx;
3033 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3034 : Sema::TDK_DeducedMismatch;
3035 };
3036
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003037 QualType A = OriginalArg.OriginalArgType;
3038 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003039
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003040 // Check for type equality (top-level cv-qualifiers are ignored).
3041 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003042 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003043
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003044 // Strip off references on the argument types; they aren't needed for
3045 // the following checks.
3046 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3047 DeducedA = DeducedARef->getPointeeType();
3048 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3049 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003050
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003051 // C++ [temp.deduct.call]p4:
3052 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003053 // - If the original P is a reference type, the deduced A (i.e., the
3054 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003055 // the transformed A.
3056 if (const ReferenceType *OriginalParamRef
3057 = OriginalParamType->getAs<ReferenceType>()) {
3058 // We don't want to keep the reference around any more.
3059 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003060
Richard Smith1be59c52016-10-22 01:32:19 +00003061 // FIXME: Resolve core issue (no number yet): if the original P is a
3062 // reference type and the transformed A is function type "noexcept F",
3063 // the deduced A can be F.
3064 QualType Tmp;
3065 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003066 return Sema::TDK_Success;
Richard Smith1be59c52016-10-22 01:32:19 +00003067
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003068 Qualifiers AQuals = A.getQualifiers();
3069 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00003070
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003071 // Under Objective-C++ ARC, the deduced type may have implicitly
3072 // been given strong or (when dealing with a const reference)
3073 // unsafe_unretained lifetime. If so, update the original
3074 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00003075 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003076 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3077 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3078 (DeducedAQuals.hasConst() &&
3079 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3080 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00003081 }
3082
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003083 if (AQuals == DeducedAQuals) {
3084 // Qualifiers match; there's nothing to do.
3085 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00003086 return Failed();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003087 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003088 // Qualifiers are compatible, so have the argument type adopt the
3089 // deduced argument type's qualifiers as if we had performed the
3090 // qualification conversion.
3091 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3092 }
3093 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003094
3095 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00003096 // type that can be converted to the deduced A via a function pointer
3097 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00003098 //
Richard Smith1be59c52016-10-22 01:32:19 +00003099 // Also allow conversions which merely strip __attribute__((noreturn)) from
3100 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003101 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00003102 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003103 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00003104 (S.IsQualificationConversion(A, DeducedA, false,
3105 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00003106 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003107 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003108
Simon Pilgrim728134c2016-08-12 11:43:57 +00003109 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003110 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003111 // [...] Likewise, if P is a pointer to a class of the form
3112 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003113 // derived class pointed to by the deduced A.
3114 if (const PointerType *OriginalParamPtr
3115 = OriginalParamType->getAs<PointerType>()) {
3116 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3117 if (const PointerType *APtr = A->getAs<PointerType>()) {
3118 if (A->getPointeeType()->isRecordType()) {
3119 OriginalParamType = OriginalParamPtr->getPointeeType();
3120 DeducedA = DeducedAPtr->getPointeeType();
3121 A = APtr->getPointeeType();
3122 }
3123 }
3124 }
3125 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003126
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003127 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003128 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003129
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003130 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith148bc6a2018-02-20 23:47:12 +00003131 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003132 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003133
Richard Smithb1efc9b2017-08-30 00:44:08 +00003134 return Failed();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003135}
3136
Richard Smithc92d2062017-01-05 23:02:44 +00003137/// Find the pack index for a particular parameter index in an instantiation of
3138/// a function template with specific arguments.
3139///
3140/// \return The pack index for whichever pack produced this parameter, or -1
3141/// if this was not produced by a parameter. Intended to be used as the
3142/// ArgumentPackSubstitutionIndex for further substitutions.
3143// FIXME: We should track this in OriginalCallArgs so we don't need to
3144// reconstruct it here.
3145static unsigned getPackIndexForParam(Sema &S,
3146 FunctionTemplateDecl *FunctionTemplate,
3147 const MultiLevelTemplateArgumentList &Args,
3148 unsigned ParamIdx) {
3149 unsigned Idx = 0;
3150 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3151 if (PD->isParameterPack()) {
3152 unsigned NumExpansions =
3153 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3154 if (Idx + NumExpansions > ParamIdx)
3155 return ParamIdx - Idx;
3156 Idx += NumExpansions;
3157 } else {
3158 if (Idx == ParamIdx)
3159 return -1; // Not a pack expansion
3160 ++Idx;
3161 }
3162 }
3163
3164 llvm_unreachable("parameter index would not be produced from template");
3165}
3166
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003167/// Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003168/// checking the deduced template arguments for completeness and forming
3169/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00003170///
3171/// \param OriginalCallArgs If non-NULL, the original call arguments against
3172/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00003173Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3174 FunctionTemplateDecl *FunctionTemplate,
3175 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3176 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3177 TemplateDeductionInfo &Info,
3178 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3179 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003180 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003181 EnterExpressionEvaluationContext Unevaluated(
3182 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003183 SFINAETrap Trap(*this);
3184
Douglas Gregor9b146582009-07-08 20:55:45 +00003185 // Enter a new template instantiation context while we instantiate the
3186 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003187 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003188 InstantiatingTemplate Inst(
3189 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3190 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003191 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003192 return TDK_InstantiationDepth;
3193
John McCalle23b8712010-04-29 01:18:58 +00003194 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003195
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003196 // C++ [temp.deduct.type]p2:
3197 // [...] or if any template argument remains neither deduced nor
3198 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003199 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003200 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003201 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003202 CurrentInstantiationScope, NumExplicitlySpecified,
3203 PartialOverloading))
3204 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003205
Richard Smith6eedfe72017-01-09 08:01:21 +00003206 // C++ [temp.deduct.call]p10: [DR1391]
3207 // If deduction succeeds for all parameters that contain
3208 // template-parameters that participate in template argument deduction,
3209 // and all template arguments are explicitly specified, deduced, or
3210 // obtained from default template arguments, remaining parameters are then
3211 // compared with the corresponding arguments. For each remaining parameter
3212 // P with a type that was non-dependent before substitution of any
3213 // explicitly-specified template arguments, if the corresponding argument
3214 // A cannot be implicitly converted to P, deduction fails.
3215 if (CheckNonDependent())
3216 return TDK_NonDependentConversionFailure;
3217
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003218 // Form the template argument list from the deduced template arguments.
3219 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003220 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003221 Info.reset(DeducedArgumentList);
3222
Mike Stump11289f42009-09-09 15:08:12 +00003223 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003224 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003225 DeclContext *Owner = FunctionTemplate->getDeclContext();
3226 if (FunctionTemplate->getFriendObjectKind())
3227 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003228 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003229 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003230 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003231 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003232 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003233
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003234 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003235 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
Mike Stump11289f42009-09-09 15:08:12 +00003237 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003238 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003239 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3240 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003241 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003242
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003243 // There may have been an error that did not prevent us from constructing a
3244 // declaration. Mark the declaration invalid and return with a substitution
3245 // failure.
3246 if (Trap.hasErrorOccurred()) {
3247 Specialization->setInvalidDecl(true);
3248 return TDK_SubstitutionFailure;
3249 }
3250
Douglas Gregore65aacb2011-06-16 16:50:48 +00003251 if (OriginalCallArgs) {
3252 // C++ [temp.deduct.call]p4:
3253 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003254 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003255 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003256 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003257 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3258 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003259
Richard Smithc92d2062017-01-05 23:02:44 +00003260 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003261 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003262 // FIXME: This presumably means a pack ended up smaller than we
3263 // expected while deducing. Should this not result in deduction
3264 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003265 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003266
Richard Smithc92d2062017-01-05 23:02:44 +00003267 QualType DeducedA;
3268 if (!OriginalArg.DecomposedParam) {
3269 // P is one of the function parameters, just look up its substituted
3270 // type.
3271 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3272 } else {
3273 // P is a decomposed element of a parameter corresponding to a
3274 // braced-init-list argument. Substitute back into P to find the
3275 // deduced A.
3276 QualType &CacheEntry =
3277 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3278 if (CacheEntry.isNull()) {
3279 ArgumentPackSubstitutionIndexRAII PackIndex(
3280 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3281 ParamIdx));
3282 CacheEntry =
3283 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3284 Specialization->getTypeSpecStartLoc(),
3285 Specialization->getDeclName());
3286 }
3287 DeducedA = CacheEntry;
3288 }
3289
Richard Smithb1efc9b2017-08-30 00:44:08 +00003290 if (auto TDK =
3291 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3292 return TDK;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003293 }
3294 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003295
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003296 // If we suppressed any diagnostics while performing template argument
3297 // deduction, and if we haven't already instantiated this declaration,
3298 // keep track of these diagnostics. They'll be emitted if this specialization
3299 // is actually used.
3300 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003301 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003302 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3303 if (Pos == SuppressedDiagnostics.end())
3304 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3305 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003307
Mike Stump11289f42009-09-09 15:08:12 +00003308 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003309}
3310
John McCall8d08b9b2010-08-27 09:08:28 +00003311/// Gets the type of a function for template-argument-deducton
3312/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003313static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003314 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003315 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003316 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003317 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003318 return {};
Richard Smith2a7d4812013-05-04 07:00:32 +00003319
John McCallc1f69982010-02-02 02:21:27 +00003320 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003321 if (Method->isInstance()) {
3322 // An instance method that's referenced in a form that doesn't
3323 // look like a member pointer is just invalid.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003324 if (!R.HasFormOfMemberPointer)
3325 return {};
John McCall8d08b9b2010-08-27 09:08:28 +00003326
Richard Smith2a7d4812013-05-04 07:00:32 +00003327 return S.Context.getMemberPointerType(Fn->getType(),
3328 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003329 }
3330
3331 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003332 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003333}
3334
3335/// Apply the deduction rules for overload sets.
3336///
3337/// \return the null type if this argument should be treated as an
3338/// undeduced context
3339static QualType
3340ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003341 Expr *Arg, QualType ParamType,
3342 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
John McCall8d08b9b2010-08-27 09:08:28 +00003344 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003345
John McCall8d08b9b2010-08-27 09:08:28 +00003346 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003347
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003348 // C++0x [temp.deduct.call]p4
3349 unsigned TDF = 0;
3350 if (ParamWasReference)
3351 TDF |= TDF_ParamWithReferenceType;
3352 if (R.IsAddressOfOperand)
3353 TDF |= TDF_IgnoreQualifiers;
3354
John McCallc1f69982010-02-02 02:21:27 +00003355 // C++0x [temp.deduct.call]p6:
3356 // When P is a function type, pointer to function type, or pointer
3357 // to member function type:
3358
3359 if (!ParamType->isFunctionType() &&
3360 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003361 !ParamType->isMemberFunctionPointerType()) {
3362 if (Ovl->hasExplicitTemplateArgs()) {
3363 // But we can still look for an explicit specialization.
3364 if (FunctionDecl *ExplicitSpec
3365 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003366 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003367 }
John McCallc1f69982010-02-02 02:21:27 +00003368
George Burgess IVcc2f3552016-03-19 21:51:45 +00003369 DeclAccessPair DAP;
3370 if (FunctionDecl *Viable =
3371 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3372 return GetTypeOfFunction(S, R, Viable);
3373
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003374 return {};
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003375 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003376
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003377 // Gather the explicit template arguments, if any.
3378 TemplateArgumentListInfo ExplicitTemplateArgs;
3379 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003380 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003381 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003382 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3383 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003384 NamedDecl *D = (*I)->getUnderlyingDecl();
3385
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003386 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3387 // - If the argument is an overload set containing one or more
3388 // function templates, the parameter is treated as a
3389 // non-deduced context.
3390 if (!Ovl->hasExplicitTemplateArgs())
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003391 return {};
Simon Pilgrim728134c2016-08-12 11:43:57 +00003392
3393 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003394 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003395 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003396 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3397 Specialization, Info))
3398 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003399
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003400 D = Specialization;
3401 }
John McCallc1f69982010-02-02 02:21:27 +00003402
3403 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003404 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003405 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003406
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003407 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003409 ArgType->isFunctionType())
3410 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
John McCallc1f69982010-02-02 02:21:27 +00003412 // - If the argument is an overload set (not containing function
3413 // templates), trial argument deduction is attempted using each
3414 // of the members of the set. If deduction succeeds for only one
3415 // of the overload set members, that member is used as the
3416 // argument value for the deduction. If deduction succeeds for
3417 // more than one member of the overload set the parameter is
3418 // treated as a non-deduced context.
3419
3420 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3421 // Type deduction is done independently for each P/A pair, and
3422 // the deduced template argument values are then combined.
3423 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003424 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003425 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003426 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003427 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003428 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3429 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003430 if (Result) continue;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003431 if (!Match.isNull())
3432 return {};
John McCallc1f69982010-02-02 02:21:27 +00003433 Match = ArgType;
3434 }
3435
3436 return Match;
3437}
3438
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003439/// Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003440/// described in C++ [temp.deduct.call].
3441///
3442/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003443/// argument deduction based on this P/A pair because the argument is an
3444/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003445static bool AdjustFunctionParmAndArgTypesForDeduction(
3446 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3447 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003448 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003449 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003450 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003451 if (ParamType.hasQualifiers())
3452 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003453
3454 // [...] If P is a reference type, the type referred to by P is
3455 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003456 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003457 if (ParamRefType)
3458 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003459
Nathan Sidwell96090022015-01-16 15:20:14 +00003460 // Overload sets usually make this parameter an undeduced context,
3461 // but there are sometimes special circumstances. Typically
3462 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003463 if (ArgType == S.Context.OverloadTy) {
3464 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3465 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003466 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003467 if (ArgType.isNull())
3468 return true;
3469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470
Douglas Gregor7825bf32011-01-06 22:09:01 +00003471 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003472 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003473 if (ArgType->isIncompleteArrayType()) {
3474 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003475 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003476 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003477
Richard Smith32918772017-02-14 00:25:28 +00003478 // C++1z [temp.deduct.call]p3:
3479 // If P is a forwarding reference and the argument is an lvalue, the type
3480 // "lvalue reference to A" is used in place of A for type deduction.
3481 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003482 Arg->isLValue())
3483 ArgType = S.Context.getLValueReferenceType(ArgType);
3484 } else {
3485 // C++ [temp.deduct.call]p2:
3486 // If P is not a reference type:
3487 // - If A is an array type, the pointer type produced by the
3488 // array-to-pointer standard conversion (4.2) is used in place of
3489 // A for type deduction; otherwise,
3490 if (ArgType->isArrayType())
3491 ArgType = S.Context.getArrayDecayedType(ArgType);
3492 // - If A is a function type, the pointer type produced by the
3493 // function-to-pointer standard conversion (4.3) is used in place
3494 // of A for type deduction; otherwise,
3495 else if (ArgType->isFunctionType())
3496 ArgType = S.Context.getPointerType(ArgType);
3497 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003498 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003499 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003500 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003501 }
3502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Douglas Gregor7825bf32011-01-06 22:09:01 +00003504 // C++0x [temp.deduct.call]p4:
3505 // In general, the deduction process attempts to find template argument
3506 // values that will make the deduced A identical to A (after the type A
3507 // is transformed as described above). [...]
3508 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509
Douglas Gregor7825bf32011-01-06 22:09:01 +00003510 // - If the original P is a reference type, the deduced A (i.e., the
3511 // type referred to by the reference) can be more cv-qualified than
3512 // the transformed A.
3513 if (ParamRefType)
3514 TDF |= TDF_ParamWithReferenceType;
3515 // - The transformed A can be another pointer or pointer to member
3516 // type that can be converted to the deduced A via a qualification
3517 // conversion (4.4).
3518 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3519 ArgType->isObjCObjectPointerType())
3520 TDF |= TDF_IgnoreQualifiers;
3521 // - If P is a class and P has the form simple-template-id, then the
3522 // transformed A can be a derived class of the deduced A. Likewise,
3523 // if P is a pointer to a class of the form simple-template-id, the
3524 // transformed A can be a pointer to a derived class pointed to by
3525 // the deduced A.
3526 if (isSimpleTemplateIdType(ParamType) ||
3527 (isa<PointerType>(ParamType) &&
3528 isSimpleTemplateIdType(
3529 ParamType->getAs<PointerType>()->getPointeeType())))
3530 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregor7825bf32011-01-06 22:09:01 +00003532 return false;
3533}
3534
Richard Smithf0393bf2017-02-16 04:22:56 +00003535static bool
3536hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3537 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003538
Richard Smith707eab62017-01-05 04:08:31 +00003539static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003540 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3541 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003542 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3543 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003544 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003546/// Attempt template argument deduction from an initializer list
Hubert Tong3280b332015-06-25 00:25:49 +00003547/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003548static Sema::TemplateDeductionResult DeduceFromInitializerList(
3549 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3550 InitListExpr *ILE, TemplateDeductionInfo &Info,
3551 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003552 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3553 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003554 // C++ [temp.deduct.call]p1: (CWG 1591)
3555 // If removing references and cv-qualifiers from P gives
3556 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3557 // a non-empty initializer list, then deduction is performed instead for
3558 // each element of the initializer list, taking P0 as a function template
3559 // parameter type and the initializer element as its argument
3560 //
Richard Smith707eab62017-01-05 04:08:31 +00003561 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003562 if (!ILE->getNumInits())
3563 return Sema::TDK_Success;
3564
Richard Smitha7d5ec92017-01-04 19:47:19 +00003565 QualType ElTy;
3566 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3567 if (ArrTy)
3568 ElTy = ArrTy->getElementType();
3569 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3570 // Otherwise, an initializer list argument causes the parameter to be
3571 // considered a non-deduced context
3572 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003573 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003574
Faisal Valif6dfdb32015-12-10 05:36:39 +00003575 // Deduction only needs to be done for dependent types.
3576 if (ElTy->isDependentType()) {
3577 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003578 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003579 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003580 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003581 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003582 }
3583 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003584
3585 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3586 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003587 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003588 // Determine the array bound is something we can deduce.
3589 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003590 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003591 // We can perform template argument deduction for the given non-type
3592 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003593 // C++ [temp.deduct.type]p13:
3594 // The type of N in the type T[N] is std::size_t.
3595 QualType T = S.Context.getSizeType();
3596 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003597 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003598 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003599 /*ArrayBound=*/true, Info, Deduced))
3600 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003601 }
3602 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003603
3604 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003605}
3606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003607/// Perform template argument deduction per [temp.deduct.call] for a
Richard Smith707eab62017-01-05 04:08:31 +00003608/// single parameter / argument pair.
3609static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003610 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3611 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003612 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3613 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003614 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003615 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003616 QualType OrigParamType = ParamType;
3617
3618 // If P is a reference type [...]
3619 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003620 if (AdjustFunctionParmAndArgTypesForDeduction(
3621 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003622 return Sema::TDK_Success;
3623
Richard Smith707eab62017-01-05 04:08:31 +00003624 // If [...] the argument is a non-empty initializer list [...]
3625 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3626 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003627 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003628
3629 // [...] the deduction process attempts to find template argument values
3630 // that will make the deduced A identical to A
3631 //
3632 // Keep track of the argument type and corresponding parameter index,
3633 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003634 OriginalCallArgs.push_back(
3635 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003636 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003637 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003638}
3639
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003640/// Perform template argument deduction from a function call
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003641/// (C++ [temp.deduct.call]).
3642///
3643/// \param FunctionTemplate the function template for which we are performing
3644/// template argument deduction.
3645///
James Dennett18348b62012-06-22 08:52:37 +00003646/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003647/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003648///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003649/// \param Args the function call arguments
3650///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003651/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003652/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003653/// template argument deduction.
3654///
3655/// \param Info the argument will be updated to provide additional information
3656/// about template argument deduction.
3657///
Richard Smith6eedfe72017-01-09 08:01:21 +00003658/// \param CheckNonDependent A callback to invoke to check conversions for
3659/// non-dependent parameters, between deduction and substitution, per DR1391.
3660/// If this returns true, substitution will be skipped and we return
3661/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3662/// types (after substituting explicit template arguments).
3663///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003664/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003665Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3666 FunctionTemplateDecl *FunctionTemplate,
3667 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003668 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003669 bool PartialOverloading,
3670 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003671 if (FunctionTemplate->isInvalidDecl())
3672 return TDK_Invalid;
3673
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003674 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003675 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003676
Richard Smith32918772017-02-14 00:25:28 +00003677 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3678
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003679 // C++ [temp.deduct.call]p1:
3680 // Template argument deduction is done by comparing each function template
3681 // parameter type (call it P) with the type of the corresponding argument
3682 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003683 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003684 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003685 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003686 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003687 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003688 if (Proto->isTemplateVariadic())
3689 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003690 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003691 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693
Douglas Gregor89026b52009-06-30 23:57:56 +00003694 // The types of the parameters from which we will perform template argument
3695 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003696 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003697 TemplateParameterList *TemplateParams
3698 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003699 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003700 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003701 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003702 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003703 TemplateDeductionResult Result =
3704 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003705 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003706 Deduced,
3707 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003708 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003709 Info);
3710 if (Result)
3711 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003712
3713 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003714 } else {
3715 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003716 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003717 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3718 }
Mike Stump11289f42009-09-09 15:08:12 +00003719
Richard Smith6eedfe72017-01-09 08:01:21 +00003720 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003721
3722 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3723 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003724 // C++ [demp.deduct.call]p1: (DR1391)
3725 // Template argument deduction is done by comparing each function template
3726 // parameter that contains template-parameters that participate in
3727 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003728 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003729 return Sema::TDK_Success;
3730
Richard Smith707eab62017-01-05 04:08:31 +00003731 // ... with the type of the corresponding argument
3732 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003733 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003734 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003735 };
3736
Douglas Gregor89026b52009-06-30 23:57:56 +00003737 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003738 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003739 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003740 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003741 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003742 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003743
Richard Smitha7d5ec92017-01-04 19:47:19 +00003744 const PackExpansionType *ParamExpansion =
3745 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003746 if (!ParamExpansion) {
3747 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003748 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003749 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Richard Smith6eedfe72017-01-09 08:01:21 +00003751 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003752 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003753 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003754
Douglas Gregor7825bf32011-01-06 22:09:01 +00003755 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003756 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757
Richard Smithde0d34a2017-01-09 07:14:40 +00003758 QualType ParamPattern = ParamExpansion->getPattern();
3759 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3760 ParamPattern);
3761
Douglas Gregor7825bf32011-01-06 22:09:01 +00003762 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 // For a function parameter pack that occurs at the end of the
3764 // parameter-declaration-list, the type A of each remaining argument of
3765 // the call is compared with the type P of the declarator-id of the
3766 // function parameter pack. Each comparison deduces template arguments
3767 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003768 // the function parameter pack. When a function parameter pack appears
3769 // in a non-deduced context [not at the end of the list], the type of
3770 // that parameter pack is never deduced.
3771 //
3772 // FIXME: The above rule allows the size of the parameter pack to change
3773 // after we skip it (in the non-deduced case). That makes no sense, so
3774 // we instead notionally deduce the pack against N arguments, where N is
3775 // the length of the explicitly-specified pack if it's expanded by the
3776 // parameter pack and 0 otherwise, and we treat each deduction as a
3777 // non-deduced context.
3778 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003779 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3780 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003781 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3782 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003783 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003784 } else {
3785 // If the parameter type contains an explicitly-specified pack that we
3786 // could not expand, skip the number of parameters notionally created
3787 // by the expansion.
3788 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003789 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003790 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003791 ++I, ++ArgIdx) {
3792 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003793 // FIXME: Should we add OriginalCallArgs for these? What if the
3794 // corresponding argument is a list?
3795 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003796 }
3797 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799
Douglas Gregor7825bf32011-01-06 22:09:01 +00003800 // Build argument packs for each of the parameter packs expanded by this
3801 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003802 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003804 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003805
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003806 // Capture the context in which the function call is made. This is the context
3807 // that is needed when the accessibility of template arguments is checked.
3808 DeclContext *CallingCtx = CurContext;
3809
Richard Smith6eedfe72017-01-09 08:01:21 +00003810 return FinishTemplateArgumentDeduction(
3811 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003812 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3813 ContextRAII SavedContext(*this, CallingCtx);
3814 return CheckNonDependent(ParamTypesForArgChecking);
3815 });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003816}
3817
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003818QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003819 QualType FunctionType,
3820 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003821 if (ArgFunctionType.isNull())
3822 return ArgFunctionType;
3823
3824 const FunctionProtoType *FunctionTypeP =
3825 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003826 const FunctionProtoType *ArgFunctionTypeP =
3827 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003828
3829 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3830 bool Rebuild = false;
3831
3832 CallingConv CC = FunctionTypeP->getCallConv();
3833 if (EPI.ExtInfo.getCC() != CC) {
3834 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3835 Rebuild = true;
3836 }
3837
3838 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3839 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3840 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3841 Rebuild = true;
3842 }
3843
3844 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3845 ArgFunctionTypeP->hasExceptionSpec())) {
3846 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3847 Rebuild = true;
3848 }
3849
3850 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003851 return ArgFunctionType;
3852
Richard Smithbaa47832016-12-01 02:11:49 +00003853 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3854 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003855}
3856
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003857/// Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003858/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3859/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003860///
3861/// \param FunctionTemplate the function template for which we are performing
3862/// template argument deduction.
3863///
James Dennett18348b62012-06-22 08:52:37 +00003864/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003865/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003866///
3867/// \param ArgFunctionType the function type that will be used as the
3868/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003869/// function template's function type. This type may be NULL, if there is no
3870/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003871///
3872/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003873/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003874/// template argument deduction.
3875///
3876/// \param Info the argument will be updated to provide additional information
3877/// about template argument deduction.
3878///
Richard Smithbaa47832016-12-01 02:11:49 +00003879/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3880/// the address of a function template per [temp.deduct.funcaddr] and
3881/// [over.over]. If \c false, we are looking up a function template
3882/// specialization based on its signature, per [temp.deduct.decl].
3883///
Douglas Gregor9b146582009-07-08 20:55:45 +00003884/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003885Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3886 FunctionTemplateDecl *FunctionTemplate,
3887 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3888 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3889 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003890 if (FunctionTemplate->isInvalidDecl())
3891 return TDK_Invalid;
3892
Douglas Gregor9b146582009-07-08 20:55:45 +00003893 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3894 TemplateParameterList *TemplateParams
3895 = FunctionTemplate->getTemplateParameters();
3896 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003897
Douglas Gregor9b146582009-07-08 20:55:45 +00003898 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003899 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003900 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003901 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003902 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003903 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003904 if (TemplateDeductionResult Result
3905 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003906 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003907 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003908 &FunctionType, Info))
3909 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003910
3911 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003912 }
3913
Richard Smithcd198152017-06-07 21:46:22 +00003914 // When taking the address of a function, we require convertibility of
3915 // the resulting function type. Otherwise, we allow arbitrary mismatches
3916 // of calling convention and noreturn.
3917 if (!IsAddressOfFunction)
3918 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3919 /*AdjustExceptionSpec*/false);
3920
Eli Friedman77dcc722012-02-08 03:07:05 +00003921 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003922 EnterExpressionEvaluationContext Unevaluated(
3923 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003924 SFINAETrap Trap(*this);
3925
John McCallc1f69982010-02-02 02:21:27 +00003926 Deduced.resize(TemplateParams->size());
3927
Richard Smith2a7d4812013-05-04 07:00:32 +00003928 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003929 // type so that we treat it as a non-deduced context in what follows. If we
3930 // are looking up by signature, the signature type should also have a deduced
3931 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003932 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003933 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003934 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003935 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003936 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003937 }
3938
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003939 if (!ArgFunctionType.isNull()) {
Richard Smithcd198152017-06-07 21:46:22 +00003940 unsigned TDF =
3941 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003942 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003943 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003944 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003945 FunctionType, ArgFunctionType,
3946 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003947 return Result;
3948 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003949
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003951 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3952 NumExplicitlySpecified,
3953 Specialization, Info))
3954 return Result;
3955
Richard Smith2a7d4812013-05-04 07:00:32 +00003956 // If the function has a deduced return type, deduce it now, so we can check
3957 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003958 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003959 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003960 DeduceReturnType(Specialization, Info.getLocation(), false))
3961 return TDK_MiscellaneousDeductionFailure;
3962
Richard Smith9095e5b2016-11-01 01:31:23 +00003963 // If the function has a dependent exception specification, resolve it now,
3964 // so we can check that the exception specification matches.
3965 auto *SpecializationFPT =
3966 Specialization->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003967 if (getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +00003968 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3969 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3970 return TDK_MiscellaneousDeductionFailure;
3971
Richard Smithcd198152017-06-07 21:46:22 +00003972 // Adjust the exception specification of the argument to match the
Richard Smithbaa47832016-12-01 02:11:49 +00003973 // substituted and resolved type we just formed. (Calling convention and
3974 // noreturn can't be dependent, so we don't actually need this for them
3975 // right now.)
3976 QualType SpecializationType = Specialization->getType();
3977 if (!IsAddressOfFunction)
3978 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3979 /*AdjustExceptionSpec*/true);
3980
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003981 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003982 // specialization with respect to arguments of compatible pointer to function
3983 // types, template argument deduction fails.
3984 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003985 if (IsAddressOfFunction &&
3986 !isSameOrCompatibleFunctionType(
3987 Context.getCanonicalType(SpecializationType),
3988 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003989 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003990
3991 if (!IsAddressOfFunction &&
3992 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003993 return TDK_MiscellaneousDeductionFailure;
3994 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003995
3996 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003997}
3998
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003999/// Deduce template arguments for a templated conversion
Douglas Gregor05155d82009-08-21 23:19:43 +00004000/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4001/// conversion function template specialization.
4002Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00004003Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00004004 QualType ToType,
4005 CXXConversionDecl *&Specialization,
4006 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00004007 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004008 return TDK_Invalid;
4009
Faisal Vali2b3a3012013-10-24 23:40:02 +00004010 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00004011 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4012
Faisal Vali2b3a3012013-10-24 23:40:02 +00004013 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00004014
4015 // Canonicalize the types for deduction.
4016 QualType P = Context.getCanonicalType(FromType);
4017 QualType A = Context.getCanonicalType(ToType);
4018
Douglas Gregord99609a2011-03-06 09:03:20 +00004019 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00004020 // If P is a reference type, the type referred to by P is used for
4021 // type deduction.
4022 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4023 P = PRef->getPointeeType();
4024
Douglas Gregord99609a2011-03-06 09:03:20 +00004025 // C++0x [temp.deduct.conv]p4:
4026 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00004027 // for type deduction.
4028 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00004029 A = ARef->getPointeeType().getUnqualifiedType();
4030 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00004031 //
Mike Stump11289f42009-09-09 15:08:12 +00004032 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00004033 else {
4034 assert(!A->isReferenceType() && "Reference types were handled above");
4035
4036 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00004037 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00004038 // of P for type deduction; otherwise,
4039 if (P->isArrayType())
4040 P = Context.getArrayDecayedType(P);
4041 // - If P is a function type, the pointer type produced by the
4042 // function-to-pointer standard conversion (4.3) is used in
4043 // place of P for type deduction; otherwise,
4044 else if (P->isFunctionType())
4045 P = Context.getPointerType(P);
4046 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004047 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004048 else
4049 P = P.getUnqualifiedType();
4050
Douglas Gregord99609a2011-03-06 09:03:20 +00004051 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004052 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00004053 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00004054 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004055 A = A.getUnqualifiedType();
4056 }
4057
Eli Friedman77dcc722012-02-08 03:07:05 +00004058 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004059 EnterExpressionEvaluationContext Unevaluated(
4060 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004061 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004062
4063 // C++ [temp.deduct.conv]p1:
4064 // Template argument deduction is done by comparing the return
4065 // type of the template conversion function (call it P) with the
4066 // type that is required as the result of the conversion (call it
4067 // A) as described in 14.8.2.4.
4068 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004069 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004070 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004071 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004072
4073 // C++0x [temp.deduct.conv]p4:
4074 // In general, the deduction process attempts to find template
4075 // argument values that will make the deduced A identical to
4076 // A. However, there are two cases that allow a difference:
4077 unsigned TDF = 0;
4078 // - If the original A is a reference type, A can be more
4079 // cv-qualified than the deduced A (i.e., the type referred to
4080 // by the reference)
4081 if (ToType->isReferenceType())
4082 TDF |= TDF_ParamWithReferenceType;
4083 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004084 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004085 // conversion.
4086 //
4087 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4088 // both P and A are pointers or member pointers. In this case, we
4089 // just ignore cv-qualifiers completely).
4090 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004091 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004092 TDF |= TDF_IgnoreQualifiers;
4093 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004094 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4095 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004096 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004097
4098 // Create an Instantiation Scope for finalizing the operator.
4099 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004100 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004101 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004102 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004103 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004104 ConversionSpecialized, Info);
4105 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
Douglas Gregor05155d82009-08-21 23:19:43 +00004106 return Result;
4107}
4108
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004109/// Deduce template arguments for a function template when there is
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004110/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4111///
4112/// \param FunctionTemplate the function template for which we are performing
4113/// template argument deduction.
4114///
James Dennett18348b62012-06-22 08:52:37 +00004115/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004116/// arguments.
4117///
4118/// \param Specialization if template argument deduction was successful,
4119/// this will be set to the function template specialization produced by
4120/// template argument deduction.
4121///
4122/// \param Info the argument will be updated to provide additional information
4123/// about template argument deduction.
4124///
Richard Smithbaa47832016-12-01 02:11:49 +00004125/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4126/// the address of a function template in a context where we do not have a
4127/// target type, per [over.over]. If \c false, we are looking up a function
4128/// template specialization based on its signature, which only happens when
4129/// deducing a function parameter type from an argument that is a template-id
4130/// naming a function template specialization.
4131///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004132/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004133Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4134 FunctionTemplateDecl *FunctionTemplate,
4135 TemplateArgumentListInfo *ExplicitTemplateArgs,
4136 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4137 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004138 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004139 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004140 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004141}
4142
Richard Smith30482bc2011-02-20 03:19:35 +00004143namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004144
Richard Smith60437622017-02-09 19:17:44 +00004145 /// Substitute the 'auto' specifier or deduced template specialization type
4146 /// specifier within a type for a given replacement type.
4147 class SubstituteDeducedTypeTransform :
4148 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004149 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004150 bool UseTypeSugar;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004151
Richard Smith30482bc2011-02-20 03:19:35 +00004152 public:
Richard Smith60437622017-02-09 19:17:44 +00004153 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4154 bool UseTypeSugar = true)
4155 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4156 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4157
4158 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4159 assert(isa<TemplateTypeParmType>(Replacement) &&
4160 "unexpected unsugared replacement kind");
4161 QualType Result = Replacement;
4162 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4163 NewTL.setNameLoc(TL.getNameLoc());
4164 return Result;
4165 }
Nico Weberc153d242014-07-28 00:02:09 +00004166
Richard Smith30482bc2011-02-20 03:19:35 +00004167 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4168 // If we're building the type pattern to deduce against, don't wrap the
4169 // substituted type in an AutoType. Certain template deduction rules
4170 // apply only when a template type parameter appears directly (and not if
4171 // the parameter is found through desugaring). For instance:
4172 // auto &&lref = lvalue;
4173 // must transform into "rvalue reference to T" not "rvalue reference to
4174 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004175 //
4176 // FIXME: Is this still necessary?
4177 if (!UseTypeSugar)
4178 return TransformDesugared(TLB, TL);
4179
4180 QualType Result = SemaRef.Context.getAutoType(
4181 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4182 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4183 NewTL.setNameLoc(TL.getNameLoc());
4184 return Result;
4185 }
4186
4187 QualType TransformDeducedTemplateSpecializationType(
4188 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4189 if (!UseTypeSugar)
4190 return TransformDesugared(TLB, TL);
4191
4192 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4193 TL.getTypePtr()->getTemplateName(),
4194 Replacement, Replacement.isNull());
4195 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4196 NewTL.setNameLoc(TL.getNameLoc());
4197 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004198 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004199
4200 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4201 // Lambdas never need to be transformed.
4202 return E;
4203 }
Richard Smith061f1e22013-04-30 21:23:01 +00004204
Richard Smith2a7d4812013-05-04 07:00:32 +00004205 QualType Apply(TypeLoc TL) {
4206 // Create some scratch storage for the transformed type locations.
4207 // FIXME: We're just going to throw this information away. Don't build it.
4208 TypeLocBuilder TLB;
4209 TLB.reserve(TL.getFullDataSize());
4210 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004211 }
Richard Smith30482bc2011-02-20 03:19:35 +00004212 };
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004213
4214} // namespace
Richard Smith30482bc2011-02-20 03:19:35 +00004215
Richard Smith2a7d4812013-05-04 07:00:32 +00004216Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004217Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4218 Optional<unsigned> DependentDeductionDepth) {
4219 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4220 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004221}
4222
Richard Smithb1efc9b2017-08-30 00:44:08 +00004223/// Attempt to produce an informative diagostic explaining why auto deduction
4224/// failed.
4225/// \return \c true if diagnosed, \c false if not.
4226static bool diagnoseAutoDeductionFailure(Sema &S,
4227 Sema::TemplateDeductionResult TDK,
4228 TemplateDeductionInfo &Info,
4229 ArrayRef<SourceRange> Ranges) {
4230 switch (TDK) {
4231 case Sema::TDK_Inconsistent: {
4232 // Inconsistent deduction means we were deducing from an initializer list.
4233 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4234 D << Info.FirstArg << Info.SecondArg;
4235 for (auto R : Ranges)
4236 D << R;
4237 return true;
4238 }
4239
4240 // FIXME: Are there other cases for which a custom diagnostic is more useful
4241 // than the basic "types don't match" diagnostic?
4242
4243 default:
4244 return false;
4245 }
4246}
4247
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004248/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004249///
Richard Smith87d263e2016-12-25 08:05:23 +00004250/// Note that this is done even if the initializer is dependent. (This is
4251/// necessary to support partial ordering of templates using 'auto'.)
4252/// A dependent type will be produced when deducing from a dependent type.
4253///
Richard Smith30482bc2011-02-20 03:19:35 +00004254/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004255/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004256/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004257/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004258/// \param DependentDeductionDepth Set if we should permit deduction in
4259/// dependent cases. This is necessary for template partial ordering with
4260/// 'auto' template parameters. The value specified is the template
4261/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004262Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004263Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4264 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004265 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004266 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4267 if (NonPlaceholder.isInvalid())
4268 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004269 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004270 }
4271
Richard Smith87d263e2016-12-25 08:05:23 +00004272 if (!DependentDeductionDepth &&
4273 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004274 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004275 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004276 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004277 }
4278
Richard Smith87d263e2016-12-25 08:05:23 +00004279 // Find the depth of template parameter to synthesize.
4280 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4281
Richard Smith74aeef52013-04-26 16:15:35 +00004282 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4283 // Since 'decltype(auto)' can only occur at the top of the type, we
4284 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004285 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004286 if (AT->isDecltypeAuto()) {
4287 if (isa<InitListExpr>(Init)) {
4288 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4289 return DAR_FailedAlreadyDiagnosed;
4290 }
4291
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004292 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004293 if (Deduced.isNull())
4294 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004295 // FIXME: Support a non-canonical deduced type for 'auto'.
4296 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004297 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004298 if (Result.isNull())
4299 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004300 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004301 } else if (!getLangOpts().CPlusPlus) {
4302 if (isa<InitListExpr>(Init)) {
4303 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4304 return DAR_FailedAlreadyDiagnosed;
4305 }
Richard Smith74aeef52013-04-26 16:15:35 +00004306 }
4307 }
4308
Richard Smith30482bc2011-02-20 03:19:35 +00004309 SourceLocation Loc = Init->getExprLoc();
4310
4311 LocalInstantiationScope InstScope(*this);
4312
4313 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004314 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4315 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004316 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4317 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004318 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4319 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004320
Richard Smith87d263e2016-12-25 08:05:23 +00004321 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004322 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004323 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004324 assert(!FuncParam.isNull() &&
4325 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004326
4327 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004328 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004329 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004330
Richard Smith87d263e2016-12-25 08:05:23 +00004331 TemplateDeductionInfo Info(Loc, Depth);
4332
4333 // If deduction failed, don't diagnose if the initializer is dependent; it
4334 // might acquire a matching type in the instantiation.
Richard Smithb1efc9b2017-08-30 00:44:08 +00004335 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4336 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
Richard Smith87d263e2016-12-25 08:05:23 +00004337 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004338 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004339 assert(!Result.isNull() && "substituting DependentTy can't fail");
4340 return DAR_Succeeded;
4341 }
Richard Smithb1efc9b2017-08-30 00:44:08 +00004342 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4343 return DAR_FailedAlreadyDiagnosed;
Richard Smith87d263e2016-12-25 08:05:23 +00004344 return DAR_Failed;
4345 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004346
Richard Smith707eab62017-01-05 04:08:31 +00004347 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4348
Richard Smith74801c82012-07-08 04:13:07 +00004349 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004350 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004351 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4352 // against that. Such deduction only succeeds if removing cv-qualifiers and
4353 // references results in std::initializer_list<T>.
4354 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4355 return DAR_Failed;
4356
Richard Smithb1efc9b2017-08-30 00:44:08 +00004357 SourceRange DeducedFromInitRange;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004358 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00004359 Expr *Init = InitList->getInit(i);
4360
4361 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4362 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
Richard Smithc92d2062017-01-05 23:02:44 +00004363 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4364 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004365 return DeductionFailed(TDK, {DeducedFromInitRange,
4366 Init->getSourceRange()});
4367
4368 if (DeducedFromInitRange.isInvalid() &&
4369 Deduced[0].getKind() != TemplateArgument::Null)
4370 DeducedFromInitRange = Init->getSourceRange();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004371 }
4372 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004373 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4374 Diag(Loc, diag::err_auto_bitfield);
4375 return DAR_FailedAlreadyDiagnosed;
4376 }
4377
Richard Smithb1efc9b2017-08-30 00:44:08 +00004378 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004379 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004380 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004381 return DeductionFailed(TDK, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004382 }
Richard Smith30482bc2011-02-20 03:19:35 +00004383
Richard Smith87d263e2016-12-25 08:05:23 +00004384 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004385 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smithb1efc9b2017-08-30 00:44:08 +00004386 return DeductionFailed(TDK_Incomplete, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004387
Eli Friedmane4310952012-11-06 23:56:42 +00004388 QualType DeducedType = Deduced[0].getAsType();
4389
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004390 if (InitList) {
4391 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4392 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004393 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004394 }
4395
Richard Smith60437622017-02-09 19:17:44 +00004396 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004397 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004398 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004399
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004400 // Check that the deduced argument type is compatible with the original
4401 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004402 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004403 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004404 assert((bool)InitList == OriginalArg.DecomposedParam &&
4405 "decomposed non-init-list in auto deduction?");
Richard Smithb1efc9b2017-08-30 00:44:08 +00004406 if (auto TDK =
4407 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004408 Result = QualType();
Richard Smithb1efc9b2017-08-30 00:44:08 +00004409 return DeductionFailed(TDK, {});
Richard Smith707eab62017-01-05 04:08:31 +00004410 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004411 }
4412
Sebastian Redl09edce02012-01-23 22:09:39 +00004413 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004414}
4415
Simon Pilgrim728134c2016-08-12 11:43:57 +00004416QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004417 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004418 if (TypeToReplaceAuto->isDependentType())
4419 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004420 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004421 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004422}
4423
Richard Smith60437622017-02-09 19:17:44 +00004424TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4425 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004426 if (TypeToReplaceAuto->isDependentType())
4427 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004428 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004429 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004430}
4431
Richard Smith33c33c32017-02-04 01:28:01 +00004432QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4433 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004434 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4435 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004436 .TransformType(TypeWithAuto);
4437}
4438
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004439void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4440 if (isa<InitListExpr>(Init))
4441 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004442 VDecl->isInitCapture()
4443 ? diag::err_init_capture_deduction_failure_from_init_list
4444 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004445 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4446 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004447 Diag(VDecl->getLocation(),
4448 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4449 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004450 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4451 << Init->getSourceRange();
4452}
4453
Richard Smith2a7d4812013-05-04 07:00:32 +00004454bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4455 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004456 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004457
Richard Smith50e291e2018-01-02 23:52:42 +00004458 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4459 // within the return type from the call operator's type.
4460 if (isLambdaConversionOperator(FD)) {
4461 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4462 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4463
4464 // For a generic lambda, instantiate the call operator if needed.
4465 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4466 CallOp = InstantiateFunctionDeclaration(
4467 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4468 if (!CallOp || CallOp->isInvalidDecl())
4469 return true;
4470
4471 // We might need to deduce the return type by instantiating the definition
4472 // of the operator() function.
4473 if (CallOp->getReturnType()->isUndeducedType())
4474 InstantiateFunctionDefinition(Loc, CallOp);
4475 }
4476
4477 if (CallOp->isInvalidDecl())
4478 return true;
4479 assert(!CallOp->getReturnType()->isUndeducedType() &&
4480 "failed to deduce lambda return type");
4481
4482 // Build the new return type from scratch.
4483 QualType RetType = getLambdaConversionFunctionResultType(
4484 CallOp->getType()->castAs<FunctionProtoType>());
4485 if (FD->getReturnType()->getAs<PointerType>())
4486 RetType = Context.getPointerType(RetType);
4487 else {
4488 assert(FD->getReturnType()->getAs<BlockPointerType>());
4489 RetType = Context.getBlockPointerType(RetType);
4490 }
4491 Context.adjustDeducedFunctionResultType(FD, RetType);
4492 return false;
4493 }
4494
Richard Smith2a7d4812013-05-04 07:00:32 +00004495 if (FD->getTemplateInstantiationPattern())
4496 InstantiateFunctionDefinition(Loc, FD);
4497
Alp Toker314cc812014-01-25 16:55:45 +00004498 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004499 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4500 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4501 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4502 }
4503
4504 return StillUndeduced;
4505}
4506
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004507/// If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004508static void
4509AddImplicitObjectParameterType(ASTContext &Context,
4510 CXXMethodDecl *Method,
4511 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004512 // C++11 [temp.func.order]p3:
4513 // [...] The new parameter is of type "reference to cv A," where cv are
4514 // the cv-qualifiers of the function template (if any) and A is
4515 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004516 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004517 // The standard doesn't say explicitly, but we pick the appropriate kind of
4518 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004519 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4520 ArgTy = Context.getQualifiedType(ArgTy,
4521 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004522 if (Method->getRefQualifier() == RQ_RValue)
4523 ArgTy = Context.getRValueReferenceType(ArgTy);
4524 else
4525 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004526 ArgTypes.push_back(ArgTy);
4527}
4528
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004529/// Determine whether the function template \p FT1 is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004530/// specialized as \p FT2.
4531static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004532 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004533 FunctionTemplateDecl *FT1,
4534 FunctionTemplateDecl *FT2,
4535 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004536 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004537 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004539 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4540 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004542 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4543 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004544 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004545 Deduced.resize(TemplateParams->size());
4546
4547 // C++0x [temp.deduct.partial]p3:
4548 // The types used to determine the ordering depend on the context in which
4549 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004550 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004551 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004552 switch (TPOC) {
4553 case TPOC_Call: {
4554 // - In the context of a function call, the function parameter types are
4555 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004556 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4557 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004558
Eli Friedman3b5774a2012-09-19 23:27:04 +00004559 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004560 // [...] If only one of the function templates is a non-static
4561 // member, that function template is considered to have a new
4562 // first parameter inserted in its function parameter list. The
4563 // new parameter is of type "reference to cv A," where cv are
4564 // the cv-qualifiers of the function template (if any) and A is
4565 // the class of which the function template is a member.
4566 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004567 // Note that we interpret this to mean "if one of the function
4568 // templates is a non-static member and the other is a non-member";
4569 // otherwise, the ordering rules for static functions against non-static
4570 // functions don't make any sense.
4571 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004572 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4573 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004574 SmallVector<QualType, 4> Args1;
4575
Richard Smithe5b52202013-09-11 00:52:39 +00004576 unsigned NumComparedArguments = NumCallArguments1;
4577
4578 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004579 // Compare 'this' from Method1 against first parameter from Method2.
4580 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4581 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004582 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004583 // Compare 'this' from Method2 against first parameter from Method1.
4584 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004585 }
4586
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004587 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004588 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004589 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004590 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
Douglas Gregorb837ea42011-01-11 17:34:58 +00004592 // C++ [temp.func.order]p5:
4593 // The presence of unused ellipsis and default arguments has no effect on
4594 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004595 if (Args1.size() > NumComparedArguments)
4596 Args1.resize(NumComparedArguments);
4597 if (Args2.size() > NumComparedArguments)
4598 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004599 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4600 Args1.data(), Args1.size(), Info, Deduced,
4601 TDF_None, /*PartialOrdering=*/true))
4602 return false;
4603
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004604 break;
4605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004607 case TPOC_Conversion:
4608 // - In the context of a call to a conversion operator, the return types
4609 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004610 if (DeduceTemplateArgumentsByTypeMatch(
4611 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4612 Info, Deduced, TDF_None,
4613 /*PartialOrdering=*/true))
4614 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004617 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004618 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004619 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004620 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4621 FD2->getType(), FD1->getType(),
4622 Info, Deduced, TDF_None,
4623 /*PartialOrdering=*/true))
4624 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004625 break;
4626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004628 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629 // In most cases, all template parameters must have values in order for
4630 // deduction to succeed, but for partial ordering purposes a template
4631 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004632 // types being used for partial ordering. [ Note: a template parameter used
4633 // in a non-deduced context is considered used. -end note]
4634 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4635 for (; ArgIdx != NumArgs; ++ArgIdx)
4636 if (Deduced[ArgIdx].isNull())
4637 break;
4638
Richard Smithf0393bf2017-02-16 04:22:56 +00004639 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4640 // to substitute the deduced arguments back into the template and check that
4641 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004642
Richard Smithf0393bf2017-02-16 04:22:56 +00004643 if (ArgIdx == NumArgs) {
4644 // All template arguments were deduced. FT1 is at least as specialized
4645 // as FT2.
4646 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004647 }
4648
Richard Smithf0393bf2017-02-16 04:22:56 +00004649 // Figure out which template parameters were used.
4650 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4651 switch (TPOC) {
4652 case TPOC_Call:
4653 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4654 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4655 TemplateParams->getDepth(),
4656 UsedParameters);
4657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Richard Smithf0393bf2017-02-16 04:22:56 +00004659 case TPOC_Conversion:
4660 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4661 TemplateParams->getDepth(), UsedParameters);
4662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663
Richard Smithf0393bf2017-02-16 04:22:56 +00004664 case TPOC_Other:
4665 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4666 TemplateParams->getDepth(),
4667 UsedParameters);
4668 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004669 }
4670
Richard Smithf0393bf2017-02-16 04:22:56 +00004671 for (; ArgIdx != NumArgs; ++ArgIdx)
4672 // If this argument had no value deduced but was used in one of the types
4673 // used for partial ordering, then deduction fails.
4674 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4675 return false;
4676
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004677 return true;
4678}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004680/// Determine whether this a function template whose parameter-type-list
Douglas Gregorcef1a032011-01-16 16:03:23 +00004681/// ends with a function parameter pack.
4682static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4683 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4684 unsigned NumParams = Function->getNumParams();
4685 if (NumParams == 0)
4686 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687
Douglas Gregorcef1a032011-01-16 16:03:23 +00004688 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4689 if (!Last->isParameterPack())
4690 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregorcef1a032011-01-16 16:03:23 +00004692 // Make sure that no previous parameter is a parameter pack.
4693 while (--NumParams > 0) {
4694 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4695 return false;
4696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697
Douglas Gregorcef1a032011-01-16 16:03:23 +00004698 return true;
4699}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004701/// Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004702/// to the rules of function template partial ordering (C++ [temp.func.order]).
4703///
4704/// \param FT1 the first function template
4705///
4706/// \param FT2 the second function template
4707///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004708/// \param TPOC the context in which we are performing partial ordering of
4709/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004710///
Richard Smithe5b52202013-09-11 00:52:39 +00004711/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4712/// only when \c TPOC is \c TPOC_Call.
4713///
4714/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4715/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004716///
Douglas Gregorbe999392009-09-15 16:23:51 +00004717/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004718/// template is more specialized, returns NULL.
4719FunctionTemplateDecl *
4720Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4721 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004722 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004723 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004724 unsigned NumCallArguments1,
4725 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004726 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004727 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004729 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004731 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004732 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004734 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004735 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004736
Douglas Gregorcef1a032011-01-16 16:03:23 +00004737 // FIXME: This mimics what GCC implements, but doesn't match up with the
4738 // proposed resolution for core issue 692. This area needs to be sorted out,
4739 // but for now we attempt to maintain compatibility.
4740 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4741 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4742 if (Variadic1 != Variadic2)
4743 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Craig Topperc3ec1492014-05-26 06:22:03 +00004745 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004746}
Douglas Gregor9b146582009-07-08 20:55:45 +00004747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004748/// Determine if the two templates are equivalent.
Douglas Gregor450f00842009-09-25 18:43:00 +00004749static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4750 if (T1 == T2)
4751 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752
Douglas Gregor450f00842009-09-25 18:43:00 +00004753 if (!T1 || !T2)
4754 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755
Douglas Gregor450f00842009-09-25 18:43:00 +00004756 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4757}
4758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004759/// Retrieve the most specialized of the given function template
Douglas Gregor450f00842009-09-25 18:43:00 +00004760/// specializations.
4761///
John McCall58cc69d2010-01-27 01:50:18 +00004762/// \param SpecBegin the start iterator of the function template
4763/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004764///
John McCall58cc69d2010-01-27 01:50:18 +00004765/// \param SpecEnd the end iterator of the function template
4766/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004767///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004769/// diagnostic should occur.
4770///
4771/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4772/// no matching candidates.
4773///
4774/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4775/// occurs.
4776///
4777/// \param CandidateDiag partial diagnostic used for each function template
4778/// specialization that is a candidate in the ambiguous ordering. One parameter
4779/// in this diagnostic should be unbound, which will correspond to the string
4780/// describing the template arguments for the function template specialization.
4781///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004783/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004784UnresolvedSetIterator Sema::getMostSpecialized(
4785 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4786 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004787 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4788 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4789 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004790 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004791 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004792 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004793 FailedCandidates.NoteCandidates(*this, Loc);
4794 }
John McCall58cc69d2010-01-27 01:50:18 +00004795 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
4798 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004799 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Douglas Gregor450f00842009-09-25 18:43:00 +00004801 // Find the function template that is better than all of the templates it
4802 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004803 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004805 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004806 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004807 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4808 FunctionTemplateDecl *Challenger
4809 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004810 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004811 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004812 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004813 Challenger)) {
4814 Best = I;
4815 BestTemplate = Challenger;
4816 }
4817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Douglas Gregor450f00842009-09-25 18:43:00 +00004819 // Make sure that the "best" function template is more specialized than all
4820 // of the others.
4821 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004822 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4823 FunctionTemplateDecl *Challenger
4824 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004825 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004827 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004828 BestTemplate)) {
4829 Ambiguous = true;
4830 break;
4831 }
4832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Douglas Gregor450f00842009-09-25 18:43:00 +00004834 if (!Ambiguous) {
4835 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004836 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838
Douglas Gregor450f00842009-09-25 18:43:00 +00004839 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004840 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004841 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004842
Richard Smithb875c432013-05-04 01:51:08 +00004843 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004844 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4845 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004846 const auto *FD = cast<FunctionDecl>(*I);
4847 PD << FD << getTemplateArgumentBindingsText(
4848 FD->getPrimaryTemplate()->getTemplateParameters(),
4849 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004850 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004851 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004852 Diag((*I)->getLocation(), PD);
4853 }
Richard Smithb875c432013-05-04 01:51:08 +00004854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855
John McCall58cc69d2010-01-27 01:50:18 +00004856 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004857}
4858
Richard Smith0da6dc42016-12-24 16:40:51 +00004859/// Determine whether one partial specialization, P1, is at least as
4860/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004861///
Richard Smith26b86ea2016-12-31 21:41:23 +00004862/// \tparam TemplateLikeDecl The kind of P2, which must be a
4863/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004864/// \param T1 The injected-class-name of P1 (faked for a variable template).
4865/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004866template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004867static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004868 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004869 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004870 // C++ [temp.class.order]p1:
4871 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872 // specialized as the second if, given the following rewrite to two
4873 // function templates, the first function template is at least as
4874 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004875 // templates (14.6.6.2):
4876 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877 // first partial specialization and has a single function parameter
4878 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004879 // arguments of the first partial specialization, and
4880 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881 // second partial specialization and has a single function parameter
4882 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004883 // arguments of the second partial specialization.
4884 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004885 // Rather than synthesize function templates, we merely perform the
4886 // equivalent partial ordering by performing deduction directly on
4887 // the template arguments of the class template partial
4888 // specializations. This computation is slightly simpler than the
4889 // general problem of function template partial ordering, because
4890 // class template partial specializations are more constrained. We
4891 // know that every template parameter is deducible from the class
4892 // template partial specialization's template arguments, for
4893 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004894 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004895
Richard Smith0da6dc42016-12-24 16:40:51 +00004896 // Determine whether P1 is at least as specialized as P2.
4897 Deduced.resize(P2->getTemplateParameters()->size());
4898 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4899 T2, T1, Info, Deduced, TDF_None,
4900 /*PartialOrdering=*/true))
4901 return false;
4902
4903 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4904 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004905 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4906 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004907 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4908 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004909 S, P2, /*PartialOrdering=*/true,
4910 TemplateArgumentList(TemplateArgumentList::OnStack,
4911 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004912 Deduced, Info))
4913 return false;
4914
4915 return true;
4916}
4917
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004918/// Returns the more specialized class template partial specialization
Richard Smith0da6dc42016-12-24 16:40:51 +00004919/// according to the rules of partial ordering of class template partial
4920/// specializations (C++ [temp.class.order]).
4921///
4922/// \param PS1 the first class template partial specialization
4923///
4924/// \param PS2 the second class template partial specialization
4925///
4926/// \returns the more specialized class template partial specialization. If
4927/// neither partial specialization is more specialized, returns NULL.
4928ClassTemplatePartialSpecializationDecl *
4929Sema::getMoreSpecializedPartialSpecialization(
4930 ClassTemplatePartialSpecializationDecl *PS1,
4931 ClassTemplatePartialSpecializationDecl *PS2,
4932 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004933 QualType PT1 = PS1->getInjectedSpecializationType();
4934 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935
Richard Smith0e617ec2016-12-27 07:56:27 +00004936 TemplateDeductionInfo Info(Loc);
4937 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4938 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004939
4940 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004941 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004942
4943 return Better1 ? PS1 : PS2;
4944}
4945
Richard Smith0e617ec2016-12-27 07:56:27 +00004946bool Sema::isMoreSpecializedThanPrimary(
4947 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4948 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4949 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4950 QualType PartialT = Spec->getInjectedSpecializationType();
4951 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4952 return false;
4953 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4954 Info.clearSFINAEDiagnostic();
4955 return false;
4956 }
4957 return true;
4958}
4959
Larisse Voufo39a1e502013-08-06 01:03:05 +00004960VarTemplatePartialSpecializationDecl *
4961Sema::getMoreSpecializedPartialSpecialization(
4962 VarTemplatePartialSpecializationDecl *PS1,
4963 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004964 // Pretend the variable template specializations are class template
4965 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004966 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004967 "the partial specializations being compared should specialize"
4968 " the same template.");
4969 TemplateName Name(PS1->getSpecializedTemplate());
4970 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4971 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004972 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004973 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004974 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004975
Richard Smith0e617ec2016-12-27 07:56:27 +00004976 TemplateDeductionInfo Info(Loc);
4977 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4978 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
Douglas Gregorbe999392009-09-15 16:23:51 +00004980 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004981 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982
Richard Smith0da6dc42016-12-24 16:40:51 +00004983 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004984}
4985
Richard Smith0e617ec2016-12-27 07:56:27 +00004986bool Sema::isMoreSpecializedThanPrimary(
4987 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4988 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4989 // FIXME: Cache the injected template arguments rather than recomputing
4990 // them for each partial specialization.
4991 SmallVector<TemplateArgument, 8> PrimaryArgs;
4992 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4993 PrimaryArgs);
4994
4995 TemplateName CanonTemplate =
4996 Context.getCanonicalTemplateName(TemplateName(Primary));
4997 QualType PrimaryT = Context.getTemplateSpecializationType(
4998 CanonTemplate, PrimaryArgs);
4999 QualType PartialT = Context.getTemplateSpecializationType(
5000 CanonTemplate, Spec->getTemplateArgs().asArray());
5001 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5002 return false;
5003 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5004 Info.clearSFINAEDiagnostic();
5005 return false;
5006 }
5007 return true;
5008}
5009
Richard Smith26b86ea2016-12-31 21:41:23 +00005010bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5011 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5012 // C++1z [temp.arg.template]p4: (DR 150)
5013 // A template template-parameter P is at least as specialized as a
5014 // template template-argument A if, given the following rewrite to two
5015 // function templates...
5016
5017 // Rather than synthesize function templates, we merely perform the
5018 // equivalent partial ordering by performing deduction directly on
5019 // the template parameter lists of the template template parameters.
5020 //
5021 // Given an invented class template X with the template parameter list of
5022 // A (including default arguments):
5023 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5024 TemplateParameterList *A = AArg->getTemplateParameters();
5025
5026 // - Each function template has a single function parameter whose type is
5027 // a specialization of X with template arguments corresponding to the
5028 // template parameters from the respective function template
5029 SmallVector<TemplateArgument, 8> AArgs;
5030 Context.getInjectedTemplateArgs(A, AArgs);
5031
5032 // Check P's arguments against A's parameter list. This will fill in default
5033 // template arguments as needed. AArgs are already correct by construction.
5034 // We can't just use CheckTemplateIdType because that will expand alias
5035 // templates.
5036 SmallVector<TemplateArgument, 4> PArgs;
5037 {
5038 SFINAETrap Trap(*this);
5039
5040 Context.getInjectedTemplateArgs(P, PArgs);
5041 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5042 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5043 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5044 // expansions, to form an "as written" argument list.
5045 TemplateArgument Arg = PArgs[I];
5046 if (Arg.getKind() == TemplateArgument::Pack) {
5047 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5048 Arg = *Arg.pack_begin();
5049 }
5050 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5051 Arg, QualType(), P->getParam(I)->getLocation()));
5052 }
5053 PArgs.clear();
5054
5055 // C++1z [temp.arg.template]p3:
5056 // If the rewrite produces an invalid type, then P is not at least as
5057 // specialized as A.
5058 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5059 Trap.hasErrorOccurred())
5060 return false;
5061 }
5062
5063 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5064 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5065
Richard Smith26b86ea2016-12-31 21:41:23 +00005066 // ... the function template corresponding to P is at least as specialized
5067 // as the function template corresponding to A according to the partial
5068 // ordering rules for function templates.
5069 TemplateDeductionInfo Info(Loc, A->getDepth());
5070 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5071}
5072
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005073/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005074/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00005075static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005076MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005077 const Expr *E,
5078 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005079 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005080 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005081 // We can deduce from a pack expansion.
5082 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5083 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084
Richard Smith34349002012-07-09 03:07:20 +00005085 // Skip through any implicit casts we added while type-checking, and any
5086 // substitutions performed by template alias expansion.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00005087 while (true) {
Richard Smith34349002012-07-09 03:07:20 +00005088 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5089 E = ICE->getSubExpr();
5090 else if (const SubstNonTypeTemplateParmExpr *Subst =
5091 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5092 E = Subst->getReplacement();
5093 else
5094 break;
5095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096
5097 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005098 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005099 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00005100 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00005101 return;
5102
Mike Stump11289f42009-09-09 15:08:12 +00005103 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00005104 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5105 if (!NTTP)
5106 return;
5107
Douglas Gregor21610382009-10-29 00:04:11 +00005108 if (NTTP->getDepth() == Depth)
5109 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00005110
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005111 // In C++17 mode, additional arguments may be deduced from the type of a
Richard Smith5f274382016-09-28 23:55:27 +00005112 // non-type argument.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005113 if (Ctx.getLangOpts().CPlusPlus17)
Richard Smith5f274382016-09-28 23:55:27 +00005114 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005115}
5116
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005117/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005118/// nested name specifier.
5119static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005120MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005121 NestedNameSpecifier *NNS,
5122 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005123 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005124 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005125 if (!NNS)
5126 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005127
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005128 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005129 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005130 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005131 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005132}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005133
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005134/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005135/// template name.
5136static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005137MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005138 TemplateName Name,
5139 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005140 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005141 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005142 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5143 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005144 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5145 if (TTP->getDepth() == Depth)
5146 Used[TTP->getIndex()] = true;
5147 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005148 return;
5149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005151 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005152 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005153 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005154 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005155 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005156 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005157}
5158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005159/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005160/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005161static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005162MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005163 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005164 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005165 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005166 if (T.isNull())
5167 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Douglas Gregor91772d12009-06-13 00:26:55 +00005169 // Non-dependent types have nothing deducible
5170 if (!T->isDependentType())
5171 return;
5172
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005173 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005174 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005175 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005176 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005177 cast<PointerType>(T)->getPointeeType(),
5178 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005179 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005180 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005181 break;
5182
5183 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005184 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005185 cast<BlockPointerType>(T)->getPointeeType(),
5186 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005187 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005188 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005189 break;
5190
5191 case Type::LValueReference:
5192 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005193 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005194 cast<ReferenceType>(T)->getPointeeType(),
5195 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005196 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005197 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005198 break;
5199
5200 case Type::MemberPointer: {
5201 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005202 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005203 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005204 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005205 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005206 break;
5207 }
5208
5209 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005210 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005211 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005212 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005213 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005214 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005215
5216 case Type::ConstantArray:
5217 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005218 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005219 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005220 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005221 break;
5222
5223 case Type::Vector:
5224 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005225 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005226 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005227 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005228 break;
5229
Douglas Gregor758a8692009-06-17 21:51:59 +00005230 case Type::DependentSizedExtVector: {
5231 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005232 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005233 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005234 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005235 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005236 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005237 break;
5238 }
5239
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005240 case Type::DependentAddressSpace: {
5241 const DependentAddressSpaceType *DependentASType =
5242 cast<DependentAddressSpaceType>(T);
5243 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5244 OnlyDeduced, Depth, Used);
5245 MarkUsedTemplateParameters(Ctx,
5246 DependentASType->getAddrSpaceExpr(),
5247 OnlyDeduced, Depth, Used);
5248 break;
5249 }
5250
Douglas Gregor91772d12009-06-13 00:26:55 +00005251 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005252 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005253 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5254 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005255 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5256 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005257 Depth, Used);
Richard Smithcd198152017-06-07 21:46:22 +00005258 if (auto *E = Proto->getNoexceptExpr())
5259 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005260 break;
5261 }
5262
Douglas Gregor21610382009-10-29 00:04:11 +00005263 case Type::TemplateTypeParm: {
5264 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5265 if (TTP->getDepth() == Depth)
5266 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005267 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005268 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005269
Douglas Gregorfb322d82011-01-14 05:11:40 +00005270 case Type::SubstTemplateTypeParmPack: {
5271 const SubstTemplateTypeParmPackType *Subst
5272 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005273 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005274 QualType(Subst->getReplacedParameter(), 0),
5275 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005276 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005277 OnlyDeduced, Depth, Used);
5278 break;
5279 }
5280
John McCall2408e322010-04-27 00:57:59 +00005281 case Type::InjectedClassName:
5282 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005283 LLVM_FALLTHROUGH;
John McCall2408e322010-04-27 00:57:59 +00005284
Douglas Gregor91772d12009-06-13 00:26:55 +00005285 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005286 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005287 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005288 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005289 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005290
Douglas Gregord0ad2942010-12-23 01:24:45 +00005291 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005292 // If the template argument list of P contains a pack expansion that is
5293 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005294 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005296 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005297 break;
5298
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005299 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005300 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005301 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005302 break;
5303 }
5304
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005305 case Type::Complex:
5306 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005307 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005308 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005309 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005310 break;
5311
Eli Friedman0dfb8892011-10-06 23:00:33 +00005312 case Type::Atomic:
5313 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005314 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005315 cast<AtomicType>(T)->getValueType(),
5316 OnlyDeduced, Depth, Used);
5317 break;
5318
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005319 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005320 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005321 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005322 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005323 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005324 break;
5325
John McCallc392f372010-06-11 00:33:02 +00005326 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005327 // C++14 [temp.deduct.type]p5:
5328 // The non-deduced contexts are:
5329 // -- The nested-name-specifier of a type that was specified using a
5330 // qualified-id
5331 //
5332 // C++14 [temp.deduct.type]p6:
5333 // When a type name is specified in a way that includes a non-deduced
5334 // context, all of the types that comprise that type name are also
5335 // non-deduced.
5336 if (OnlyDeduced)
5337 break;
5338
John McCallc392f372010-06-11 00:33:02 +00005339 const DependentTemplateSpecializationType *Spec
5340 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005341
Richard Smith50d5b972015-12-30 20:56:05 +00005342 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5343 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005344
John McCallc392f372010-06-11 00:33:02 +00005345 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005346 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005347 Used);
5348 break;
5349 }
5350
John McCallbd8d9bd2010-03-01 23:49:17 +00005351 case Type::TypeOf:
5352 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005353 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005354 cast<TypeOfType>(T)->getUnderlyingType(),
5355 OnlyDeduced, Depth, Used);
5356 break;
5357
5358 case Type::TypeOfExpr:
5359 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005360 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005361 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5362 OnlyDeduced, Depth, Used);
5363 break;
5364
5365 case Type::Decltype:
5366 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005367 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005368 cast<DecltypeType>(T)->getUnderlyingExpr(),
5369 OnlyDeduced, Depth, Used);
5370 break;
5371
Alexis Hunte852b102011-05-24 22:41:36 +00005372 case Type::UnaryTransform:
5373 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005374 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005375 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005376 OnlyDeduced, Depth, Used);
5377 break;
5378
Douglas Gregord2fa7662010-12-20 02:24:11 +00005379 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005380 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005381 cast<PackExpansionType>(T)->getPattern(),
5382 OnlyDeduced, Depth, Used);
5383 break;
5384
Richard Smith30482bc2011-02-20 03:19:35 +00005385 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005386 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005387 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005388 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005389 OnlyDeduced, Depth, Used);
Adrian Prantl4b490852017-12-19 22:21:48 +00005390 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005391
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005392 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005393 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005394 case Type::VariableArray:
5395 case Type::FunctionNoProto:
5396 case Type::Record:
5397 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005398 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005399 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005400 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005401 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005402 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005403#define TYPE(Class, Base)
5404#define ABSTRACT_TYPE(Class, Base)
5405#define DEPENDENT_TYPE(Class, Base)
5406#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5407#include "clang/AST/TypeNodes.def"
5408 break;
5409 }
5410}
5411
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005412/// Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005413/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005414static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005415MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005416 const TemplateArgument &TemplateArg,
5417 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005418 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005419 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005420 switch (TemplateArg.getKind()) {
5421 case TemplateArgument::Null:
5422 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005423 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005424 break;
Mike Stump11289f42009-09-09 15:08:12 +00005425
Eli Friedmanb826a002012-09-26 02:36:12 +00005426 case TemplateArgument::NullPtr:
5427 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5428 Depth, Used);
5429 break;
5430
Douglas Gregor91772d12009-06-13 00:26:55 +00005431 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005432 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005433 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005434 break;
5435
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005436 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005437 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005438 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005439 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005440 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005441 break;
5442
5443 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005444 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005445 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005446 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Anders Carlssonbc343912009-06-15 17:04:53 +00005448 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005449 for (const auto &P : TemplateArg.pack_elements())
5450 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005451 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005452 }
5453}
5454
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005455/// Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005456/// template argument list.
5457///
5458/// \param TemplateArgs the template argument list from which template
5459/// parameters will be deduced.
5460///
James Dennett41725122012-06-22 10:16:05 +00005461/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005462/// to indicate when the corresponding template parameter will be
5463/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005464void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005465Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005466 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005467 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005468 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469 // If the template argument list of P contains a pack expansion that is not
5470 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005471 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005473 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005474 return;
5475
Douglas Gregor91772d12009-06-13 00:26:55 +00005476 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005477 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005478 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005479}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005480
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005481/// Marks all of the template parameters that will be deduced by a
Douglas Gregorce23bae2009-09-18 23:21:38 +00005482/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005483void Sema::MarkDeducedTemplateParameters(
5484 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5485 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005487 = FunctionTemplate->getTemplateParameters();
5488 Deduced.clear();
5489 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005490
Douglas Gregorce23bae2009-09-18 23:21:38 +00005491 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5492 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005493 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005494 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005495}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005496
Richard Smithf0393bf2017-02-16 04:22:56 +00005497bool hasDeducibleTemplateParameters(Sema &S,
5498 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005499 QualType T) {
5500 if (!T->isDependentType())
5501 return false;
5502
Richard Smithf0393bf2017-02-16 04:22:56 +00005503 TemplateParameterList *TemplateParams
5504 = FunctionTemplate->getTemplateParameters();
5505 llvm::SmallBitVector Deduced(TemplateParams->size());
5506 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5507 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005508
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005509 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005510}