blob: f2f989ce1241c9ef2dbd88b0eb262b0d532885cc [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,
Richard Smithb884ed12018-07-11 23:19:41 +0000102
103 /// Within template argument deduction for a conversion function, we are
104 /// matching with an argument type for which the original argument was
105 /// a reference.
106 TDF_ArgWithReferenceType = 0x40,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000107 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000108}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000109
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000110using namespace clang;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000111using namespace sema;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000112
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000113/// Compare two APSInts, extending and switching the sign as
Douglas Gregor0a29a052010-03-26 05:50:28 +0000114/// necessary to compare their values regardless of underlying type.
115static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
116 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000117 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000118 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000119 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000120
121 // If there is a signedness mismatch, correct it.
122 if (X.isSigned() != Y.isSigned()) {
123 // If the signed value is negative, then the values cannot be the same.
124 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
125 return false;
126
127 Y.setIsSigned(true);
128 X.setIsSigned(true);
129 }
130
131 return X == Y;
132}
133
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000134static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000135DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000136 TemplateParameterList *TemplateParams,
137 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000138 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000139 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000140 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000141
Douglas Gregor7baabef2010-12-22 18:17:10 +0000142static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000143DeduceTemplateArgumentsByTypeMatch(Sema &S,
144 TemplateParameterList *TemplateParams,
145 QualType Param,
146 QualType Arg,
147 TemplateDeductionInfo &Info,
148 SmallVectorImpl<DeducedTemplateArgument> &
149 Deduced,
150 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000151 bool PartialOrdering = false,
152 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000153
154static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000155DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000156 ArrayRef<TemplateArgument> Params,
157 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000158 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000159 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
160 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000161
Richard Smith130cc442017-02-21 23:49:18 +0000162static void MarkUsedTemplateParameters(ASTContext &Ctx,
163 const TemplateArgument &TemplateArg,
164 bool OnlyDeduced, unsigned Depth,
165 llvm::SmallBitVector &Used);
166
167static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
168 bool OnlyDeduced, unsigned Level,
169 llvm::SmallBitVector &Deduced);
170
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000171/// If the given expression is of a form that permits the deduction
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000172/// of a non-type template parameter, return the declaration of that
173/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000174static NonTypeTemplateParmDecl *
175getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000176 // If we are within an alias template, the expression may have undergone
177 // any number of parameter substitutions already.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000178 while (true) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000179 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
180 E = IC->getSubExpr();
Fangrui Song407659a2018-11-30 23:41:18 +0000181 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
182 E = CE->getSubExpr();
Richard Smith7ebb07c2012-07-08 04:37:51 +0000183 else if (SubstNonTypeTemplateParmExpr *Subst =
184 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
185 E = Subst->getReplacement();
186 else
187 break;
188 }
Mike Stump11289f42009-09-09 15:08:12 +0000189
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000190 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000191 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
192 if (NTTP->getDepth() == Info.getDeducedDepth())
193 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Craig Topperc3ec1492014-05-26 06:22:03 +0000195 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000196}
197
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000198/// Determine whether two declaration pointers refer to the same
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000199/// declaration.
200static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000201 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
202 X = NX->getUnderlyingDecl();
203 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
204 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000206 return X->getCanonicalDecl() == Y->getCanonicalDecl();
207}
208
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000209/// Verify that the given, deduced template arguments are compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000210///
211/// \returns The deduced template argument, or a NULL template argument if
212/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000213static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000214checkDeducedTemplateArguments(ASTContext &Context,
215 const DeducedTemplateArgument &X,
216 const DeducedTemplateArgument &Y) {
217 // We have no deduction for one or both of the arguments; they're compatible.
218 if (X.isNull())
219 return Y;
220 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000222
Richard Smith593d6a12016-12-23 01:30:39 +0000223 // If we have two non-type template argument values deduced for the same
224 // parameter, they must both match the type of the parameter, and thus must
225 // match each other's type. As we're only keeping one of them, we must check
226 // for that now. The exception is that if either was deduced from an array
227 // bound, the type is permitted to differ.
228 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
229 QualType XType = X.getNonTypeTemplateArgumentType();
230 if (!XType.isNull()) {
231 QualType YType = Y.getNonTypeTemplateArgumentType();
232 if (YType.isNull() || !Context.hasSameType(XType, YType))
233 return DeducedTemplateArgument();
234 }
235 }
236
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000237 switch (X.getKind()) {
238 case TemplateArgument::Null:
239 llvm_unreachable("Non-deduced template arguments handled above");
240
241 case TemplateArgument::Type:
242 // If two template type arguments have the same type, they're compatible.
243 if (Y.getKind() == TemplateArgument::Type &&
244 Context.hasSameType(X.getAsType(), Y.getAsType()))
245 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000246
Richard Smith5f274382016-09-28 23:55:27 +0000247 // If one of the two arguments was deduced from an array bound, the other
248 // supersedes it.
249 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
250 return X.wasDeducedFromArrayBound() ? Y : X;
251
252 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000253 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000254
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000255 case TemplateArgument::Integral:
256 // If we deduced a constant in one case and either a dependent expression or
257 // declaration in another case, keep the integral constant.
258 // If both are integral constants with the same value, keep that value.
259 if (Y.getKind() == TemplateArgument::Expression ||
260 Y.getKind() == TemplateArgument::Declaration ||
261 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000262 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000263 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000264
265 // All other combinations are incompatible.
266 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000267
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000268 case TemplateArgument::Template:
269 if (Y.getKind() == TemplateArgument::Template &&
270 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
271 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000273 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000275
276 case TemplateArgument::TemplateExpansion:
277 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000279 Y.getAsTemplateOrTemplatePattern()))
280 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000282 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000284
Richard Smith593d6a12016-12-23 01:30:39 +0000285 case TemplateArgument::Expression: {
286 if (Y.getKind() != TemplateArgument::Expression)
287 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Richard Smith593d6a12016-12-23 01:30:39 +0000289 // Compare the expressions for equality
290 llvm::FoldingSetNodeID ID1, ID2;
291 X.getAsExpr()->Profile(ID1, Context, true);
292 Y.getAsExpr()->Profile(ID2, Context, true);
293 if (ID1 == ID2)
294 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295
Richard Smith593d6a12016-12-23 01:30:39 +0000296 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000297 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000299
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000301 assert(!X.wasDeducedFromArrayBound());
302
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 // If we deduced a declaration and a dependent expression, keep the
304 // declaration.
305 if (Y.getKind() == TemplateArgument::Expression)
306 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000307
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000309 // integral constant and whichever type did not come from an array
310 // bound.
311 if (Y.getKind() == TemplateArgument::Integral) {
312 if (Y.wasDeducedFromArrayBound())
313 return TemplateArgument(Context, Y.getAsIntegral(),
314 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000315 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000318 // If we deduced two declarations, make sure that they refer to the
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000319 // same declaration.
320 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000321 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000322 return X;
323
324 // All other combinations are incompatible.
325 return DeducedTemplateArgument();
326
327 case TemplateArgument::NullPtr:
328 // If we deduced a null pointer and a dependent expression, keep the
329 // null pointer.
330 if (Y.getKind() == TemplateArgument::Expression)
331 return X;
332
333 // If we deduced a null pointer and an integral constant, keep the
334 // integral constant.
335 if (Y.getKind() == TemplateArgument::Integral)
336 return Y;
337
Richard Smith593d6a12016-12-23 01:30:39 +0000338 // If we deduced two null pointers, they are the same.
339 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000340 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000341
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000342 // All other combinations are incompatible.
343 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000345 case TemplateArgument::Pack: {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000346 if (Y.getKind() != TemplateArgument::Pack ||
347 X.pack_size() != Y.pack_size())
348 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349
Richard Smith539e8e32017-01-04 01:48:55 +0000350 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000352 XAEnd = X.pack_end(),
353 YA = Y.pack_begin();
354 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000355 TemplateArgument Merged = checkDeducedTemplateArguments(
356 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
357 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
358 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000359 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000360 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362
Richard Smith539e8e32017-01-04 01:48:55 +0000363 return DeducedTemplateArgument(
364 TemplateArgument::CreatePackCopy(Context, NewPack),
365 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000366 }
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368
David Blaikiee4d798f2012-01-20 21:50:17 +0000369 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000370}
371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000372/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000373/// as the given deduced template argument. All non-type template parameter
374/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000375static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000376 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000377 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
378 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000379 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000380 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
381 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000382
Richard Smith5d102892016-12-27 03:59:58 +0000383 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
384 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000385 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000386 Info.Param = NTTP;
387 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000388 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000392 Deduced[NTTP->getIndex()] = Result;
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000393 if (!S.getLangOpts().CPlusPlus17)
Richard Smithd92eddf2016-12-27 06:14:37 +0000394 return Sema::TDK_Success;
395
Richard Smith130cc442017-02-21 23:49:18 +0000396 if (NTTP->isExpandedParameterPack())
397 // FIXME: We may still need to deduce parts of the type here! But we
398 // don't have any way to find which slice of the type to use, and the
399 // type stored on the NTTP itself is nonsense. Perhaps the type of an
400 // expanded NTTP should be a pack expansion type?
401 return Sema::TDK_Success;
402
Richard Smith7bfcc052017-12-01 21:24:36 +0000403 // Get the type of the parameter for deduction. If it's a (dependent) array
404 // or function type, we will not have decayed it yet, so do that now.
405 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
Richard Smith130cc442017-02-21 23:49:18 +0000406 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
407 ParamType = Expansion->getPattern();
408
Richard Smithd92eddf2016-12-27 06:14:37 +0000409 // FIXME: It's not clear how deduction of a parameter of reference
410 // type from an argument (of non-reference type) should be performed.
411 // For now, we just remove reference types from both sides and let
412 // the final check for matching types sort out the mess.
413 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000414 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000415 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
416 /*PartialOrdering=*/false,
417 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000418}
419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000420/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000421/// from the given integral constant.
422static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
423 Sema &S, TemplateParameterList *TemplateParams,
424 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
425 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
426 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
427 return DeduceNonTypeTemplateArgument(
428 S, TemplateParams, NTTP,
429 DeducedTemplateArgument(S.Context, Value, ValueType,
430 DeducedFromArrayBound),
431 ValueType, Info, Deduced);
432}
433
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000434/// Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000435/// from the given null pointer template argument type.
436static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000437 Sema &S, TemplateParameterList *TemplateParams,
438 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000439 TemplateDeductionInfo &Info,
440 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
441 Expr *Value =
442 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
443 S.Context.NullPtrTy, NTTP->getLocation()),
444 NullPtrType, CK_NullToPointer)
445 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000446 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
447 DeducedTemplateArgument(Value),
448 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000449}
450
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000451/// Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000452/// from the given type- or value-dependent expression.
453///
454/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000455static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
456 Sema &S, TemplateParameterList *TemplateParams,
457 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
458 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000459 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
460 DeducedTemplateArgument(Value),
461 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000462}
463
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000464/// Deduce the value of the given non-type template parameter
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000465/// from the given declaration.
466///
467/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000468static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
469 Sema &S, TemplateParameterList *TemplateParams,
470 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
471 TemplateDeductionInfo &Info,
472 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000473 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000474 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000475 return DeduceNonTypeTemplateArgument(
476 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000477}
478
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000479static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000480DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000481 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000482 TemplateName Param,
483 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000484 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000485 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000486 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000487 if (!ParamDecl) {
488 // The parameter type is dependent and is not a template template parameter,
489 // so there is nothing that we can deduce.
490 return Sema::TDK_Success;
491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregoradee3e32009-11-11 23:06:43 +0000493 if (TemplateTemplateParmDecl *TempParam
494 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000495 // If we're not deducing at this depth, there's nothing to deduce.
496 if (TempParam->getDepth() != Info.getDeducedDepth())
497 return Sema::TDK_Success;
498
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000499 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000501 Deduced[TempParam->getIndex()],
502 NewDeduced);
503 if (Result.isNull()) {
504 Info.Param = TempParam;
505 Info.FirstArg = Deduced[TempParam->getIndex()];
506 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000509
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000510 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000513
Douglas Gregoradee3e32009-11-11 23:06:43 +0000514 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000515 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000516 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000517
Douglas Gregoradee3e32009-11-11 23:06:43 +0000518 // Mismatch of non-dependent template parameter to argument.
519 Info.FirstArg = TemplateArgument(Param);
520 Info.SecondArg = TemplateArgument(Arg);
521 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000522}
523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000524/// Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000525/// type (which is a template-id) with the template argument type.
526///
Chandler Carruthc1263112010-02-07 21:33:28 +0000527/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000528///
529/// \param TemplateParams the template parameters that we are deducing
530///
531/// \param Param the parameter type
532///
533/// \param Arg the argument type
534///
535/// \param Info information about the template argument deduction itself
536///
537/// \param Deduced the deduced template arguments
538///
539/// \returns the result of template argument deduction so far. Note that a
540/// "success" result means that template argument deduction has not yet failed,
541/// but it may still fail, later, for other reasons.
542static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000543DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000544 TemplateParameterList *TemplateParams,
545 const TemplateSpecializationType *Param,
546 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000547 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000548 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000549 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000550
Richard Smith13373182018-01-04 01:24:17 +0000551 // Treat an injected-class-name as its underlying template-id.
552 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
553 Arg = Injected->getInjectedSpecializationType();
554
Douglas Gregore81f3e72009-07-07 23:09:34 +0000555 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000556 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000557 = dyn_cast<TemplateSpecializationType>(Arg)) {
558 // Perform template argument deduction for the template name.
559 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000560 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000561 Param->getTemplateName(),
562 SpecArg->getTemplateName(),
563 Info, Deduced))
564 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000565
Mike Stump11289f42009-09-09 15:08:12 +0000566
Douglas Gregore81f3e72009-07-07 23:09:34 +0000567 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000568 // argument. Ignore any missing/extra arguments, since they could be
569 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000570 return DeduceTemplateArguments(S, TemplateParams,
571 Param->template_arguments(),
572 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000573 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000574 }
Mike Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregore81f3e72009-07-07 23:09:34 +0000576 // If the argument type is a class template specialization, we
577 // perform template argument deduction using its template
578 // arguments.
579 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000580 if (!RecordArg) {
581 Info.FirstArg = TemplateArgument(QualType(Param, 0));
582 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000583 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000584 }
Mike Stump11289f42009-09-09 15:08:12 +0000585
586 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000587 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000588 if (!SpecArg) {
589 Info.FirstArg = TemplateArgument(QualType(Param, 0));
590 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000591 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000592 }
Mike Stump11289f42009-09-09 15:08:12 +0000593
Douglas Gregore81f3e72009-07-07 23:09:34 +0000594 // Perform template argument deduction for the template name.
595 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000596 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000597 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000598 Param->getTemplateName(),
599 TemplateName(SpecArg->getSpecializedTemplate()),
600 Info, Deduced))
601 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregor7baabef2010-12-22 18:17:10 +0000603 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000604 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
605 SpecArg->getTemplateArgs().asArray(), Info,
606 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000607}
608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000609/// Determines whether the given type is an opaque type that
John McCall08569062010-08-28 22:14:41 +0000610/// might be more qualified when instantiated.
611static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
612 switch (T->getTypeClass()) {
613 case Type::TypeOfExpr:
614 case Type::TypeOf:
615 case Type::DependentName:
616 case Type::Decltype:
617 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000618 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000619 return true;
620
621 case Type::ConstantArray:
622 case Type::IncompleteArray:
623 case Type::VariableArray:
624 case Type::DependentSizedArray:
625 return IsPossiblyOpaquelyQualifiedType(
626 cast<ArrayType>(T)->getElementType());
627
628 default:
629 return false;
630 }
631}
632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000633/// Helper function to build a TemplateParameter when we don't
Douglas Gregor5499af42011-01-05 23:12:31 +0000634/// know its type statically.
635static TemplateParameter makeTemplateParameter(Decl *D) {
636 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
637 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000638 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000639 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640
Douglas Gregor5499af42011-01-05 23:12:31 +0000641 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
642}
643
Richard Smith4a8f3512018-07-19 19:00:37 +0000644/// If \p Param is an expanded parameter pack, get the number of expansions.
645static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
646 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
647 if (NTTP->isExpandedParameterPack())
648 return NTTP->getNumExpansionTypes();
649
650 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
651 if (TTP->isExpandedParameterPack())
652 return TTP->getNumExpansionTemplateParameters();
653
654 return None;
655}
656
Richard Smith0a80d572014-05-29 01:12:14 +0000657/// A pack that we're currently deducing.
658struct clang::DeducedPack {
Richard Smith0a80d572014-05-29 01:12:14 +0000659 // The index of the pack.
660 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Richard Smith0a80d572014-05-29 01:12:14 +0000662 // The old value of the pack before we started deducing it.
663 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000664
Richard Smith0a80d572014-05-29 01:12:14 +0000665 // A deferred value of this pack from an inner deduction, that couldn't be
666 // deduced because this deduction hadn't happened yet.
667 DeducedTemplateArgument DeferredDeduction;
668
669 // The new value of the pack.
670 SmallVector<DeducedTemplateArgument, 4> New;
671
672 // The outer deduction for this pack, if any.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000673 DeducedPack *Outer = nullptr;
674
675 DeducedPack(unsigned Index) : Index(Index) {}
Richard Smith0a80d572014-05-29 01:12:14 +0000676};
677
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000678namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000679
Richard Smith0a80d572014-05-29 01:12:14 +0000680/// A scope in which we're performing pack deduction.
681class PackDeductionScope {
682public:
Richard Smith4a8f3512018-07-19 19:00:37 +0000683 /// Prepare to deduce the packs named within Pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000684 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
685 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
686 TemplateDeductionInfo &Info, TemplateArgument Pattern)
687 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith4a8f3512018-07-19 19:00:37 +0000688 unsigned NumNamedPacks = addPacks(Pattern);
689 finishConstruction(NumNamedPacks);
690 }
691
692 /// Prepare to directly deduce arguments of the parameter with index \p Index.
693 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
694 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
695 TemplateDeductionInfo &Info, unsigned Index)
696 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
697 addPack(Index);
698 finishConstruction(1);
699 }
700
701private:
702 void addPack(unsigned Index) {
703 // Save the deduced template argument for the parameter pack expanded
704 // by this pack expansion, then clear out the deduction.
705 DeducedPack Pack(Index);
706 Pack.Saved = Deduced[Index];
707 Deduced[Index] = TemplateArgument();
708
709 // FIXME: What if we encounter multiple packs with different numbers of
710 // pre-expanded expansions? (This should already have been diagnosed
711 // during substitution.)
712 if (Optional<unsigned> ExpandedPackExpansions =
713 getExpandedPackSize(TemplateParams->getParam(Index)))
714 FixedNumExpansions = ExpandedPackExpansions;
715
716 Packs.push_back(Pack);
717 }
718
719 unsigned addPacks(TemplateArgument Pattern) {
720 // Compute the set of template parameter indices that correspond to
721 // parameter packs expanded by the pack expansion.
722 llvm::SmallBitVector SawIndices(TemplateParams->size());
723
724 auto AddPack = [&](unsigned Index) {
725 if (SawIndices[Index])
726 return;
727 SawIndices[Index] = true;
728 addPack(Index);
729 };
730
731 // First look for unexpanded packs in the pattern.
732 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
733 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
734 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
735 unsigned Depth, Index;
736 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
737 if (Depth == Info.getDeducedDepth())
738 AddPack(Index);
739 }
740 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
741
742 unsigned NumNamedPacks = Packs.size();
743
744 // We can also have deduced template parameters that do not actually
745 // appear in the pattern, but can be deduced by it (the type of a non-type
746 // template parameter pack, in particular). These won't have prevented us
747 // from partially expanding the pack.
748 llvm::SmallBitVector Used(TemplateParams->size());
749 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
750 Info.getDeducedDepth(), Used);
751 for (int Index = Used.find_first(); Index != -1;
752 Index = Used.find_next(Index))
753 if (TemplateParams->getParam(Index)->isParameterPack())
754 AddPack(Index);
755
756 return NumNamedPacks;
757 }
758
759 void finishConstruction(unsigned NumNamedPacks) {
Richard Smith130cc442017-02-21 23:49:18 +0000760 // Dig out the partially-substituted pack, if there is one.
761 const TemplateArgument *PartialPackArgs = nullptr;
762 unsigned NumPartialPackArgs = 0;
763 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
764 if (auto *Scope = S.CurrentInstantiationScope)
765 if (auto *Partial = Scope->getPartiallySubstitutedPack(
766 &PartialPackArgs, &NumPartialPackArgs))
767 PartialPackDepthIndex = getDepthAndIndex(Partial);
768
Richard Smith4a8f3512018-07-19 19:00:37 +0000769 // This pack expansion will have been partially or fully expanded if
770 // it only names explicitly-specified parameter packs (including the
771 // partially-substituted one, if any).
772 bool IsExpanded = true;
773 for (unsigned I = 0; I != NumNamedPacks; ++I) {
774 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
775 IsExpanded = false;
776 IsPartiallyExpanded = false;
777 break;
Richard Smith0a80d572014-05-29 01:12:14 +0000778 }
Richard Smith4a8f3512018-07-19 19:00:37 +0000779 if (PartialPackDepthIndex ==
780 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
781 IsPartiallyExpanded = true;
782 }
Richard Smith0a80d572014-05-29 01:12:14 +0000783 }
Richard Smith0a80d572014-05-29 01:12:14 +0000784
Richard Smith4a8f3512018-07-19 19:00:37 +0000785 // Skip over the pack elements that were expanded into separate arguments.
786 // If we partially expanded, this is the number of partial arguments.
787 if (IsPartiallyExpanded)
788 PackElements += NumPartialPackArgs;
789 else if (IsExpanded)
790 PackElements += *FixedNumExpansions;
791
Richard Smith0a80d572014-05-29 01:12:14 +0000792 for (auto &Pack : Packs) {
793 if (Info.PendingDeducedPacks.size() > Pack.Index)
794 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
795 else
796 Info.PendingDeducedPacks.resize(Pack.Index + 1);
797 Info.PendingDeducedPacks[Pack.Index] = &Pack;
798
Richard Smith130cc442017-02-21 23:49:18 +0000799 if (PartialPackDepthIndex ==
800 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
801 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
802 // We pre-populate the deduced value of the partially-substituted
803 // pack with the specified value. This is not entirely correct: the
804 // value is supposed to have been substituted, not deduced, but the
805 // cases where this is observable require an exact type match anyway.
806 //
807 // FIXME: If we could represent a "depth i, index j, pack elem k"
808 // parameter, we could substitute the partially-substituted pack
809 // everywhere and avoid this.
Richard Smith4a8f3512018-07-19 19:00:37 +0000810 if (!IsPartiallyExpanded)
Richard Smith130cc442017-02-21 23:49:18 +0000811 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000812 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000813 }
814 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000815
Richard Smith4a8f3512018-07-19 19:00:37 +0000816public:
Richard Smith0a80d572014-05-29 01:12:14 +0000817 ~PackDeductionScope() {
818 for (auto &Pack : Packs)
819 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
Richard Smithde0d34a2017-01-09 07:14:40 +0000822 /// Determine whether this pack has already been partially expanded into a
823 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000824 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000825
Richard Smith4a8f3512018-07-19 19:00:37 +0000826 /// Determine whether this pack expansion scope has a known, fixed arity.
827 /// This happens if it involves a pack from an outer template that has
828 /// (notionally) already been expanded.
829 bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
830
831 /// Determine whether the next element of the argument is still part of this
832 /// pack. This is the case unless the pack is already expanded to a fixed
833 /// length.
834 bool hasNextElement() {
835 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
836 }
837
Richard Smith0a80d572014-05-29 01:12:14 +0000838 /// Move to deducing the next element in each pack that is being deduced.
839 void nextPackElement() {
840 // Capture the deduced template arguments for each parameter pack expanded
841 // by this pack expansion, add them to the list of arguments we've deduced
842 // for that pack, then clear out the deduced argument.
843 for (auto &Pack : Packs) {
844 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000845 if (!Pack.New.empty() || !DeducedArg.isNull()) {
846 while (Pack.New.size() < PackElements)
847 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000848 if (Pack.New.size() == PackElements)
849 Pack.New.push_back(DeducedArg);
850 else
851 Pack.New[PackElements] = DeducedArg;
852 DeducedArg = Pack.New.size() > PackElements + 1
853 ? Pack.New[PackElements + 1]
854 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000855 }
856 }
Richard Smith539e8e32017-01-04 01:48:55 +0000857 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000858 }
859
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000860 /// Finish template argument deduction for a set of argument packs,
Richard Smith0a80d572014-05-29 01:12:14 +0000861 /// producing the argument packs and checking for consistency with prior
862 /// deductions.
Richard Smith4a8f3512018-07-19 19:00:37 +0000863 Sema::TemplateDeductionResult
864 finish(bool TreatNoDeductionsAsNonDeduced = true) {
Richard Smith0a80d572014-05-29 01:12:14 +0000865 // Build argument packs for each of the parameter packs expanded by this
866 // pack expansion.
867 for (auto &Pack : Packs) {
868 // Put back the old value for this pack.
869 Deduced[Pack.Index] = Pack.Saved;
870
Richard Smith4a8f3512018-07-19 19:00:37 +0000871 // If we are deducing the size of this pack even if we didn't deduce any
872 // values for it, then make sure we build a pack of the right size.
873 // FIXME: Should we always deduce the size, even if the pack appears in
874 // a non-deduced context?
875 if (!TreatNoDeductionsAsNonDeduced)
876 Pack.New.resize(PackElements);
877
Richard Smith0a80d572014-05-29 01:12:14 +0000878 // Build or find a new value for this pack.
879 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000880 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000881 if (Pack.DeferredDeduction.isNull()) {
882 // We were not able to deduce anything for this parameter pack
883 // (because it only appeared in non-deduced contexts), so just
884 // restore the saved argument pack.
885 continue;
886 }
887
888 NewPack = Pack.DeferredDeduction;
889 Pack.DeferredDeduction = TemplateArgument();
890 } else if (Pack.New.empty()) {
891 // If we deduced an empty argument pack, create it now.
892 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
893 } else {
894 TemplateArgument *ArgumentPack =
895 new (S.Context) TemplateArgument[Pack.New.size()];
896 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
897 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000898 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000899 // FIXME: This is wrong, it's possible that some pack elements are
900 // deduced from an array bound and others are not:
901 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
902 // g({1, 2, 3}, {{}, {}});
903 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000904 Pack.New[0].wasDeducedFromArrayBound());
905 }
906
907 // Pick where we're going to put the merged pack.
908 DeducedTemplateArgument *Loc;
909 if (Pack.Outer) {
910 if (Pack.Outer->DeferredDeduction.isNull()) {
911 // Defer checking this pack until we have a complete pack to compare
912 // it against.
913 Pack.Outer->DeferredDeduction = NewPack;
914 continue;
915 }
916 Loc = &Pack.Outer->DeferredDeduction;
917 } else {
918 Loc = &Deduced[Pack.Index];
919 }
920
921 // Check the new pack matches any previous value.
922 DeducedTemplateArgument OldPack = *Loc;
923 DeducedTemplateArgument Result =
924 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
925
926 // If we deferred a deduction of this pack, check that one now too.
927 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
928 OldPack = Result;
929 NewPack = Pack.DeferredDeduction;
930 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
931 }
932
Richard Smith4a8f3512018-07-19 19:00:37 +0000933 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000934 if (Result.isNull()) {
Richard Smith4a8f3512018-07-19 19:00:37 +0000935 Info.Param = makeTemplateParameter(Param);
Richard Smith0a80d572014-05-29 01:12:14 +0000936 Info.FirstArg = OldPack;
937 Info.SecondArg = NewPack;
938 return Sema::TDK_Inconsistent;
939 }
940
Richard Smith4a8f3512018-07-19 19:00:37 +0000941 // If we have a pre-expanded pack and we didn't deduce enough elements
942 // for it, fail deduction.
943 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
944 if (*Expansions != PackElements) {
945 Info.Param = makeTemplateParameter(Param);
946 Info.FirstArg = Result;
947 return Sema::TDK_IncompletePack;
948 }
949 }
950
Richard Smith0a80d572014-05-29 01:12:14 +0000951 *Loc = Result;
952 }
953
954 return Sema::TDK_Success;
955 }
956
957private:
958 Sema &S;
959 TemplateParameterList *TemplateParams;
960 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
961 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000962 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000963 bool IsPartiallyExpanded = false;
Richard Smith4a8f3512018-07-19 19:00:37 +0000964 /// The number of expansions, if we have a fully-expanded pack in this scope.
965 Optional<unsigned> FixedNumExpansions;
Richard Smith0a80d572014-05-29 01:12:14 +0000966
967 SmallVector<DeducedPack, 2> Packs;
968};
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000969
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000970} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000971
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000972/// Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000973/// types to the list of argument types, as in the parameter-type-lists of
974/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000975///
976/// \param S The semantic analysis object within which we are deducing
977///
978/// \param TemplateParams The template parameters that we are deducing
979///
980/// \param Params The list of parameter types
981///
982/// \param NumParams The number of types in \c Params
983///
984/// \param Args The list of argument types
985///
986/// \param NumArgs The number of types in \c Args
987///
988/// \param Info information about the template argument deduction itself
989///
990/// \param Deduced the deduced template arguments
991///
992/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
993/// how template argument deduction is performed.
994///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000995/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000997/// (C++0x [temp.deduct.partial]).
998///
Douglas Gregor5499af42011-01-05 23:12:31 +0000999/// \returns the result of template argument deduction so far. Note that a
1000/// "success" result means that template argument deduction has not yet failed,
1001/// but it may still fail, later, for other reasons.
1002static Sema::TemplateDeductionResult
1003DeduceTemplateArguments(Sema &S,
1004 TemplateParameterList *TemplateParams,
1005 const QualType *Params, unsigned NumParams,
1006 const QualType *Args, unsigned NumArgs,
1007 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +00001008 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +00001009 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +00001010 bool PartialOrdering = false) {
Douglas Gregor5499af42011-01-05 23:12:31 +00001011 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // Similarly, if P has a form that contains (T), then each parameter type
1013 // Pi of the respective parameter-type- list of P is compared with the
1014 // corresponding parameter type Ai of the corresponding parameter-type-list
1015 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +00001016 unsigned ArgIdx = 0, ParamIdx = 0;
1017 for (; ParamIdx != NumParams; ++ParamIdx) {
1018 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +00001020 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1021 if (!Expansion) {
1022 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001023
Douglas Gregor5499af42011-01-05 23:12:31 +00001024 // Make sure we have an argument.
1025 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +00001026 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001028 if (isa<PackExpansionType>(Args[ArgIdx])) {
1029 // C++0x [temp.deduct.type]p22:
1030 // If the original function parameter associated with A is a function
1031 // parameter pack and the function parameter associated with P is not
1032 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001033 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001034 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
Douglas Gregor5499af42011-01-05 23:12:31 +00001036 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001037 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1038 Params[ParamIdx], Args[ArgIdx],
1039 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +00001040 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +00001041 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001042
Douglas Gregor5499af42011-01-05 23:12:31 +00001043 ++ArgIdx;
1044 continue;
1045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregor5499af42011-01-05 23:12:31 +00001047 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +00001049 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +00001051 // comparison deduces template arguments for subsequent positions in the
1052 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053
Douglas Gregor5499af42011-01-05 23:12:31 +00001054 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00001055 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001056
Richard Smith4a8f3512018-07-19 19:00:37 +00001057 // A pack scope with fixed arity is not really a pack any more, so is not
1058 // a non-deduced context.
1059 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1060 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
Richard Smithc379d1a2018-07-12 23:32:39 +00001061 // Deduce template arguments from the pattern.
1062 if (Sema::TemplateDeductionResult Result
1063 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1064 Args[ArgIdx], Info, Deduced,
1065 TDF, PartialOrdering))
1066 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067
Richard Smithc379d1a2018-07-12 23:32:39 +00001068 PackScope.nextPackElement();
1069 }
1070 } else {
1071 // C++0x [temp.deduct.type]p5:
1072 // The non-deduced contexts are:
1073 // - A function parameter pack that does not occur at the end of the
1074 // parameter-declaration-clause.
1075 //
1076 // FIXME: There is no wording to say what we should do in this case. We
1077 // choose to resolve this by applying the same rule that is applied for a
1078 // function call: that is, deduce all contained packs to their
1079 // explicitly-specified values (or to <> if there is no such value).
1080 //
1081 // This is seemingly-arbitrarily different from the case of a template-id
1082 // with a non-trailing pack-expansion in its arguments, which renders the
1083 // entire template-argument-list a non-deduced context.
1084
1085 // If the parameter type contains an explicitly-specified pack that we
1086 // could not expand, skip the number of parameters notionally created
1087 // by the expansion.
1088 Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1089 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1090 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1091 ++I, ++ArgIdx)
1092 PackScope.nextPackElement();
1093 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001095
Douglas Gregor5499af42011-01-05 23:12:31 +00001096 // Build argument packs for each of the parameter packs expanded by this
1097 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001098 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +00001100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101
Douglas Gregor5499af42011-01-05 23:12:31 +00001102 // Make sure we don't have any extra arguments.
1103 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +00001104 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Douglas Gregor5499af42011-01-05 23:12:31 +00001106 return Sema::TDK_Success;
1107}
1108
Richard Smith34c32502018-07-11 21:07:04 +00001109/// Determine whether the parameter has qualifiers that the argument
1110/// lacks. Put another way, determine whether there is no way to add
1111/// a deduced set of qualifiers to the ParamType that would result in
1112/// its qualifiers matching those of the ArgType.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001113static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1114 QualType ArgType) {
1115 Qualifiers ParamQs = ParamType.getQualifiers();
1116 Qualifiers ArgQs = ArgType.getQualifiers();
1117
1118 if (ParamQs == ArgQs)
1119 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001120
Douglas Gregor1d684c22011-04-28 00:56:09 +00001121 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +00001122 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +00001123 ParamQs.hasObjCGCAttr())
1124 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001125
Douglas Gregor1d684c22011-04-28 00:56:09 +00001126 // Mismatched (but not missing) address spaces.
1127 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1128 ParamQs.hasAddressSpace())
1129 return true;
1130
John McCall31168b02011-06-15 23:02:42 +00001131 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1132 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1133 ParamQs.hasObjCLifetime())
1134 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001135
Richard Smith34c32502018-07-11 21:07:04 +00001136 // CVR qualifiers inconsistent or a superset.
1137 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
Douglas Gregor1d684c22011-04-28 00:56:09 +00001138}
1139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001140/// Compare types for equality with respect to possibly compatible
Douglas Gregor19a41f12013-04-17 08:45:07 +00001141/// function types (noreturn adjustment, implicit calling conventions). If any
1142/// of parameter and argument is not a function, just perform type comparison.
1143///
1144/// \param Param the template parameter type.
1145///
1146/// \param Arg the argument type.
1147bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1148 CanQualType Arg) {
1149 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1150 *ArgFunction = Arg->getAs<FunctionType>();
1151
1152 // Just compare if not functions.
1153 if (!ParamFunction || !ArgFunction)
1154 return Param == Arg;
1155
Richard Smith3c4f8d22016-10-16 17:54:23 +00001156 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001157 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001158 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001159 return Arg == Context.getCanonicalType(AdjustedParam);
1160
1161 // FIXME: Compatible calling conventions.
1162
1163 return Param == Arg;
1164}
1165
Richard Smith32918772017-02-14 00:25:28 +00001166/// Get the index of the first template parameter that was originally from the
1167/// innermost template-parameter-list. This is 0 except when we concatenate
1168/// the template parameter lists of a class template and a constructor template
1169/// when forming an implicit deduction guide.
1170static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001171 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1172 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001173 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001174 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001175}
1176
1177/// Determine whether a type denotes a forwarding reference.
1178static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1179 // C++1z [temp.deduct.call]p3:
1180 // A forwarding reference is an rvalue reference to a cv-unqualified
1181 // template parameter that does not represent a template parameter of a
1182 // class template.
1183 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1184 if (ParamRef->getPointeeType().getQualifiers())
1185 return false;
1186 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1187 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1188 }
1189 return false;
1190}
1191
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001192/// Deduce the template arguments by comparing the parameter type and
Douglas Gregorcceb9752009-06-26 18:27:22 +00001193/// the argument type (C++ [temp.deduct.type]).
1194///
Chandler Carruthc1263112010-02-07 21:33:28 +00001195/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001196///
1197/// \param TemplateParams the template parameters that we are deducing
1198///
1199/// \param ParamIn the parameter type
1200///
1201/// \param ArgIn the argument type
1202///
1203/// \param Info information about the template argument deduction itself
1204///
1205/// \param Deduced the deduced template arguments
1206///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001207/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001208/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001209///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001210/// \param PartialOrdering Whether we're performing template argument deduction
1211/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1212///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001213/// \returns the result of template argument deduction so far. Note that a
1214/// "success" result means that template argument deduction has not yet failed,
1215/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001216static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001217DeduceTemplateArgumentsByTypeMatch(Sema &S,
1218 TemplateParameterList *TemplateParams,
1219 QualType ParamIn, QualType ArgIn,
1220 TemplateDeductionInfo &Info,
1221 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1222 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001223 bool PartialOrdering,
1224 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001225 // We only want to look at the canonical types, since typedefs and
1226 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001227 QualType Param = S.Context.getCanonicalType(ParamIn);
1228 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001229
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001230 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001231 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001232 if (const PackExpansionType *ArgExpansion
1233 = dyn_cast<PackExpansionType>(Arg))
1234 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001235
Douglas Gregorb837ea42011-01-11 17:34:58 +00001236 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001237 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238 // Before the partial ordering is done, certain transformations are
1239 // performed on the types used for partial ordering:
1240 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001241 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1242 if (ParamRef)
1243 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
Douglas Gregorb837ea42011-01-11 17:34:58 +00001245 // - If A is a reference type, A is replaced by the type referred to.
1246 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1247 if (ArgRef)
1248 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001249
Richard Smithed563c22015-02-20 04:45:22 +00001250 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1251 // C++11 [temp.deduct.partial]p9:
1252 // If, for a given type, deduction succeeds in both directions (i.e.,
1253 // the types are identical after the transformations above) and both
1254 // P and A were reference types [...]:
1255 // - if [one type] was an lvalue reference and [the other type] was
1256 // not, [the other type] is not considered to be at least as
1257 // specialized as [the first type]
1258 // - if [one type] is more cv-qualified than [the other type],
1259 // [the other type] is not considered to be at least as specialized
1260 // as [the first type]
1261 // Objective-C ARC adds:
1262 // - [one type] has non-trivial lifetime, [the other type] has
1263 // __unsafe_unretained lifetime, and the types are otherwise
1264 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001265 //
Richard Smithed563c22015-02-20 04:45:22 +00001266 // A is "considered to be at least as specialized" as P iff deduction
1267 // succeeds, so we model this as a deduction failure. Note that
1268 // [the first type] is P and [the other type] is A here; the standard
1269 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001270 Qualifiers ParamQuals = Param.getQualifiers();
1271 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001272 if ((ParamRef->isLValueReferenceType() &&
1273 !ArgRef->isLValueReferenceType()) ||
1274 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1275 (ParamQuals.hasNonTrivialObjCLifetime() &&
1276 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1277 ParamQuals.withoutObjCLifetime() ==
1278 ArgQuals.withoutObjCLifetime())) {
1279 Info.FirstArg = TemplateArgument(ParamIn);
1280 Info.SecondArg = TemplateArgument(ArgIn);
1281 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001282 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284
Richard Smithed563c22015-02-20 04:45:22 +00001285 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001286 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001288 // version of P.
1289 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001290 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001291 // version of A.
1292 Arg = Arg.getUnqualifiedType();
1293 } else {
1294 // C++0x [temp.deduct.call]p4 bullet 1:
1295 // - If the original P is a reference type, the deduced A (i.e., the type
1296 // referred to by the reference) can be more cv-qualified than the
1297 // transformed A.
1298 if (TDF & TDF_ParamWithReferenceType) {
1299 Qualifiers Quals;
1300 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1301 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001302 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001303 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305
Douglas Gregor85f240c2011-01-25 17:19:08 +00001306 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1307 // C++0x [temp.deduct.type]p10:
1308 // If P and A are function types that originated from deduction when
1309 // taking the address of a function template (14.8.2.2) or when deducing
1310 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001312 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1313 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001315 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1316 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001317 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001318 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001319 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1320 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001321 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001324 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001325 // A template type argument T, a template template argument TT or a
1326 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 // the following forms:
1328 //
1329 // T
1330 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001331 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001332 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001333 // Just skip any attempts to deduce from a placeholder type or a parameter
1334 // at a different depth.
1335 if (Arg->isPlaceholderType() ||
1336 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001337 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001338
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001339 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001340 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregor60454822009-07-22 20:02:25 +00001342 // If the argument type is an array type, move the qualifiers up to the
1343 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001344 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001345 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001346 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001347 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001348 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001349 RecanonicalizeArg = true;
1350 }
1351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001353 // The argument type can not be less qualified than the parameter
1354 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001355 if (!(TDF & TDF_IgnoreQualifiers) &&
1356 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001357 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001358 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001359 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001360 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001361 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001362
Lei Liu413f3c52018-05-03 01:43:23 +00001363 // Do not match a function type with a cv-qualified type.
1364 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1365 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1366 return Sema::TDK_NonDeducedMismatch;
1367 }
1368
Richard Smith87d263e2016-12-25 08:05:23 +00001369 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1370 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001371 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001372 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001373
Douglas Gregor1d684c22011-04-28 00:56:09 +00001374 // Remove any qualifiers on the parameter from the deduced type.
1375 // We checked the qualifiers for consistency above.
1376 Qualifiers DeducedQs = DeducedType.getQualifiers();
1377 Qualifiers ParamQs = Param.getQualifiers();
1378 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1379 if (ParamQs.hasObjCGCAttr())
1380 DeducedQs.removeObjCGCAttr();
1381 if (ParamQs.hasAddressSpace())
1382 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001383 if (ParamQs.hasObjCLifetime())
1384 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001385
Douglas Gregore46db902011-06-17 22:11:49 +00001386 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001387 // If template deduction would produce a lifetime qualifier on a type
1388 // that is not a lifetime type, template argument deduction fails.
1389 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1390 !DeducedType->isDependentType()) {
1391 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1392 Info.FirstArg = TemplateArgument(Param);
1393 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001394 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001395 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001396
Douglas Gregora4f2b432011-07-26 14:53:44 +00001397 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001398 // If template deduction would produce an argument type with lifetime type
1399 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001400 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001401 DeducedType->isObjCLifetimeType() &&
1402 !DeducedQs.hasObjCLifetime())
1403 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001404
Douglas Gregor1d684c22011-04-28 00:56:09 +00001405 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1406 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001407
Douglas Gregord6605db2009-07-22 21:30:48 +00001408 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001409 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001410
Richard Smith5f274382016-09-28 23:55:27 +00001411 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001413 Deduced[Index],
1414 NewDeduced);
1415 if (Result.isNull()) {
1416 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1417 Info.FirstArg = Deduced[Index];
1418 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001419 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001422 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001424 }
1425
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001426 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001427 Info.FirstArg = TemplateArgument(ParamIn);
1428 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001429
Douglas Gregorfb322d82011-01-14 05:11:40 +00001430 // If the parameter is an already-substituted template parameter
1431 // pack, do nothing: we don't know which of its arguments to look
1432 // at, so we have to wait until all of the parameter packs in this
1433 // expansion have arguments.
1434 if (isa<SubstTemplateTypeParmPackType>(Param))
1435 return Sema::TDK_Success;
1436
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001437 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001438 CanQualType CanParam = S.Context.getCanonicalType(Param);
1439 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001440 if (!(TDF & TDF_IgnoreQualifiers)) {
1441 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001442 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001443 return Sema::TDK_NonDeducedMismatch;
Richard Smithb884ed12018-07-11 23:19:41 +00001444 } else if (TDF & TDF_ArgWithReferenceType) {
1445 // C++ [temp.deduct.conv]p4:
1446 // If the original A is a reference type, A can be more cv-qualified
1447 // than the deduced A
1448 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1449 return Sema::TDK_NonDeducedMismatch;
1450
1451 // Strip out all extra qualifiers from the argument to figure out the
1452 // type we're converting to, prior to the qualification conversion.
1453 Qualifiers Quals;
1454 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1455 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
John McCall08569062010-08-28 22:14:41 +00001456 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001457 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001458 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001459 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001460
Douglas Gregor194ea692012-03-11 03:29:50 +00001461 // If the parameter type is not dependent, there is nothing to deduce.
1462 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001463 if (!(TDF & TDF_SkipNonDependent)) {
Richard Smithcd198152017-06-07 21:46:22 +00001464 bool NonDeduced =
1465 (TDF & TDF_AllowCompatibleFunctionType)
1466 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1467 : Param != Arg;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001468 if (NonDeduced) {
1469 return Sema::TDK_NonDeducedMismatch;
1470 }
1471 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001472 return Sema::TDK_Success;
1473 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001474 } else if (!Param->isDependentType()) {
1475 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1476 ArgUnqualType = CanArg.getUnqualifiedType();
Richard Smithcd198152017-06-07 21:46:22 +00001477 bool Success =
1478 (TDF & TDF_AllowCompatibleFunctionType)
1479 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1480 : ParamUnqualType == ArgUnqualType;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001481 if (Success)
1482 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001483 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001484
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001485 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001486 // Non-canonical types cannot appear here.
1487#define NON_CANONICAL_TYPE(Class, Base) \
1488 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1489#define TYPE(Class, Base)
1490#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001491
Douglas Gregor39c02722011-06-15 16:02:29 +00001492 case Type::TemplateTypeParm:
1493 case Type::SubstTemplateTypeParmPack:
1494 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001495
1496 // These types cannot be dependent, so simply check whether the types are
1497 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001498 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001499 case Type::VariableArray:
1500 case Type::Vector:
1501 case Type::FunctionNoProto:
1502 case Type::Record:
1503 case Type::Enum:
1504 case Type::ObjCObject:
1505 case Type::ObjCInterface:
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001506 case Type::ObjCObjectPointer:
Douglas Gregor194ea692012-03-11 03:29:50 +00001507 if (TDF & TDF_SkipNonDependent)
1508 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001509
Douglas Gregor194ea692012-03-11 03:29:50 +00001510 if (TDF & TDF_IgnoreQualifiers) {
1511 Param = Param.getUnqualifiedType();
1512 Arg = Arg.getUnqualifiedType();
1513 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001514
Douglas Gregor194ea692012-03-11 03:29:50 +00001515 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001516
1517 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001518 case Type::Complex:
1519 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001520 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1521 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001522 ComplexArg->getElementType(),
1523 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001524
1525 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001526
1527 // _Atomic T [extension]
1528 case Type::Atomic:
1529 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001530 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001531 cast<AtomicType>(Param)->getValueType(),
1532 AtomicArg->getValueType(),
1533 Info, Deduced, TDF);
1534
1535 return Sema::TDK_NonDeducedMismatch;
1536
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001537 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001538 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001539 QualType PointeeType;
1540 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1541 PointeeType = PointerArg->getPointeeType();
1542 } else if (const ObjCObjectPointerType *PointerArg
1543 = Arg->getAs<ObjCObjectPointerType>()) {
1544 PointeeType = PointerArg->getPointeeType();
1545 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001546 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Douglas Gregorfc516c92009-06-26 23:27:24 +00001549 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001550 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1551 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001552 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001553 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001556 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001557 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001558 const LValueReferenceType *ReferenceArg =
1559 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001560 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001561 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001562
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001563 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001564 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001565 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001566 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001567
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001568 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001569 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001570 const RValueReferenceType *ReferenceArg =
1571 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001572 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001573 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001574
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001575 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1576 cast<RValueReferenceType>(Param)->getPointeeType(),
1577 ReferenceArg->getPointeeType(),
1578 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001579 }
Mike Stump11289f42009-09-09 15:08:12 +00001580
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001581 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001582 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001583 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001584 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001585 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001586 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCallf7332682010-08-19 00:20:19 +00001588 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001589 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1590 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1591 IncompleteArrayArg->getElementType(),
1592 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001593 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001594
1595 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001596 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001597 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001598 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001599 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001600 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001601
1602 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001603 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001604 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001605 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001606
John McCallf7332682010-08-19 00:20:19 +00001607 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001608 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1609 ConstantArrayParm->getElementType(),
1610 ConstantArrayArg->getElementType(),
1611 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001612 }
1613
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001614 // type [i]
1615 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001616 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001617 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001618 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001619
John McCallf7332682010-08-19 00:20:19 +00001620 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1621
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001622 // Check the element type of the arrays
1623 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001624 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001625 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001626 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1627 DependentArrayParm->getElementType(),
1628 ArrayArg->getElementType(),
1629 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001630 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001631
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001632 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001633 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001634 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001635 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001636 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001637
1638 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001639 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001640 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1641 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001642 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001643 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1644 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001645 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001646 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001647 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001648 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001649 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001650 if (const DependentSizedArrayType *DependentArrayArg
1651 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001652 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001653 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001654 DependentArrayArg->getSizeExpr(),
1655 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001656
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001657 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001658 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
1661 // type(*)(T)
1662 // T(*)()
1663 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001664 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001665 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001666 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001667 dyn_cast<FunctionProtoType>(Arg);
1668 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001669 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001670
1671 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001672 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001673
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001674 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001675 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001677 != FunctionProtoArg->getRefQualifier() ||
1678 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001679 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001680
Anders Carlsson2128ec72009-06-08 15:19:08 +00001681 // Check return types.
Richard Smithcd198152017-06-07 21:46:22 +00001682 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1683 S, TemplateParams, FunctionProtoParam->getReturnType(),
1684 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001685 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001686
Richard Smithcd198152017-06-07 21:46:22 +00001687 // Check parameter types.
1688 if (auto Result = DeduceTemplateArguments(
1689 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1690 FunctionProtoParam->getNumParams(),
1691 FunctionProtoArg->param_type_begin(),
1692 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1693 return Result;
1694
1695 if (TDF & TDF_AllowCompatibleFunctionType)
1696 return Sema::TDK_Success;
1697
1698 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1699 // deducing through the noexcept-specifier if it's part of the canonical
1700 // type. libstdc++ relies on this.
1701 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1702 if (NonTypeTemplateParmDecl *NTTP =
1703 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1704 : nullptr) {
1705 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1706 "saw non-type template parameter with wrong depth");
1707
1708 llvm::APSInt Noexcept(1);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001709 switch (FunctionProtoArg->canThrow()) {
Richard Smithcd198152017-06-07 21:46:22 +00001710 case CT_Cannot:
1711 Noexcept = 1;
1712 LLVM_FALLTHROUGH;
1713
1714 case CT_Can:
1715 // We give E in noexcept(E) the "deduced from array bound" treatment.
1716 // FIXME: Should we?
1717 return DeduceNonTypeTemplateArgument(
1718 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1719 /*ArrayBound*/true, Info, Deduced);
1720
1721 case CT_Dependent:
1722 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1723 return DeduceNonTypeTemplateArgument(
1724 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1725 // Can't deduce anything from throw(T...).
1726 break;
1727 }
1728 }
1729 // FIXME: Detect non-deduced exception specification mismatches?
Richard Smith746e35e2018-07-12 18:49:13 +00001730 //
1731 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1732 // top-level differences in noexcept-specifications.
Richard Smithcd198152017-06-07 21:46:22 +00001733
1734 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +00001735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001737 case Type::InjectedClassName:
John McCalle78aac42010-03-10 03:28:59 +00001738 // Treat a template's injected-class-name as if the template
1739 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001740 Param = cast<InjectedClassNameType>(Param)
1741 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001742 assert(isa<TemplateSpecializationType>(Param) &&
1743 "injected class name is not a template specialization type");
Richard Smithcd198152017-06-07 21:46:22 +00001744 LLVM_FALLTHROUGH;
John McCalle78aac42010-03-10 03:28:59 +00001745
Douglas Gregor705c9002009-06-26 20:57:09 +00001746 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001747 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001748 // TT<T>
1749 // TT<i>
1750 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001751 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001752 const TemplateSpecializationType *SpecParam =
1753 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001754
Richard Smith9b296e32016-04-25 19:09:05 +00001755 // When Arg cannot be a derived class, we can just try to deduce template
1756 // arguments from the template-id.
1757 const RecordType *RecordT = Arg->getAs<RecordType>();
1758 if (!(TDF & TDF_DerivedClass) || !RecordT)
1759 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1760 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001761
Richard Smith9b296e32016-04-25 19:09:05 +00001762 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1763 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001764
Richard Smith9b296e32016-04-25 19:09:05 +00001765 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1766 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Richard Smith9b296e32016-04-25 19:09:05 +00001768 if (Result == Sema::TDK_Success)
1769 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001770
Richard Smith9b296e32016-04-25 19:09:05 +00001771 // We cannot inspect base classes as part of deduction when the type
1772 // is incomplete, so either instantiate any templates necessary to
1773 // complete the type, or skip over it if it cannot be completed.
1774 if (!S.isCompleteType(Info.getLocation(), Arg))
1775 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001776
Richard Smith9b296e32016-04-25 19:09:05 +00001777 // C++14 [temp.deduct.call] p4b3:
1778 // If P is a class and P has the form simple-template-id, then the
1779 // transformed A can be a derived class of the deduced A. Likewise if
1780 // P is a pointer to a class of the form simple-template-id, the
1781 // transformed A can be a pointer to a derived class pointed to by the
1782 // deduced A.
1783 //
1784 // These alternatives are considered only if type deduction would
1785 // otherwise fail. If they yield more than one possible deduced A, the
1786 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001787
Faisal Vali683b0742016-05-19 02:28:21 +00001788 // Reset the incorrectly deduced argument from above.
1789 Deduced = DeducedOrig;
1790
1791 // Use data recursion to crawl through the list of base classes.
1792 // Visited contains the set of nodes we have already visited, while
1793 // ToVisit is our stack of records that we still need to visit.
1794 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1795 SmallVector<const RecordType *, 8> ToVisit;
1796 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001797 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001798 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001799 while (!ToVisit.empty()) {
1800 // Retrieve the next class in the inheritance hierarchy.
1801 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001802
Faisal Vali683b0742016-05-19 02:28:21 +00001803 // If we have already seen this type, skip it.
1804 if (!Visited.insert(NextT).second)
1805 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001806
Faisal Vali683b0742016-05-19 02:28:21 +00001807 // If this is a base class, try to perform template argument
1808 // deduction from it.
1809 if (NextT != RecordT) {
1810 TemplateDeductionInfo BaseInfo(Info.getLocation());
1811 Sema::TemplateDeductionResult BaseResult =
1812 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1813 QualType(NextT, 0), BaseInfo, Deduced);
1814
1815 // If template argument deduction for this base was successful,
1816 // note that we had some success. Otherwise, ignore any deductions
1817 // from this base class.
1818 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001819 // If we've already seen some success, then deduction fails due to
1820 // an ambiguity (temp.deduct.call p5).
1821 if (Successful)
1822 return Sema::TDK_MiscellaneousDeductionFailure;
1823
Faisal Vali683b0742016-05-19 02:28:21 +00001824 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001825 std::swap(SuccessfulDeduced, Deduced);
1826
Faisal Vali683b0742016-05-19 02:28:21 +00001827 Info.Param = BaseInfo.Param;
1828 Info.FirstArg = BaseInfo.FirstArg;
1829 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001830 }
1831
1832 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
Faisal Vali683b0742016-05-19 02:28:21 +00001835 // Visit base classes
1836 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1837 for (const auto &Base : Next->bases()) {
1838 assert(Base.getType()->isRecordType() &&
1839 "Base class that isn't a record?");
1840 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1841 }
1842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001844 if (Successful) {
1845 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001846 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001847 }
Richard Smith9b296e32016-04-25 19:09:05 +00001848
Douglas Gregore81f3e72009-07-07 23:09:34 +00001849 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001850 }
1851
Douglas Gregor637d9982009-06-10 23:47:09 +00001852 // T type::*
1853 // T T::*
1854 // T (type::*)()
1855 // type (T::*)()
1856 // type (type::*)(T)
1857 // type (T::*)(T)
1858 // T (type::*)(T)
1859 // T (T::*)()
1860 // T (T::*)(T)
1861 case Type::MemberPointer: {
1862 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1863 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1864 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001865 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001866
David Majnemera381cda2015-11-30 20:34:28 +00001867 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1868 if (ParamPointeeType->isFunctionType())
1869 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1870 /*IsCtorOrDtor=*/false, Info.getLocation());
1871 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1872 if (ArgPointeeType->isFunctionType())
1873 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1874 /*IsCtorOrDtor=*/false, Info.getLocation());
1875
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001876 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001877 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001878 ParamPointeeType,
1879 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001880 Info, Deduced,
1881 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001882 return Result;
1883
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001884 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1885 QualType(MemPtrParam->getClass(), 0),
1886 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001887 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001888 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001889 }
1890
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001891 // (clang extension)
1892 //
Mike Stump11289f42009-09-09 15:08:12 +00001893 // type(^)(T)
1894 // T(^)()
1895 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001896 case Type::BlockPointer: {
1897 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1898 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Anders Carlssona767eee2009-06-12 16:23:10 +00001900 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001901 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001903 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1904 BlockPtrParam->getPointeeType(),
1905 BlockPtrArg->getPointeeType(),
1906 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001907 }
1908
Douglas Gregor39c02722011-06-15 16:02:29 +00001909 // (clang extension)
1910 //
1911 // T __attribute__(((ext_vector_type(<integral constant>))))
1912 case Type::ExtVector: {
1913 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1914 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1915 // Make sure that the vectors have the same number of elements.
1916 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1917 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001918
Douglas Gregor39c02722011-06-15 16:02:29 +00001919 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001920 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1921 VectorParam->getElementType(),
1922 VectorArg->getElementType(),
1923 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001924 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001925
1926 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001927 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1928 // We can't check the number of elements, since the argument has a
1929 // dependent number of elements. This can only occur during partial
1930 // ordering.
1931
1932 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001933 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1934 VectorParam->getElementType(),
1935 VectorArg->getElementType(),
1936 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001937 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001938
Douglas Gregor39c02722011-06-15 16:02:29 +00001939 return Sema::TDK_NonDeducedMismatch;
1940 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001941
Erich Keanef702b022018-07-13 19:46:04 +00001942 case Type::DependentVector: {
1943 const auto *VectorParam = cast<DependentVectorType>(Param);
1944
1945 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1946 // Perform deduction on the element types.
1947 if (Sema::TemplateDeductionResult Result =
1948 DeduceTemplateArgumentsByTypeMatch(
1949 S, TemplateParams, VectorParam->getElementType(),
1950 VectorArg->getElementType(), Info, Deduced, TDF))
1951 return Result;
1952
1953 // Perform deduction on the vector size, if we can.
1954 NonTypeTemplateParmDecl *NTTP =
1955 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1956 if (!NTTP)
1957 return Sema::TDK_Success;
1958
1959 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1960 ArgSize = VectorArg->getNumElements();
1961 // Note that we use the "array bound" rules here; just like in that
1962 // case, we don't have any particular type for the vector size, but
1963 // we can provide one if necessary.
1964 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1965 S.Context.UnsignedIntTy, true,
1966 Info, Deduced);
1967 }
1968
1969 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1970 // Perform deduction on the element types.
1971 if (Sema::TemplateDeductionResult Result =
1972 DeduceTemplateArgumentsByTypeMatch(
1973 S, TemplateParams, VectorParam->getElementType(),
1974 VectorArg->getElementType(), Info, Deduced, TDF))
1975 return Result;
1976
1977 // Perform deduction on the vector size, if we can.
1978 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1979 Info, VectorParam->getSizeExpr());
1980 if (!NTTP)
1981 return Sema::TDK_Success;
1982
1983 return DeduceNonTypeTemplateArgument(
1984 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1985 }
1986
1987 return Sema::TDK_NonDeducedMismatch;
1988 }
1989
Douglas Gregor39c02722011-06-15 16:02:29 +00001990 // (clang extension)
1991 //
1992 // T __attribute__(((ext_vector_type(N))))
1993 case Type::DependentSizedExtVector: {
1994 const DependentSizedExtVectorType *VectorParam
1995 = cast<DependentSizedExtVectorType>(Param);
1996
1997 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1998 // Perform deduction on the element types.
1999 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00002000 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2001 VectorParam->getElementType(),
2002 VectorArg->getElementType(),
2003 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00002004 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002005
Douglas Gregor39c02722011-06-15 16:02:29 +00002006 // Perform deduction on the vector size, if we can.
2007 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002008 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00002009 if (!NTTP)
2010 return Sema::TDK_Success;
2011
2012 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2013 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00002014 // Note that we use the "array bound" rules here; just like in that
2015 // case, we don't have any particular type for the vector size, but
2016 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00002017 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00002018 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00002019 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00002020 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002021
2022 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00002023 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2024 // Perform deduction on the element types.
2025 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00002026 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2027 VectorParam->getElementType(),
2028 VectorArg->getElementType(),
2029 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00002030 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002031
Douglas Gregor39c02722011-06-15 16:02:29 +00002032 // Perform deduction on the vector size, if we can.
2033 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002034 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00002035 if (!NTTP)
2036 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002037
Richard Smith5f274382016-09-28 23:55:27 +00002038 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2039 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00002040 Info, Deduced);
2041 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002042
Douglas Gregor39c02722011-06-15 16:02:29 +00002043 return Sema::TDK_NonDeducedMismatch;
2044 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002045
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002046 // (clang extension)
2047 //
2048 // T __attribute__(((address_space(N))))
2049 case Type::DependentAddressSpace: {
2050 const DependentAddressSpaceType *AddressSpaceParam =
2051 cast<DependentAddressSpaceType>(Param);
2052
2053 if (const DependentAddressSpaceType *AddressSpaceArg =
2054 dyn_cast<DependentAddressSpaceType>(Arg)) {
2055 // Perform deduction on the pointer type.
2056 if (Sema::TemplateDeductionResult Result =
2057 DeduceTemplateArgumentsByTypeMatch(
2058 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2059 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2060 return Result;
2061
2062 // Perform deduction on the address space, if we can.
2063 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2064 Info, AddressSpaceParam->getAddrSpaceExpr());
2065 if (!NTTP)
2066 return Sema::TDK_Success;
2067
2068 return DeduceNonTypeTemplateArgument(
2069 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2070 Deduced);
2071 }
2072
Alexander Richardson6d989432017-10-15 18:48:14 +00002073 if (isTargetAddressSpace(Arg.getAddressSpace())) {
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002074 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2075 false);
Alexander Richardson6d989432017-10-15 18:48:14 +00002076 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002077
2078 // Perform deduction on the pointer types.
2079 if (Sema::TemplateDeductionResult Result =
2080 DeduceTemplateArgumentsByTypeMatch(
2081 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2082 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2083 return Result;
2084
2085 // Perform deduction on the address space, if we can.
2086 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2087 Info, AddressSpaceParam->getAddrSpaceExpr());
2088 if (!NTTP)
2089 return Sema::TDK_Success;
2090
2091 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2092 ArgAddressSpace, S.Context.IntTy,
2093 true, Info, Deduced);
2094 }
2095
2096 return Sema::TDK_NonDeducedMismatch;
2097 }
2098
Douglas Gregor637d9982009-06-10 23:47:09 +00002099 case Type::TypeOfExpr:
2100 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002101 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00002102 case Type::UnresolvedUsing:
2103 case Type::Decltype:
2104 case Type::UnaryTransform:
2105 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002106 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00002107 case Type::DependentTemplateSpecialization:
2108 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002109 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00002110 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002111 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002112 }
2113
David Blaikiee4d798f2012-01-20 21:50:17 +00002114 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002115}
2116
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002117static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002118DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002119 TemplateParameterList *TemplateParams,
2120 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002121 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00002122 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002123 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002124 // If the template argument is a pack expansion, perform template argument
2125 // deduction against the pattern of that expansion. This only occurs during
2126 // partial ordering.
2127 if (Arg.isPackExpansion())
2128 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002130 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002131 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002132 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00002133
2134 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002135 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00002136 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2137 Param.getAsType(),
2138 Arg.getAsType(),
2139 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002140 Info.FirstArg = Param;
2141 Info.SecondArg = Arg;
2142 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002143
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002144 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00002145 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002147 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00002148 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002149 Info.FirstArg = Param;
2150 Info.SecondArg = Arg;
2151 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002152
2153 case TemplateArgument::TemplateExpansion:
2154 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002155
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002156 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002157 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00002158 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00002159 return Sema::TDK_Success;
2160
2161 Info.FirstArg = Param;
2162 Info.SecondArg = Arg;
2163 return Sema::TDK_NonDeducedMismatch;
2164
2165 case TemplateArgument::NullPtr:
2166 if (Arg.getKind() == TemplateArgument::NullPtr &&
2167 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002168 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002170 Info.FirstArg = Param;
2171 Info.SecondArg = Arg;
2172 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002174 case TemplateArgument::Integral:
2175 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002176 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002177 return Sema::TDK_Success;
2178
2179 Info.FirstArg = Param;
2180 Info.SecondArg = Arg;
2181 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002182 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002183
2184 if (Arg.getKind() == TemplateArgument::Expression) {
2185 Info.FirstArg = Param;
2186 Info.SecondArg = Arg;
2187 return Sema::TDK_NonDeducedMismatch;
2188 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002189
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002190 Info.FirstArg = Param;
2191 Info.SecondArg = Arg;
2192 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002193
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002194 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00002195 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002196 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002197 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00002198 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002199 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00002200 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002201 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002202 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00002203 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00002204 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2205 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00002206 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002207 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00002208 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2209 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002210 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00002211 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2212 Arg.getAsDecl(),
2213 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002214 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002215
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002216 Info.FirstArg = Param;
2217 Info.SecondArg = Arg;
2218 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002219 }
Mike Stump11289f42009-09-09 15:08:12 +00002220
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002221 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002222 return Sema::TDK_Success;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002223
Anders Carlssonbc343912009-06-15 17:04:53 +00002224 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00002225 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002226 }
Mike Stump11289f42009-09-09 15:08:12 +00002227
David Blaikiee4d798f2012-01-20 21:50:17 +00002228 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002229}
2230
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002231/// Determine whether there is a template argument to be used for
Douglas Gregor7baabef2010-12-22 18:17:10 +00002232/// deduction.
2233///
2234/// This routine "expands" argument packs in-place, overriding its input
2235/// parameters so that \c Args[ArgIdx] will be the available template argument.
2236///
2237/// \returns true if there is another template argument (which will be at
2238/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00002239static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2240 unsigned &ArgIdx) {
2241 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00002242 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243
Douglas Gregor7baabef2010-12-22 18:17:10 +00002244 const TemplateArgument &Arg = Args[ArgIdx];
2245 if (Arg.getKind() != TemplateArgument::Pack)
2246 return true;
2247
Richard Smith0bda5b52016-12-23 23:46:56 +00002248 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2249 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002250 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002251 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002252}
2253
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002254/// Determine whether the given set of template arguments has a pack
Douglas Gregord0ad2942010-12-23 01:24:45 +00002255/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00002256static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2257 bool FoundPackExpansion = false;
2258 for (const auto &A : Args) {
2259 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00002260 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00002261
2262 if (A.getKind() == TemplateArgument::Pack)
2263 return hasPackExpansionBeforeEnd(A.pack_elements());
2264
Richard Smith4a8f3512018-07-19 19:00:37 +00002265 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2266 // templates, it should not be treated as a pack expansion.
Richard Smith0bda5b52016-12-23 23:46:56 +00002267 if (A.isPackExpansion())
2268 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00002269 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002270
Douglas Gregord0ad2942010-12-23 01:24:45 +00002271 return false;
2272}
2273
Douglas Gregor7baabef2010-12-22 18:17:10 +00002274static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002275DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00002276 ArrayRef<TemplateArgument> Params,
2277 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002278 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002279 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2280 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002281 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282 // If the template argument list of P contains a pack expansion that is not
2283 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002284 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00002285 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00002286 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002287
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002288 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289 // If P has a form that contains <T> or <i>, then each argument Pi of the
2290 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002291 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002292 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002293 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00002294 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002295 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002296
Douglas Gregor7baabef2010-12-22 18:17:10 +00002297 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00002298 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002299 return NumberOfArgumentsMustMatch
2300 ? Sema::TDK_MiscellaneousDeductionFailure
2301 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302
Richard Smith26b86ea2016-12-31 21:41:23 +00002303 // C++1z [temp.deduct.type]p9:
2304 // During partial ordering, if Ai was originally a pack expansion [and]
2305 // Pi is not a pack expansion, template argument deduction fails.
2306 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002307 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002309 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002310 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002311 = DeduceTemplateArguments(S, TemplateParams,
2312 Params[ParamIdx], Args[ArgIdx],
2313 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002314 return Result;
2315
Douglas Gregor7baabef2010-12-22 18:17:10 +00002316 // Move to the next argument.
2317 ++ArgIdx;
2318 continue;
2319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002320
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002321 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002322
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002323 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324 // If Pi is a pack expansion, then the pattern of Pi is compared with
2325 // each remaining argument in the template argument list of A. Each
2326 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002327 // template parameter packs expanded by Pi.
2328 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329
Richard Smith0a80d572014-05-29 01:12:14 +00002330 // Prepare to deduce the packs within the pattern.
2331 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002332
2333 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002334 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002335 // template argument (the inner SmallVectors).
Richard Smith4a8f3512018-07-19 19:00:37 +00002336 for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2337 PackScope.hasNextElement();
2338 ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002339 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002340 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002341 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2342 Info, Deduced))
2343 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344
Richard Smith0a80d572014-05-29 01:12:14 +00002345 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002348 // Build argument packs for each of the parameter packs expanded by this
2349 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002350 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002351 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002353
Douglas Gregor7baabef2010-12-22 18:17:10 +00002354 return Sema::TDK_Success;
2355}
2356
Mike Stump11289f42009-09-09 15:08:12 +00002357static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002358DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002359 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002360 const TemplateArgumentList &ParamList,
2361 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002362 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002363 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002364 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002365 ArgList.asArray(), Info, Deduced,
2366 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002367}
2368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002369/// Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002370static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002371 TemplateArgument X,
2372 const TemplateArgument &Y,
2373 bool PackExpansionMatchesPack = false) {
2374 // If we're checking deduced arguments (X) against original arguments (Y),
2375 // we will have flattened packs to non-expansions in X.
2376 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2377 X = X.getPackExpansionPattern();
2378
Douglas Gregor705c9002009-06-26 20:57:09 +00002379 if (X.getKind() != Y.getKind())
2380 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002381
Douglas Gregor705c9002009-06-26 20:57:09 +00002382 switch (X.getKind()) {
2383 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002384 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002385
Douglas Gregor705c9002009-06-26 20:57:09 +00002386 case TemplateArgument::Type:
2387 return Context.getCanonicalType(X.getAsType()) ==
2388 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002389
Douglas Gregor705c9002009-06-26 20:57:09 +00002390 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002391 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002392
2393 case TemplateArgument::NullPtr:
2394 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002395
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002396 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002397 case TemplateArgument::TemplateExpansion:
2398 return Context.getCanonicalTemplateName(
2399 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2400 Context.getCanonicalTemplateName(
2401 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002402
Douglas Gregor705c9002009-06-26 20:57:09 +00002403 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002404 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002405
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002406 case TemplateArgument::Expression: {
2407 llvm::FoldingSetNodeID XID, YID;
2408 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002409 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002410 return XID == YID;
2411 }
Mike Stump11289f42009-09-09 15:08:12 +00002412
Douglas Gregor705c9002009-06-26 20:57:09 +00002413 case TemplateArgument::Pack:
2414 if (X.pack_size() != Y.pack_size())
2415 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002416
2417 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2418 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002419 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002420 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002421 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002422 return false;
2423
2424 return true;
2425 }
2426
David Blaikiee4d798f2012-01-20 21:50:17 +00002427 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002428}
2429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002430/// Allocate a TemplateArgumentLoc where all locations have
Douglas Gregorca4686d2011-01-04 23:35:54 +00002431/// been initialized to the given location.
2432///
James Dennett634962f2012-06-14 21:40:34 +00002433/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002434/// location information for.
2435///
2436/// \param NTTPType For a declaration template argument, the type of
2437/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002438/// argument. Can be null if no type sugar is available to add to the
2439/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002440///
2441/// \param Loc The source location to use for the resulting template
2442/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002443TemplateArgumentLoc
2444Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2445 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002446 switch (Arg.getKind()) {
2447 case TemplateArgument::Null:
2448 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449
Douglas Gregorca4686d2011-01-04 23:35:54 +00002450 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002451 return TemplateArgumentLoc(
2452 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002453
Douglas Gregorca4686d2011-01-04 23:35:54 +00002454 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002455 if (NTTPType.isNull())
2456 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002457 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2458 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002459 return TemplateArgumentLoc(TemplateArgument(E), E);
2460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002461
Eli Friedmanb826a002012-09-26 02:36:12 +00002462 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002463 if (NTTPType.isNull())
2464 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002465 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2466 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002467 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2468 E);
2469 }
2470
Douglas Gregorca4686d2011-01-04 23:35:54 +00002471 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002472 Expr *E =
2473 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002474 return TemplateArgumentLoc(TemplateArgument(E), E);
2475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002476
Douglas Gregor9d802122011-03-02 17:09:35 +00002477 case TemplateArgument::Template:
2478 case TemplateArgument::TemplateExpansion: {
2479 NestedNameSpecifierLocBuilder Builder;
2480 TemplateName Template = Arg.getAsTemplate();
2481 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002482 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002483 else if (QualifiedTemplateName *QTN =
2484 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002485 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002486
Douglas Gregor9d802122011-03-02 17:09:35 +00002487 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002488 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002489 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002490
2491 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002492 Loc, Loc);
2493 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002494
Douglas Gregorca4686d2011-01-04 23:35:54 +00002495 case TemplateArgument::Expression:
2496 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002497
Douglas Gregorca4686d2011-01-04 23:35:54 +00002498 case TemplateArgument::Pack:
2499 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002501
David Blaikiee4d798f2012-01-20 21:50:17 +00002502 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002503}
2504
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002505/// Convert the given deduced template argument and add it to the set of
Douglas Gregorca4686d2011-01-04 23:35:54 +00002506/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002507static bool
2508ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2509 DeducedTemplateArgument Arg,
2510 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002511 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002512 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002513 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002514 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2515 unsigned ArgumentPackIndex) {
2516 // Convert the deduced template argument into a template
2517 // argument that we can check, almost as if the user had written
2518 // the template argument explicitly.
2519 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002520 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002521
2522 // Check the template argument, converting it as necessary.
2523 return S.CheckTemplateArgument(
2524 Param, ArgLoc, Template, Template->getLocation(),
2525 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002526 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002527 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2528 : Sema::CTAK_Deduced)
2529 : Sema::CTAK_Specified);
2530 };
2531
Douglas Gregorca4686d2011-01-04 23:35:54 +00002532 if (Arg.getKind() == TemplateArgument::Pack) {
2533 // This is a template argument pack, so check each of its arguments against
2534 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002536 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002537 // When converting the deduced template argument, append it to the
2538 // general output list. We need to do this so that the template argument
2539 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002540 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002541 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002542 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2543 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002544 if (P.isNull()) {
2545 // We deduced arguments for some elements of this pack, but not for
2546 // all of them. This happens if we get a conditionally-non-deduced
2547 // context in a pack expansion (such as an overload set in one of the
2548 // arguments).
2549 S.Diag(Param->getLocation(),
2550 diag::err_template_arg_deduced_incomplete_pack)
2551 << Arg << Param;
2552 return true;
2553 }
Richard Smith37acb792016-02-03 20:15:01 +00002554 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002555 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556
Douglas Gregor51bc5712011-01-05 20:52:18 +00002557 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002558 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560
Richard Smithdf18ee92016-02-03 20:40:30 +00002561 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002562 // itself, in case that substitution fails.
2563 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002564 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002565 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002566 MultiLevelTemplateArgumentList Args(TemplateArgs);
2567
2568 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2569 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2570 NTTP, Output,
2571 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002572 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002573 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2574 NTTP->getDeclName()).isNull())
2575 return true;
2576 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2577 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2578 TTP, Output,
2579 Template->getSourceRange());
2580 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2581 return true;
2582 }
2583 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002584 }
Richard Smith37acb792016-02-03 20:15:01 +00002585
Douglas Gregorca4686d2011-01-04 23:35:54 +00002586 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002587 Output.push_back(
2588 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002589 return false;
2590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002591
Richard Smith37acb792016-02-03 20:15:01 +00002592 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002593}
2594
Richard Smith1f5be4d2016-12-21 01:10:31 +00002595// FIXME: This should not be a template, but
2596// ClassTemplatePartialSpecializationDecl sadly does not derive from
2597// TemplateDecl.
2598template<typename TemplateDeclT>
2599static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002600 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002601 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2602 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2603 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002604 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002605 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2606
2607 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2608 NamedDecl *Param = TemplateParams->getParam(I);
2609
Richard Smith4a8f3512018-07-19 19:00:37 +00002610 // C++0x [temp.arg.explicit]p3:
2611 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2612 // be deduced to an empty sequence of template arguments.
2613 // FIXME: Where did the word "trailing" come from?
2614 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2615 if (auto Result = PackDeductionScope(S, TemplateParams, Deduced, Info, I)
2616 .finish(/*TreatNoDeductionsAsNonDeduced*/false))
2617 return Result;
2618 }
2619
Richard Smith1f5be4d2016-12-21 01:10:31 +00002620 if (!Deduced[I].isNull()) {
2621 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002622 // We may have had explicitly-specified template arguments for a
2623 // template parameter pack (that may or may not have been extended
2624 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002625 if (Param->isParameterPack() && CurrentInstantiationScope &&
2626 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2627 // Forget the partially-substituted pack; its substitution is now
2628 // complete.
2629 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2630 // We still need to check the argument in case it was extended by
2631 // deduction.
2632 } else {
2633 // We have already fully type-checked and converted this
2634 // argument, because it was explicitly-specified. Just record the
2635 // presence of this argument.
2636 Builder.push_back(Deduced[I]);
2637 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002638 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002639 }
2640
Richard Smith9c0c9862017-01-05 20:27:28 +00002641 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002642 // checked and converted.
2643 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002644 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002645 Info.Param = makeTemplateParameter(Param);
2646 // FIXME: These template arguments are temporary. Free them!
2647 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2648 return Sema::TDK_SubstitutionFailure;
2649 }
2650
2651 continue;
2652 }
2653
Richard Smith1f5be4d2016-12-21 01:10:31 +00002654 // Substitute into the default template argument, if available.
2655 bool HasDefaultArg = false;
2656 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2657 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002658 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2659 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002660 return Sema::TDK_Incomplete;
2661 }
2662
2663 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2664 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2665 HasDefaultArg);
2666
2667 // If there was no default argument, deduction is incomplete.
2668 if (DefArg.getArgument().isNull()) {
2669 Info.Param = makeTemplateParameter(
2670 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2671 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002672 if (PartialOverloading) break;
2673
Richard Smith1f5be4d2016-12-21 01:10:31 +00002674 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2675 : Sema::TDK_Incomplete;
2676 }
2677
2678 // Check whether we can actually use the default argument.
2679 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2680 TD->getSourceRange().getEnd(), 0, Builder,
2681 Sema::CTAK_Specified)) {
2682 Info.Param = makeTemplateParameter(
2683 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2684 // FIXME: These template arguments are temporary. Free them!
2685 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2686 return Sema::TDK_SubstitutionFailure;
2687 }
2688
2689 // If we get here, we successfully used the default template argument.
2690 }
2691
2692 return Sema::TDK_Success;
2693}
2694
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002695static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002696 if (auto *DC = dyn_cast<DeclContext>(D))
2697 return DC;
2698 return D->getDeclContext();
2699}
2700
2701template<typename T> struct IsPartialSpecialization {
2702 static constexpr bool value = false;
2703};
2704template<>
2705struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2706 static constexpr bool value = true;
2707};
2708template<>
2709struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2710 static constexpr bool value = true;
2711};
2712
2713/// Complete template argument deduction for a partial specialization.
2714template <typename T>
2715static typename std::enable_if<IsPartialSpecialization<T>::value,
2716 Sema::TemplateDeductionResult>::type
2717FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002718 Sema &S, T *Partial, bool IsPartialOrdering,
2719 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002720 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2721 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002722 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002723 EnterExpressionEvaluationContext Unevaluated(
2724 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002725 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726
Richard Smith0da6dc42016-12-24 16:40:51 +00002727 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002728
2729 // C++ [temp.deduct.type]p2:
2730 // [...] or if any template argument remains neither deduced nor
2731 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002732 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002733 if (auto Result = ConvertDeducedTemplateArguments(
2734 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002735 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002736
Douglas Gregor684268d2010-04-29 06:21:43 +00002737 // Form the template argument list from the deduced template arguments.
2738 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002739 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002740
Douglas Gregor684268d2010-04-29 06:21:43 +00002741 Info.reset(DeducedArgumentList);
2742
2743 // Substitute the deduced template arguments into the template
2744 // arguments of the class template partial specialization, and
2745 // verify that the instantiated template arguments are both valid
2746 // and are equivalent to the template arguments originally provided
2747 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002748 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002749 auto *Template = Partial->getSpecializedTemplate();
2750 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2751 Partial->getTemplateArgsAsWritten();
2752 const TemplateArgumentLoc *PartialTemplateArgs =
2753 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002754
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002755 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2756 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002757
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002758 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002759 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2760 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2761 if (ParamIdx >= Partial->getTemplateParameters()->size())
2762 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2763
Richard Smith0da6dc42016-12-24 16:40:51 +00002764 Decl *Param = const_cast<NamedDecl *>(
2765 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002766 Info.Param = makeTemplateParameter(Param);
2767 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2768 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002769 }
2770
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002771 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002772 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2773 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002774 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775
Richard Smith0da6dc42016-12-24 16:40:51 +00002776 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002777 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002778 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002779 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002780 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002781 Info.FirstArg = TemplateArgs[I];
2782 Info.SecondArg = InstArg;
2783 return Sema::TDK_NonDeducedMismatch;
2784 }
2785 }
2786
2787 if (Trap.hasErrorOccurred())
2788 return Sema::TDK_SubstitutionFailure;
2789
2790 return Sema::TDK_Success;
2791}
2792
Richard Smith0e617ec2016-12-27 07:56:27 +00002793/// Complete template argument deduction for a class or variable template,
2794/// when partial ordering against a partial specialization.
2795// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002796static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002797 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2798 const TemplateArgumentList &TemplateArgs,
2799 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2800 TemplateDeductionInfo &Info) {
2801 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002802 EnterExpressionEvaluationContext Unevaluated(
2803 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002804 Sema::SFINAETrap Trap(S);
2805
2806 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2807
2808 // C++ [temp.deduct.type]p2:
2809 // [...] or if any template argument remains neither deduced nor
2810 // explicitly specified, template argument deduction fails.
2811 SmallVector<TemplateArgument, 4> Builder;
2812 if (auto Result = ConvertDeducedTemplateArguments(
2813 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2814 return Result;
2815
2816 // Check that we produced the correct argument list.
2817 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2818 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2819 TemplateArgument InstArg = Builder[I];
2820 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2821 /*PackExpansionMatchesPack*/true)) {
2822 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2823 Info.FirstArg = TemplateArgs[I];
2824 Info.SecondArg = InstArg;
2825 return Sema::TDK_NonDeducedMismatch;
2826 }
2827 }
2828
2829 if (Trap.hasErrorOccurred())
2830 return Sema::TDK_SubstitutionFailure;
2831
2832 return Sema::TDK_Success;
2833}
2834
2835
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002836/// Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002837/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002838/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002839Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002840Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002841 const TemplateArgumentList &TemplateArgs,
2842 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002843 if (Partial->isInvalidDecl())
2844 return TDK_Invalid;
2845
Douglas Gregor170bc422009-06-12 22:31:52 +00002846 // C++ [temp.class.spec.match]p2:
2847 // A partial specialization matches a given actual template
2848 // argument list if the template arguments of the partial
2849 // specialization can be deduced from the actual template argument
2850 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002851
2852 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002853 EnterExpressionEvaluationContext Unevaluated(
2854 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002855 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002856
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002857 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002858 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002859 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002860 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002861 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002862 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002863 TemplateArgs, Info, Deduced))
2864 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002865
Richard Smith80934652012-07-16 01:09:10 +00002866 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002867 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2868 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002869 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002870 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002871
Douglas Gregore1416332009-06-14 08:02:22 +00002872 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002873 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002874
Richard Smith87d263e2016-12-25 08:05:23 +00002875 return ::FinishTemplateArgumentDeduction(
2876 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002877}
Douglas Gregor91772d12009-06-13 00:26:55 +00002878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002879/// Perform template argument deduction to determine whether
Larisse Voufo39a1e502013-08-06 01:03:05 +00002880/// the given template arguments match the given variable template
2881/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002882Sema::TemplateDeductionResult
2883Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2884 const TemplateArgumentList &TemplateArgs,
2885 TemplateDeductionInfo &Info) {
2886 if (Partial->isInvalidDecl())
2887 return TDK_Invalid;
2888
2889 // C++ [temp.class.spec.match]p2:
2890 // A partial specialization matches a given actual template
2891 // argument list if the template arguments of the partial
2892 // specialization can be deduced from the actual template argument
2893 // list (14.8.2).
2894
2895 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002896 EnterExpressionEvaluationContext Unevaluated(
2897 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002898 SFINAETrap Trap(*this);
2899
2900 SmallVector<DeducedTemplateArgument, 4> Deduced;
2901 Deduced.resize(Partial->getTemplateParameters()->size());
2902 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2903 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2904 TemplateArgs, Info, Deduced))
2905 return Result;
2906
2907 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002908 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2909 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002910 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002911 return TDK_InstantiationDepth;
2912
2913 if (Trap.hasErrorOccurred())
2914 return Sema::TDK_SubstitutionFailure;
2915
Richard Smith87d263e2016-12-25 08:05:23 +00002916 return ::FinishTemplateArgumentDeduction(
2917 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002918}
2919
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002920/// Determine whether the given type T is a simple-template-id type.
Douglas Gregorfc516c92009-06-26 23:27:24 +00002921static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002922 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002923 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002924 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002925
Richard Smith1363e8f2017-09-07 07:22:36 +00002926 // C++17 [temp.local]p2:
2927 // the injected-class-name [...] is equivalent to the template-name followed
2928 // by the template-arguments of the class template specialization or partial
2929 // specialization enclosed in <>
2930 // ... which means it's equivalent to a simple-template-id.
2931 //
2932 // This only arises during class template argument deduction for a copy
2933 // deduction candidate, where it permits slicing.
2934 if (T->getAs<InjectedClassNameType>())
2935 return true;
2936
Douglas Gregorfc516c92009-06-26 23:27:24 +00002937 return false;
2938}
Douglas Gregor9b146582009-07-08 20:55:45 +00002939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002940/// Substitute the explicitly-provided template arguments into the
Douglas Gregor9b146582009-07-08 20:55:45 +00002941/// given function template according to C++ [temp.arg.explicit].
2942///
2943/// \param FunctionTemplate the function template into which the explicit
2944/// template arguments will be substituted.
2945///
James Dennett634962f2012-06-14 21:40:34 +00002946/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002947/// arguments.
2948///
Mike Stump11289f42009-09-09 15:08:12 +00002949/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002950/// with the converted and checked explicit template arguments.
2951///
Mike Stump11289f42009-09-09 15:08:12 +00002952/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002953/// parameters.
2954///
2955/// \param FunctionType if non-NULL, the result type of the function template
2956/// will also be instantiated and the pointed-to value will be updated with
2957/// the instantiated function type.
2958///
2959/// \param Info if substitution fails for any reason, this object will be
2960/// populated with more information about the failure.
2961///
2962/// \returns TDK_Success if substitution was successful, or some failure
2963/// condition.
2964Sema::TemplateDeductionResult
2965Sema::SubstituteExplicitTemplateArguments(
2966 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002967 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002968 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2969 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002970 QualType *FunctionType,
2971 TemplateDeductionInfo &Info) {
2972 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2973 TemplateParameterList *TemplateParams
2974 = FunctionTemplate->getTemplateParameters();
2975
John McCall6b51f282009-11-23 01:53:49 +00002976 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002977 // No arguments to substitute; just copy over the parameter types and
2978 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002979 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002980 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002981
Douglas Gregor9b146582009-07-08 20:55:45 +00002982 if (FunctionType)
2983 *FunctionType = Function->getType();
2984 return TDK_Success;
2985 }
Mike Stump11289f42009-09-09 15:08:12 +00002986
Eli Friedman77dcc722012-02-08 03:07:05 +00002987 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002988 EnterExpressionEvaluationContext Unevaluated(
2989 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002990 SFINAETrap Trap(*this);
2991
Douglas Gregor9b146582009-07-08 20:55:45 +00002992 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002993 // Template arguments that are present shall be specified in the
2994 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002995 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002996 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002997 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002998
2999 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00003000 // explicitly-specified template arguments against this function template,
3001 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00003002 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00003003 InstantiatingTemplate Inst(
3004 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3005 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003006 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00003007 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00003008
Richard Smith11255ec2017-01-18 19:19:22 +00003009 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3010 ExplicitTemplateArgs, true, Builder, false) ||
3011 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003012 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00003013 if (Index >= TemplateParams->size())
Richard Smith4a8f3512018-07-19 19:00:37 +00003014 return TDK_SubstitutionFailure;
Douglas Gregor62c281a2010-05-09 01:26:06 +00003015 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00003016 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00003017 }
Mike Stump11289f42009-09-09 15:08:12 +00003018
Douglas Gregor9b146582009-07-08 20:55:45 +00003019 // Form the template argument list from the explicitly-specified
3020 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003021 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003022 = TemplateArgumentList::CreateCopy(Context, Builder);
Richard Smith4a8f3512018-07-19 19:00:37 +00003023 Info.setExplicitArgs(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024
John McCall036855a2010-10-12 19:40:14 +00003025 // Template argument deduction and the final substitution should be
3026 // done in the context of the templated declaration. Explicit
3027 // argument substitution, on the other hand, needs to happen in the
3028 // calling context.
3029 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3030
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003032 // note that the template argument pack is partially substituted and record
3033 // the explicit template arguments. They'll be used as part of deduction
3034 // for this template parameter pack.
Richard Smith4a8f3512018-07-19 19:00:37 +00003035 unsigned PartiallySubstitutedPackIndex = -1u;
3036 if (!Builder.empty()) {
3037 const TemplateArgument &Arg = Builder.back();
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003038 if (Arg.getKind() == TemplateArgument::Pack) {
Richard Smith4a8f3512018-07-19 19:00:37 +00003039 auto *Param = TemplateParams->getParam(Builder.size() - 1);
3040 // If this is a fully-saturated fixed-size pack, it should be
3041 // fully-substituted, not partially-substituted.
3042 Optional<unsigned> Expansions = getExpandedPackSize(Param);
3043 if (!Expansions || Arg.pack_size() < *Expansions) {
3044 PartiallySubstitutedPackIndex = Builder.size() - 1;
3045 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3046 Param, Arg.pack_begin(), Arg.pack_size());
3047 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003048 }
3049 }
3050
Richard Smith5e580292012-02-10 09:58:53 +00003051 const FunctionProtoType *Proto
3052 = Function->getType()->getAs<FunctionProtoType>();
3053 assert(Proto && "Function template does not have a prototype?");
3054
Richard Smith70b13042015-01-09 01:19:56 +00003055 // Isolate our substituted parameters from our caller.
3056 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3057
John McCallc8e321d2016-03-01 02:09:25 +00003058 ExtParameterInfoBuilder ExtParamInfos;
3059
Douglas Gregor9b146582009-07-08 20:55:45 +00003060 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00003061 // explicitly-specified template arguments. If the function has a trailing
3062 // return type, substitute it after the arguments to ensure we substitute
3063 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00003064 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00003065 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00003066 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003067 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00003068 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00003069 return TDK_SubstitutionFailure;
3070 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003071
Richard Smith5e580292012-02-10 09:58:53 +00003072 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00003073 QualType ResultType;
3074 {
3075 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003076 // If a declaration declares a member function or member function
3077 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00003078 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00003079 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00003080 // declarator.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003081 Qualifiers ThisTypeQuals;
Craig Topperc3ec1492014-05-26 06:22:03 +00003082 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00003083 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3084 ThisContext = Method->getParent();
3085 ThisTypeQuals = Method->getTypeQualifiers();
3086 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003087
Douglas Gregor3024f072012-04-16 07:05:22 +00003088 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003089 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00003090
3091 ResultType =
3092 SubstType(Proto->getReturnType(),
3093 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3094 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00003095 if (ResultType.isNull() || Trap.hasErrorOccurred())
3096 return TDK_SubstitutionFailure;
3097 }
John McCallc8e321d2016-03-01 02:09:25 +00003098
Richard Smith5e580292012-02-10 09:58:53 +00003099 // Instantiate the types of each of the function parameters given the
3100 // explicitly-specified template arguments if we didn't do so earlier.
3101 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00003102 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00003103 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00003104 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00003105 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00003106 return TDK_SubstitutionFailure;
3107
Douglas Gregor9b146582009-07-08 20:55:45 +00003108 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00003109 auto EPI = Proto->getExtProtoInfo();
3110 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Richard Smithcd198152017-06-07 21:46:22 +00003111
3112 // In C++1z onwards, exception specifications are part of the function type,
3113 // so substitution into the type must also substitute into the exception
3114 // specification.
3115 SmallVector<QualType, 4> ExceptionStorage;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003116 if (getLangOpts().CPlusPlus17 &&
Richard Smithcd198152017-06-07 21:46:22 +00003117 SubstExceptionSpec(
3118 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3119 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3120 return TDK_SubstitutionFailure;
3121
Jordan Rose5c382722013-03-08 21:51:21 +00003122 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003123 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00003124 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00003125 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00003126 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3127 return TDK_SubstitutionFailure;
3128 }
Mike Stump11289f42009-09-09 15:08:12 +00003129
Douglas Gregor9b146582009-07-08 20:55:45 +00003130 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003131 // Trailing template arguments that can be deduced (14.8.2) may be
3132 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00003133 // template arguments can be deduced, they may all be omitted; in this
3134 // case, the empty template argument list <> itself may also be omitted.
3135 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003136 // Take all of the explicitly-specified arguments and put them into
Richard Smith4a8f3512018-07-19 19:00:37 +00003137 // the set of deduced template arguments. The partially-substituted
3138 // parameter pack, however, will be set to NULL since the deduction
3139 // mechanism handles the partially-substituted argument pack directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00003140 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003141 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3142 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
Richard Smith4a8f3512018-07-19 19:00:37 +00003143 if (I == PartiallySubstitutedPackIndex)
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003144 Deduced.push_back(DeducedTemplateArgument());
3145 else
3146 Deduced.push_back(Arg);
3147 }
Mike Stump11289f42009-09-09 15:08:12 +00003148
Douglas Gregor9b146582009-07-08 20:55:45 +00003149 return TDK_Success;
3150}
3151
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003152/// Check whether the deduced argument type for a call to a function
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003153/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Richard Smithb1efc9b2017-08-30 00:44:08 +00003154static Sema::TemplateDeductionResult
3155CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3156 Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003157 QualType DeducedA) {
3158 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003159
Richard Smithb1efc9b2017-08-30 00:44:08 +00003160 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3161 Info.FirstArg = TemplateArgument(DeducedA);
3162 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3163 Info.CallArgIndex = OriginalArg.ArgIdx;
3164 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3165 : Sema::TDK_DeducedMismatch;
3166 };
3167
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003168 QualType A = OriginalArg.OriginalArgType;
3169 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003170
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003171 // Check for type equality (top-level cv-qualifiers are ignored).
3172 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003173 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003174
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003175 // Strip off references on the argument types; they aren't needed for
3176 // the following checks.
3177 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3178 DeducedA = DeducedARef->getPointeeType();
3179 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3180 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003181
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003182 // C++ [temp.deduct.call]p4:
3183 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003184 // - If the original P is a reference type, the deduced A (i.e., the
3185 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003186 // the transformed A.
3187 if (const ReferenceType *OriginalParamRef
3188 = OriginalParamType->getAs<ReferenceType>()) {
3189 // We don't want to keep the reference around any more.
3190 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003191
Richard Smith1be59c52016-10-22 01:32:19 +00003192 // FIXME: Resolve core issue (no number yet): if the original P is a
3193 // reference type and the transformed A is function type "noexcept F",
3194 // the deduced A can be F.
3195 QualType Tmp;
3196 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003197 return Sema::TDK_Success;
Richard Smith1be59c52016-10-22 01:32:19 +00003198
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003199 Qualifiers AQuals = A.getQualifiers();
3200 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00003201
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003202 // Under Objective-C++ ARC, the deduced type may have implicitly
3203 // been given strong or (when dealing with a const reference)
3204 // unsafe_unretained lifetime. If so, update the original
3205 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00003206 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003207 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3208 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3209 (DeducedAQuals.hasConst() &&
3210 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3211 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00003212 }
3213
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003214 if (AQuals == DeducedAQuals) {
3215 // Qualifiers match; there's nothing to do.
3216 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00003217 return Failed();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003218 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003219 // Qualifiers are compatible, so have the argument type adopt the
3220 // deduced argument type's qualifiers as if we had performed the
3221 // qualification conversion.
3222 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3223 }
3224 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003225
3226 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00003227 // type that can be converted to the deduced A via a function pointer
3228 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00003229 //
Richard Smith1be59c52016-10-22 01:32:19 +00003230 // Also allow conversions which merely strip __attribute__((noreturn)) from
3231 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003232 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00003233 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003234 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00003235 (S.IsQualificationConversion(A, DeducedA, false,
3236 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00003237 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003238 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003239
Simon Pilgrim728134c2016-08-12 11:43:57 +00003240 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003241 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003242 // [...] Likewise, if P is a pointer to a class of the form
3243 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003244 // derived class pointed to by the deduced A.
3245 if (const PointerType *OriginalParamPtr
3246 = OriginalParamType->getAs<PointerType>()) {
3247 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3248 if (const PointerType *APtr = A->getAs<PointerType>()) {
3249 if (A->getPointeeType()->isRecordType()) {
3250 OriginalParamType = OriginalParamPtr->getPointeeType();
3251 DeducedA = DeducedAPtr->getPointeeType();
3252 A = APtr->getPointeeType();
3253 }
3254 }
3255 }
3256 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003257
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003258 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003259 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003260
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003261 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith148bc6a2018-02-20 23:47:12 +00003262 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003263 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003264
Richard Smithb1efc9b2017-08-30 00:44:08 +00003265 return Failed();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003266}
3267
Richard Smithc92d2062017-01-05 23:02:44 +00003268/// Find the pack index for a particular parameter index in an instantiation of
3269/// a function template with specific arguments.
3270///
3271/// \return The pack index for whichever pack produced this parameter, or -1
3272/// if this was not produced by a parameter. Intended to be used as the
3273/// ArgumentPackSubstitutionIndex for further substitutions.
3274// FIXME: We should track this in OriginalCallArgs so we don't need to
3275// reconstruct it here.
3276static unsigned getPackIndexForParam(Sema &S,
3277 FunctionTemplateDecl *FunctionTemplate,
3278 const MultiLevelTemplateArgumentList &Args,
3279 unsigned ParamIdx) {
3280 unsigned Idx = 0;
3281 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3282 if (PD->isParameterPack()) {
3283 unsigned NumExpansions =
3284 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3285 if (Idx + NumExpansions > ParamIdx)
3286 return ParamIdx - Idx;
3287 Idx += NumExpansions;
3288 } else {
3289 if (Idx == ParamIdx)
3290 return -1; // Not a pack expansion
3291 ++Idx;
3292 }
3293 }
3294
3295 llvm_unreachable("parameter index would not be produced from template");
3296}
3297
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003298/// Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003299/// checking the deduced template arguments for completeness and forming
3300/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00003301///
3302/// \param OriginalCallArgs If non-NULL, the original call arguments against
3303/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00003304Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3305 FunctionTemplateDecl *FunctionTemplate,
3306 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3307 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3308 TemplateDeductionInfo &Info,
3309 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3310 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003311 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003312 EnterExpressionEvaluationContext Unevaluated(
3313 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003314 SFINAETrap Trap(*this);
3315
Douglas Gregor9b146582009-07-08 20:55:45 +00003316 // Enter a new template instantiation context while we instantiate the
3317 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003318 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003319 InstantiatingTemplate Inst(
3320 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3321 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003322 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003323 return TDK_InstantiationDepth;
3324
John McCalle23b8712010-04-29 01:18:58 +00003325 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003326
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003327 // C++ [temp.deduct.type]p2:
3328 // [...] or if any template argument remains neither deduced nor
3329 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003330 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003331 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003332 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003333 CurrentInstantiationScope, NumExplicitlySpecified,
3334 PartialOverloading))
3335 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003336
Richard Smith6eedfe72017-01-09 08:01:21 +00003337 // C++ [temp.deduct.call]p10: [DR1391]
3338 // If deduction succeeds for all parameters that contain
3339 // template-parameters that participate in template argument deduction,
3340 // and all template arguments are explicitly specified, deduced, or
3341 // obtained from default template arguments, remaining parameters are then
3342 // compared with the corresponding arguments. For each remaining parameter
3343 // P with a type that was non-dependent before substitution of any
3344 // explicitly-specified template arguments, if the corresponding argument
3345 // A cannot be implicitly converted to P, deduction fails.
3346 if (CheckNonDependent())
3347 return TDK_NonDependentConversionFailure;
3348
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003349 // Form the template argument list from the deduced template arguments.
3350 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003351 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003352 Info.reset(DeducedArgumentList);
3353
Mike Stump11289f42009-09-09 15:08:12 +00003354 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003355 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003356 DeclContext *Owner = FunctionTemplate->getDeclContext();
3357 if (FunctionTemplate->getFriendObjectKind())
3358 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003359 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003360 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003361 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003362 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003363 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003364
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003366 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
Mike Stump11289f42009-09-09 15:08:12 +00003368 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003369 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003370 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3371 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003372 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003373
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003374 // There may have been an error that did not prevent us from constructing a
3375 // declaration. Mark the declaration invalid and return with a substitution
3376 // failure.
3377 if (Trap.hasErrorOccurred()) {
3378 Specialization->setInvalidDecl(true);
3379 return TDK_SubstitutionFailure;
3380 }
3381
Douglas Gregore65aacb2011-06-16 16:50:48 +00003382 if (OriginalCallArgs) {
3383 // C++ [temp.deduct.call]p4:
3384 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003385 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003386 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003387 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003388 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3389 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003390
Richard Smithc92d2062017-01-05 23:02:44 +00003391 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003392 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003393 // FIXME: This presumably means a pack ended up smaller than we
3394 // expected while deducing. Should this not result in deduction
3395 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003396 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003397
Richard Smithc92d2062017-01-05 23:02:44 +00003398 QualType DeducedA;
3399 if (!OriginalArg.DecomposedParam) {
3400 // P is one of the function parameters, just look up its substituted
3401 // type.
3402 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3403 } else {
3404 // P is a decomposed element of a parameter corresponding to a
3405 // braced-init-list argument. Substitute back into P to find the
3406 // deduced A.
3407 QualType &CacheEntry =
3408 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3409 if (CacheEntry.isNull()) {
3410 ArgumentPackSubstitutionIndexRAII PackIndex(
3411 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3412 ParamIdx));
3413 CacheEntry =
3414 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3415 Specialization->getTypeSpecStartLoc(),
3416 Specialization->getDeclName());
3417 }
3418 DeducedA = CacheEntry;
3419 }
3420
Richard Smithb1efc9b2017-08-30 00:44:08 +00003421 if (auto TDK =
3422 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3423 return TDK;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003424 }
3425 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003426
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003427 // If we suppressed any diagnostics while performing template argument
3428 // deduction, and if we haven't already instantiated this declaration,
3429 // keep track of these diagnostics. They'll be emitted if this specialization
3430 // is actually used.
3431 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003432 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003433 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3434 if (Pos == SuppressedDiagnostics.end())
3435 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3436 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003438
Mike Stump11289f42009-09-09 15:08:12 +00003439 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003440}
3441
John McCall8d08b9b2010-08-27 09:08:28 +00003442/// Gets the type of a function for template-argument-deducton
3443/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003444static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003445 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003446 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003447 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003448 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003449 return {};
Richard Smith2a7d4812013-05-04 07:00:32 +00003450
John McCallc1f69982010-02-02 02:21:27 +00003451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003452 if (Method->isInstance()) {
3453 // An instance method that's referenced in a form that doesn't
3454 // look like a member pointer is just invalid.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003455 if (!R.HasFormOfMemberPointer)
3456 return {};
John McCall8d08b9b2010-08-27 09:08:28 +00003457
Richard Smith2a7d4812013-05-04 07:00:32 +00003458 return S.Context.getMemberPointerType(Fn->getType(),
3459 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003460 }
3461
3462 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003463 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003464}
3465
3466/// Apply the deduction rules for overload sets.
3467///
3468/// \return the null type if this argument should be treated as an
3469/// undeduced context
3470static QualType
3471ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003472 Expr *Arg, QualType ParamType,
3473 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003474
John McCall8d08b9b2010-08-27 09:08:28 +00003475 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003476
John McCall8d08b9b2010-08-27 09:08:28 +00003477 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003478
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003479 // C++0x [temp.deduct.call]p4
3480 unsigned TDF = 0;
3481 if (ParamWasReference)
3482 TDF |= TDF_ParamWithReferenceType;
3483 if (R.IsAddressOfOperand)
3484 TDF |= TDF_IgnoreQualifiers;
3485
John McCallc1f69982010-02-02 02:21:27 +00003486 // C++0x [temp.deduct.call]p6:
3487 // When P is a function type, pointer to function type, or pointer
3488 // to member function type:
3489
3490 if (!ParamType->isFunctionType() &&
3491 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003492 !ParamType->isMemberFunctionPointerType()) {
3493 if (Ovl->hasExplicitTemplateArgs()) {
3494 // But we can still look for an explicit specialization.
3495 if (FunctionDecl *ExplicitSpec
3496 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003497 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003498 }
John McCallc1f69982010-02-02 02:21:27 +00003499
George Burgess IVcc2f3552016-03-19 21:51:45 +00003500 DeclAccessPair DAP;
3501 if (FunctionDecl *Viable =
3502 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3503 return GetTypeOfFunction(S, R, Viable);
3504
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003505 return {};
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003506 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003507
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003508 // Gather the explicit template arguments, if any.
3509 TemplateArgumentListInfo ExplicitTemplateArgs;
3510 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003511 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003512 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003513 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3514 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003515 NamedDecl *D = (*I)->getUnderlyingDecl();
3516
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003517 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3518 // - If the argument is an overload set containing one or more
3519 // function templates, the parameter is treated as a
3520 // non-deduced context.
3521 if (!Ovl->hasExplicitTemplateArgs())
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003522 return {};
Simon Pilgrim728134c2016-08-12 11:43:57 +00003523
3524 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003525 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003526 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003527 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3528 Specialization, Info))
3529 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003530
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003531 D = Specialization;
3532 }
John McCallc1f69982010-02-02 02:21:27 +00003533
3534 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003535 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003536 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003537
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003538 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003540 ArgType->isFunctionType())
3541 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542
John McCallc1f69982010-02-02 02:21:27 +00003543 // - If the argument is an overload set (not containing function
3544 // templates), trial argument deduction is attempted using each
3545 // of the members of the set. If deduction succeeds for only one
3546 // of the overload set members, that member is used as the
3547 // argument value for the deduction. If deduction succeeds for
3548 // more than one member of the overload set the parameter is
3549 // treated as a non-deduced context.
3550
3551 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3552 // Type deduction is done independently for each P/A pair, and
3553 // the deduced template argument values are then combined.
3554 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003555 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003556 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003557 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003558 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003559 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3560 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003561 if (Result) continue;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003562 if (!Match.isNull())
3563 return {};
John McCallc1f69982010-02-02 02:21:27 +00003564 Match = ArgType;
3565 }
3566
3567 return Match;
3568}
3569
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003570/// Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003571/// described in C++ [temp.deduct.call].
3572///
3573/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003574/// argument deduction based on this P/A pair because the argument is an
3575/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003576static bool AdjustFunctionParmAndArgTypesForDeduction(
3577 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3578 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003579 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003580 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003581 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003582 if (ParamType.hasQualifiers())
3583 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003584
3585 // [...] If P is a reference type, the type referred to by P is
3586 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003587 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003588 if (ParamRefType)
3589 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003590
Nathan Sidwell96090022015-01-16 15:20:14 +00003591 // Overload sets usually make this parameter an undeduced context,
3592 // but there are sometimes special circumstances. Typically
3593 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003594 if (ArgType == S.Context.OverloadTy) {
3595 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3596 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003597 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003598 if (ArgType.isNull())
3599 return true;
3600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601
Douglas Gregor7825bf32011-01-06 22:09:01 +00003602 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003603 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003604 if (ArgType->isIncompleteArrayType()) {
3605 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003606 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003607 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003608
Richard Smith32918772017-02-14 00:25:28 +00003609 // C++1z [temp.deduct.call]p3:
3610 // If P is a forwarding reference and the argument is an lvalue, the type
3611 // "lvalue reference to A" is used in place of A for type deduction.
3612 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003613 Arg->isLValue())
3614 ArgType = S.Context.getLValueReferenceType(ArgType);
3615 } else {
3616 // C++ [temp.deduct.call]p2:
3617 // If P is not a reference type:
3618 // - If A is an array type, the pointer type produced by the
3619 // array-to-pointer standard conversion (4.2) is used in place of
3620 // A for type deduction; otherwise,
3621 if (ArgType->isArrayType())
3622 ArgType = S.Context.getArrayDecayedType(ArgType);
3623 // - If A is a function type, the pointer type produced by the
3624 // function-to-pointer standard conversion (4.3) is used in place
3625 // of A for type deduction; otherwise,
3626 else if (ArgType->isFunctionType())
3627 ArgType = S.Context.getPointerType(ArgType);
3628 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003629 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003630 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003631 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003632 }
3633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634
Douglas Gregor7825bf32011-01-06 22:09:01 +00003635 // C++0x [temp.deduct.call]p4:
3636 // In general, the deduction process attempts to find template argument
3637 // values that will make the deduced A identical to A (after the type A
3638 // is transformed as described above). [...]
3639 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregor7825bf32011-01-06 22:09:01 +00003641 // - If the original P is a reference type, the deduced A (i.e., the
3642 // type referred to by the reference) can be more cv-qualified than
3643 // the transformed A.
3644 if (ParamRefType)
3645 TDF |= TDF_ParamWithReferenceType;
3646 // - The transformed A can be another pointer or pointer to member
3647 // type that can be converted to the deduced A via a qualification
3648 // conversion (4.4).
3649 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3650 ArgType->isObjCObjectPointerType())
3651 TDF |= TDF_IgnoreQualifiers;
3652 // - If P is a class and P has the form simple-template-id, then the
3653 // transformed A can be a derived class of the deduced A. Likewise,
3654 // if P is a pointer to a class of the form simple-template-id, the
3655 // transformed A can be a pointer to a derived class pointed to by
3656 // the deduced A.
3657 if (isSimpleTemplateIdType(ParamType) ||
3658 (isa<PointerType>(ParamType) &&
3659 isSimpleTemplateIdType(
3660 ParamType->getAs<PointerType>()->getPointeeType())))
3661 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Douglas Gregor7825bf32011-01-06 22:09:01 +00003663 return false;
3664}
3665
Richard Smithf0393bf2017-02-16 04:22:56 +00003666static bool
3667hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3668 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003669
Richard Smith707eab62017-01-05 04:08:31 +00003670static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003671 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3672 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003673 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3674 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003675 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003676
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003677/// Attempt template argument deduction from an initializer list
Hubert Tong3280b332015-06-25 00:25:49 +00003678/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003679static Sema::TemplateDeductionResult DeduceFromInitializerList(
3680 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3681 InitListExpr *ILE, TemplateDeductionInfo &Info,
3682 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003683 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3684 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003685 // C++ [temp.deduct.call]p1: (CWG 1591)
3686 // If removing references and cv-qualifiers from P gives
3687 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3688 // a non-empty initializer list, then deduction is performed instead for
3689 // each element of the initializer list, taking P0 as a function template
3690 // parameter type and the initializer element as its argument
3691 //
Richard Smith707eab62017-01-05 04:08:31 +00003692 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003693 if (!ILE->getNumInits())
3694 return Sema::TDK_Success;
3695
Richard Smitha7d5ec92017-01-04 19:47:19 +00003696 QualType ElTy;
3697 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3698 if (ArrTy)
3699 ElTy = ArrTy->getElementType();
3700 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3701 // Otherwise, an initializer list argument causes the parameter to be
3702 // considered a non-deduced context
3703 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003704 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003705
Faisal Valif6dfdb32015-12-10 05:36:39 +00003706 // Deduction only needs to be done for dependent types.
3707 if (ElTy->isDependentType()) {
3708 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003709 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003710 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003711 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003712 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003713 }
3714 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003715
3716 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3717 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003718 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003719 // Determine the array bound is something we can deduce.
3720 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003721 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003722 // We can perform template argument deduction for the given non-type
3723 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003724 // C++ [temp.deduct.type]p13:
3725 // The type of N in the type T[N] is std::size_t.
3726 QualType T = S.Context.getSizeType();
3727 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003728 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003729 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003730 /*ArrayBound=*/true, Info, Deduced))
3731 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003732 }
3733 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003734
3735 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003736}
3737
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003738/// Perform template argument deduction per [temp.deduct.call] for a
Richard Smith707eab62017-01-05 04:08:31 +00003739/// single parameter / argument pair.
3740static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003741 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3742 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003743 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3744 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003745 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003746 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003747 QualType OrigParamType = ParamType;
3748
3749 // If P is a reference type [...]
3750 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003751 if (AdjustFunctionParmAndArgTypesForDeduction(
3752 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003753 return Sema::TDK_Success;
3754
Richard Smith707eab62017-01-05 04:08:31 +00003755 // If [...] the argument is a non-empty initializer list [...]
3756 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3757 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003758 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003759
3760 // [...] the deduction process attempts to find template argument values
3761 // that will make the deduced A identical to A
3762 //
3763 // Keep track of the argument type and corresponding parameter index,
3764 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003765 OriginalCallArgs.push_back(
3766 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003767 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003768 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003769}
3770
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003771/// Perform template argument deduction from a function call
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003772/// (C++ [temp.deduct.call]).
3773///
3774/// \param FunctionTemplate the function template for which we are performing
3775/// template argument deduction.
3776///
James Dennett18348b62012-06-22 08:52:37 +00003777/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003778/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003779///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003780/// \param Args the function call arguments
3781///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003782/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003783/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003784/// template argument deduction.
3785///
3786/// \param Info the argument will be updated to provide additional information
3787/// about template argument deduction.
3788///
Richard Smith6eedfe72017-01-09 08:01:21 +00003789/// \param CheckNonDependent A callback to invoke to check conversions for
3790/// non-dependent parameters, between deduction and substitution, per DR1391.
3791/// If this returns true, substitution will be skipped and we return
3792/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3793/// types (after substituting explicit template arguments).
3794///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003795/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003796Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3797 FunctionTemplateDecl *FunctionTemplate,
3798 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003799 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003800 bool PartialOverloading,
3801 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003802 if (FunctionTemplate->isInvalidDecl())
3803 return TDK_Invalid;
3804
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003805 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003806 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003807
Richard Smith32918772017-02-14 00:25:28 +00003808 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3809
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003810 // C++ [temp.deduct.call]p1:
3811 // Template argument deduction is done by comparing each function template
3812 // parameter type (call it P) with the type of the corresponding argument
3813 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003814 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003815 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003816 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003817 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003818 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003819 if (Proto->isTemplateVariadic())
3820 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003821 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003822 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003823 }
Mike Stump11289f42009-09-09 15:08:12 +00003824
Douglas Gregor89026b52009-06-30 23:57:56 +00003825 // The types of the parameters from which we will perform template argument
3826 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003827 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003828 TemplateParameterList *TemplateParams
3829 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003830 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003831 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003832 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003833 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003834 TemplateDeductionResult Result =
3835 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003836 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003837 Deduced,
3838 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003839 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003840 Info);
3841 if (Result)
3842 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003843
3844 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003845 } else {
3846 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003847 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003848 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3849 }
Mike Stump11289f42009-09-09 15:08:12 +00003850
Richard Smith6eedfe72017-01-09 08:01:21 +00003851 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003852
3853 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3854 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003855 // C++ [demp.deduct.call]p1: (DR1391)
3856 // Template argument deduction is done by comparing each function template
3857 // parameter that contains template-parameters that participate in
3858 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003859 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003860 return Sema::TDK_Success;
3861
Richard Smith707eab62017-01-05 04:08:31 +00003862 // ... with the type of the corresponding argument
3863 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003864 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003865 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003866 };
3867
Douglas Gregor89026b52009-06-30 23:57:56 +00003868 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003869 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003870 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003871 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003872 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003873 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003874
Richard Smitha7d5ec92017-01-04 19:47:19 +00003875 const PackExpansionType *ParamExpansion =
3876 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003877 if (!ParamExpansion) {
3878 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003879 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003880 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881
Richard Smith6eedfe72017-01-09 08:01:21 +00003882 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003883 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003884 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003885
Douglas Gregor7825bf32011-01-06 22:09:01 +00003886 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003888
Richard Smithde0d34a2017-01-09 07:14:40 +00003889 QualType ParamPattern = ParamExpansion->getPattern();
3890 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3891 ParamPattern);
3892
Douglas Gregor7825bf32011-01-06 22:09:01 +00003893 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894 // For a function parameter pack that occurs at the end of the
3895 // parameter-declaration-list, the type A of each remaining argument of
3896 // the call is compared with the type P of the declarator-id of the
3897 // function parameter pack. Each comparison deduces template arguments
3898 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003899 // the function parameter pack. When a function parameter pack appears
3900 // in a non-deduced context [not at the end of the list], the type of
3901 // that parameter pack is never deduced.
3902 //
3903 // FIXME: The above rule allows the size of the parameter pack to change
3904 // after we skip it (in the non-deduced case). That makes no sense, so
3905 // we instead notionally deduce the pack against N arguments, where N is
3906 // the length of the explicitly-specified pack if it's expanded by the
3907 // parameter pack and 0 otherwise, and we treat each deduction as a
3908 // non-deduced context.
Richard Smith4a8f3512018-07-19 19:00:37 +00003909 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
3910 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
3911 PackScope.nextPackElement(), ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003912 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003913 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3914 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003915 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003916 } else {
3917 // If the parameter type contains an explicitly-specified pack that we
3918 // could not expand, skip the number of parameters notionally created
3919 // by the expansion.
3920 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003921 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003922 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003923 ++I, ++ArgIdx) {
3924 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003925 // FIXME: Should we add OriginalCallArgs for these? What if the
3926 // corresponding argument is a list?
3927 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003928 }
3929 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931
Douglas Gregor7825bf32011-01-06 22:09:01 +00003932 // Build argument packs for each of the parameter packs expanded by this
3933 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003934 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003936 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003937
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003938 // Capture the context in which the function call is made. This is the context
3939 // that is needed when the accessibility of template arguments is checked.
3940 DeclContext *CallingCtx = CurContext;
3941
Richard Smith6eedfe72017-01-09 08:01:21 +00003942 return FinishTemplateArgumentDeduction(
3943 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003944 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3945 ContextRAII SavedContext(*this, CallingCtx);
3946 return CheckNonDependent(ParamTypesForArgChecking);
3947 });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003948}
3949
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003950QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003951 QualType FunctionType,
3952 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003953 if (ArgFunctionType.isNull())
3954 return ArgFunctionType;
3955
3956 const FunctionProtoType *FunctionTypeP =
3957 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003958 const FunctionProtoType *ArgFunctionTypeP =
3959 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003960
3961 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3962 bool Rebuild = false;
3963
3964 CallingConv CC = FunctionTypeP->getCallConv();
3965 if (EPI.ExtInfo.getCC() != CC) {
3966 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3967 Rebuild = true;
3968 }
3969
3970 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3971 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3972 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3973 Rebuild = true;
3974 }
3975
3976 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3977 ArgFunctionTypeP->hasExceptionSpec())) {
3978 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3979 Rebuild = true;
3980 }
3981
3982 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003983 return ArgFunctionType;
3984
Richard Smithbaa47832016-12-01 02:11:49 +00003985 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3986 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003987}
3988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003989/// Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003990/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3991/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003992///
3993/// \param FunctionTemplate the function template for which we are performing
3994/// template argument deduction.
3995///
James Dennett18348b62012-06-22 08:52:37 +00003996/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003997/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003998///
3999/// \param ArgFunctionType the function type that will be used as the
4000/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004001/// function template's function type. This type may be NULL, if there is no
4002/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00004003///
4004/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00004005/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00004006/// template argument deduction.
4007///
4008/// \param Info the argument will be updated to provide additional information
4009/// about template argument deduction.
4010///
Richard Smithbaa47832016-12-01 02:11:49 +00004011/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4012/// the address of a function template per [temp.deduct.funcaddr] and
4013/// [over.over]. If \c false, we are looking up a function template
4014/// specialization based on its signature, per [temp.deduct.decl].
4015///
Douglas Gregor9b146582009-07-08 20:55:45 +00004016/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004017Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4018 FunctionTemplateDecl *FunctionTemplate,
4019 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4020 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4021 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004022 if (FunctionTemplate->isInvalidDecl())
4023 return TDK_Invalid;
4024
Douglas Gregor9b146582009-07-08 20:55:45 +00004025 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4026 TemplateParameterList *TemplateParams
4027 = FunctionTemplate->getTemplateParameters();
4028 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00004029
Douglas Gregor9b146582009-07-08 20:55:45 +00004030 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00004031 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004032 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004033 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004034 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00004035 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004036 if (TemplateDeductionResult Result
4037 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00004038 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004039 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00004040 &FunctionType, Info))
4041 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004042
4043 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00004044 }
4045
Richard Smithcd198152017-06-07 21:46:22 +00004046 // When taking the address of a function, we require convertibility of
4047 // the resulting function type. Otherwise, we allow arbitrary mismatches
4048 // of calling convention and noreturn.
4049 if (!IsAddressOfFunction)
4050 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4051 /*AdjustExceptionSpec*/false);
4052
Eli Friedman77dcc722012-02-08 03:07:05 +00004053 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004054 EnterExpressionEvaluationContext Unevaluated(
4055 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004056 SFINAETrap Trap(*this);
4057
John McCallc1f69982010-02-02 02:21:27 +00004058 Deduced.resize(TemplateParams->size());
4059
Richard Smith2a7d4812013-05-04 07:00:32 +00004060 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00004061 // type so that we treat it as a non-deduced context in what follows. If we
4062 // are looking up by signature, the signature type should also have a deduced
4063 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00004064 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00004065 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00004066 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00004067 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00004068 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00004069 }
4070
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004071 if (!ArgFunctionType.isNull()) {
Richard Smithcd198152017-06-07 21:46:22 +00004072 unsigned TDF =
4073 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004074 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004075 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004076 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004077 FunctionType, ArgFunctionType,
4078 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004079 return Result;
4080 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004082 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004083 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4084 NumExplicitlySpecified,
4085 Specialization, Info))
4086 return Result;
4087
Richard Smith2a7d4812013-05-04 07:00:32 +00004088 // If the function has a deduced return type, deduce it now, so we can check
4089 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00004090 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00004091 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00004092 DeduceReturnType(Specialization, Info.getLocation(), false))
4093 return TDK_MiscellaneousDeductionFailure;
4094
Richard Smith9095e5b2016-11-01 01:31:23 +00004095 // If the function has a dependent exception specification, resolve it now,
4096 // so we can check that the exception specification matches.
4097 auto *SpecializationFPT =
4098 Specialization->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004099 if (getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +00004100 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4101 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4102 return TDK_MiscellaneousDeductionFailure;
4103
Richard Smithcd198152017-06-07 21:46:22 +00004104 // Adjust the exception specification of the argument to match the
Richard Smithbaa47832016-12-01 02:11:49 +00004105 // substituted and resolved type we just formed. (Calling convention and
4106 // noreturn can't be dependent, so we don't actually need this for them
4107 // right now.)
4108 QualType SpecializationType = Specialization->getType();
4109 if (!IsAddressOfFunction)
4110 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4111 /*AdjustExceptionSpec*/true);
4112
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004113 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00004114 // specialization with respect to arguments of compatible pointer to function
4115 // types, template argument deduction fails.
4116 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00004117 if (IsAddressOfFunction &&
4118 !isSameOrCompatibleFunctionType(
4119 Context.getCanonicalType(SpecializationType),
4120 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00004121 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00004122
4123 if (!IsAddressOfFunction &&
4124 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00004125 return TDK_MiscellaneousDeductionFailure;
4126 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004127
4128 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00004129}
4130
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004131/// Deduce template arguments for a templated conversion
Douglas Gregor05155d82009-08-21 23:19:43 +00004132/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4133/// conversion function template specialization.
4134Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00004135Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00004136 QualType ToType,
4137 CXXConversionDecl *&Specialization,
4138 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00004139 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004140 return TDK_Invalid;
4141
Faisal Vali2b3a3012013-10-24 23:40:02 +00004142 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00004143 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4144
Faisal Vali2b3a3012013-10-24 23:40:02 +00004145 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00004146
4147 // Canonicalize the types for deduction.
4148 QualType P = Context.getCanonicalType(FromType);
4149 QualType A = Context.getCanonicalType(ToType);
4150
Douglas Gregord99609a2011-03-06 09:03:20 +00004151 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00004152 // If P is a reference type, the type referred to by P is used for
4153 // type deduction.
4154 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4155 P = PRef->getPointeeType();
4156
Douglas Gregord99609a2011-03-06 09:03:20 +00004157 // C++0x [temp.deduct.conv]p4:
4158 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00004159 // for type deduction.
Richard Smithb884ed12018-07-11 23:19:41 +00004160 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4161 A = ARef->getPointeeType();
4162 // We work around a defect in the standard here: cv-qualifiers are also
4163 // removed from P and A in this case, unless P was a reference type. This
4164 // seems to mostly match what other compilers are doing.
4165 if (!FromType->getAs<ReferenceType>()) {
4166 A = A.getUnqualifiedType();
4167 P = P.getUnqualifiedType();
4168 }
4169
Douglas Gregord99609a2011-03-06 09:03:20 +00004170 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00004171 //
Mike Stump11289f42009-09-09 15:08:12 +00004172 // If A is not a reference type:
Richard Smithb884ed12018-07-11 23:19:41 +00004173 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004174 assert(!A->isReferenceType() && "Reference types were handled above");
4175
4176 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00004177 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00004178 // of P for type deduction; otherwise,
4179 if (P->isArrayType())
4180 P = Context.getArrayDecayedType(P);
4181 // - If P is a function type, the pointer type produced by the
4182 // function-to-pointer standard conversion (4.3) is used in
4183 // place of P for type deduction; otherwise,
4184 else if (P->isFunctionType())
4185 P = Context.getPointerType(P);
4186 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004187 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004188 else
4189 P = P.getUnqualifiedType();
4190
Douglas Gregord99609a2011-03-06 09:03:20 +00004191 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004192 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00004193 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00004194 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004195 A = A.getUnqualifiedType();
4196 }
4197
Eli Friedman77dcc722012-02-08 03:07:05 +00004198 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004199 EnterExpressionEvaluationContext Unevaluated(
4200 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004201 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004202
4203 // C++ [temp.deduct.conv]p1:
4204 // Template argument deduction is done by comparing the return
4205 // type of the template conversion function (call it P) with the
4206 // type that is required as the result of the conversion (call it
4207 // A) as described in 14.8.2.4.
4208 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004209 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004210 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004211 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004212
4213 // C++0x [temp.deduct.conv]p4:
4214 // In general, the deduction process attempts to find template
4215 // argument values that will make the deduced A identical to
4216 // A. However, there are two cases that allow a difference:
4217 unsigned TDF = 0;
4218 // - If the original A is a reference type, A can be more
4219 // cv-qualified than the deduced A (i.e., the type referred to
4220 // by the reference)
4221 if (ToType->isReferenceType())
Richard Smithb884ed12018-07-11 23:19:41 +00004222 TDF |= TDF_ArgWithReferenceType;
Douglas Gregor05155d82009-08-21 23:19:43 +00004223 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004224 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004225 // conversion.
4226 //
4227 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4228 // both P and A are pointers or member pointers. In this case, we
4229 // just ignore cv-qualifiers completely).
4230 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004231 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004232 TDF |= TDF_IgnoreQualifiers;
4233 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004234 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4235 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004236 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004237
4238 // Create an Instantiation Scope for finalizing the operator.
4239 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004240 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004241 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004242 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004243 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004244 ConversionSpecialized, Info);
4245 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
Douglas Gregor05155d82009-08-21 23:19:43 +00004246 return Result;
4247}
4248
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004249/// Deduce template arguments for a function template when there is
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004250/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4251///
4252/// \param FunctionTemplate the function template for which we are performing
4253/// template argument deduction.
4254///
James Dennett18348b62012-06-22 08:52:37 +00004255/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004256/// arguments.
4257///
4258/// \param Specialization if template argument deduction was successful,
4259/// this will be set to the function template specialization produced by
4260/// template argument deduction.
4261///
4262/// \param Info the argument will be updated to provide additional information
4263/// about template argument deduction.
4264///
Richard Smithbaa47832016-12-01 02:11:49 +00004265/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4266/// the address of a function template in a context where we do not have a
4267/// target type, per [over.over]. If \c false, we are looking up a function
4268/// template specialization based on its signature, which only happens when
4269/// deducing a function parameter type from an argument that is a template-id
4270/// naming a function template specialization.
4271///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004272/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004273Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4274 FunctionTemplateDecl *FunctionTemplate,
4275 TemplateArgumentListInfo *ExplicitTemplateArgs,
4276 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4277 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004278 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004279 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004280 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004281}
4282
Richard Smith30482bc2011-02-20 03:19:35 +00004283namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004284
Richard Smith60437622017-02-09 19:17:44 +00004285 /// Substitute the 'auto' specifier or deduced template specialization type
4286 /// specifier within a type for a given replacement type.
4287 class SubstituteDeducedTypeTransform :
4288 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004289 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004290 bool UseTypeSugar;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004291
Richard Smith30482bc2011-02-20 03:19:35 +00004292 public:
Richard Smith60437622017-02-09 19:17:44 +00004293 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4294 bool UseTypeSugar = true)
4295 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4296 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4297
4298 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4299 assert(isa<TemplateTypeParmType>(Replacement) &&
4300 "unexpected unsugared replacement kind");
4301 QualType Result = Replacement;
4302 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4303 NewTL.setNameLoc(TL.getNameLoc());
4304 return Result;
4305 }
Nico Weberc153d242014-07-28 00:02:09 +00004306
Richard Smith30482bc2011-02-20 03:19:35 +00004307 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4308 // If we're building the type pattern to deduce against, don't wrap the
4309 // substituted type in an AutoType. Certain template deduction rules
4310 // apply only when a template type parameter appears directly (and not if
4311 // the parameter is found through desugaring). For instance:
4312 // auto &&lref = lvalue;
4313 // must transform into "rvalue reference to T" not "rvalue reference to
4314 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004315 //
4316 // FIXME: Is this still necessary?
4317 if (!UseTypeSugar)
4318 return TransformDesugared(TLB, TL);
4319
4320 QualType Result = SemaRef.Context.getAutoType(
4321 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4322 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4323 NewTL.setNameLoc(TL.getNameLoc());
4324 return Result;
4325 }
4326
4327 QualType TransformDeducedTemplateSpecializationType(
4328 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4329 if (!UseTypeSugar)
4330 return TransformDesugared(TLB, TL);
4331
4332 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4333 TL.getTypePtr()->getTemplateName(),
4334 Replacement, Replacement.isNull());
4335 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4336 NewTL.setNameLoc(TL.getNameLoc());
4337 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004338 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004339
4340 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4341 // Lambdas never need to be transformed.
4342 return E;
4343 }
Richard Smith061f1e22013-04-30 21:23:01 +00004344
Richard Smith2a7d4812013-05-04 07:00:32 +00004345 QualType Apply(TypeLoc TL) {
4346 // Create some scratch storage for the transformed type locations.
4347 // FIXME: We're just going to throw this information away. Don't build it.
4348 TypeLocBuilder TLB;
4349 TLB.reserve(TL.getFullDataSize());
4350 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004351 }
Richard Smith30482bc2011-02-20 03:19:35 +00004352 };
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004353
4354} // namespace
Richard Smith30482bc2011-02-20 03:19:35 +00004355
Richard Smith2a7d4812013-05-04 07:00:32 +00004356Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004357Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4358 Optional<unsigned> DependentDeductionDepth) {
4359 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4360 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004361}
4362
Richard Smithb1efc9b2017-08-30 00:44:08 +00004363/// Attempt to produce an informative diagostic explaining why auto deduction
4364/// failed.
4365/// \return \c true if diagnosed, \c false if not.
4366static bool diagnoseAutoDeductionFailure(Sema &S,
4367 Sema::TemplateDeductionResult TDK,
4368 TemplateDeductionInfo &Info,
4369 ArrayRef<SourceRange> Ranges) {
4370 switch (TDK) {
4371 case Sema::TDK_Inconsistent: {
4372 // Inconsistent deduction means we were deducing from an initializer list.
4373 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4374 D << Info.FirstArg << Info.SecondArg;
4375 for (auto R : Ranges)
4376 D << R;
4377 return true;
4378 }
4379
4380 // FIXME: Are there other cases for which a custom diagnostic is more useful
4381 // than the basic "types don't match" diagnostic?
4382
4383 default:
4384 return false;
4385 }
4386}
4387
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004388/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004389///
Richard Smith87d263e2016-12-25 08:05:23 +00004390/// Note that this is done even if the initializer is dependent. (This is
4391/// necessary to support partial ordering of templates using 'auto'.)
4392/// A dependent type will be produced when deducing from a dependent type.
4393///
Richard Smith30482bc2011-02-20 03:19:35 +00004394/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004395/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004396/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004397/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004398/// \param DependentDeductionDepth Set if we should permit deduction in
4399/// dependent cases. This is necessary for template partial ordering with
4400/// 'auto' template parameters. The value specified is the template
4401/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004402Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004403Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4404 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004405 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004406 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4407 if (NonPlaceholder.isInvalid())
4408 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004409 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004410 }
4411
Richard Smith87d263e2016-12-25 08:05:23 +00004412 if (!DependentDeductionDepth &&
4413 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004414 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004415 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004416 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004417 }
4418
Richard Smith87d263e2016-12-25 08:05:23 +00004419 // Find the depth of template parameter to synthesize.
4420 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4421
Richard Smith74aeef52013-04-26 16:15:35 +00004422 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4423 // Since 'decltype(auto)' can only occur at the top of the type, we
4424 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004425 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004426 if (AT->isDecltypeAuto()) {
4427 if (isa<InitListExpr>(Init)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004428 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
Richard Smith74aeef52013-04-26 16:15:35 +00004429 return DAR_FailedAlreadyDiagnosed;
4430 }
4431
Akira Hatanaka0a848562019-01-10 20:12:16 +00004432 ExprResult ER = CheckPlaceholderExpr(Init);
4433 if (ER.isInvalid())
4434 return DAR_FailedAlreadyDiagnosed;
4435 Init = ER.get();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004436 QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004437 if (Deduced.isNull())
4438 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004439 // FIXME: Support a non-canonical deduced type for 'auto'.
4440 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004441 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004442 if (Result.isNull())
4443 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004444 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004445 } else if (!getLangOpts().CPlusPlus) {
4446 if (isa<InitListExpr>(Init)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004447 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
Richard Smithe301ba22015-11-11 02:02:15 +00004448 return DAR_FailedAlreadyDiagnosed;
4449 }
Richard Smith74aeef52013-04-26 16:15:35 +00004450 }
4451 }
4452
Richard Smith30482bc2011-02-20 03:19:35 +00004453 SourceLocation Loc = Init->getExprLoc();
4454
4455 LocalInstantiationScope InstScope(*this);
4456
4457 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004458 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4459 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004460 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4461 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004462 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4463 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004464
Richard Smith87d263e2016-12-25 08:05:23 +00004465 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004466 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004467 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004468 assert(!FuncParam.isNull() &&
4469 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004470
4471 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004472 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004473 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004474
Richard Smith87d263e2016-12-25 08:05:23 +00004475 TemplateDeductionInfo Info(Loc, Depth);
4476
4477 // If deduction failed, don't diagnose if the initializer is dependent; it
4478 // might acquire a matching type in the instantiation.
Richard Smithb1efc9b2017-08-30 00:44:08 +00004479 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4480 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
Richard Smith87d263e2016-12-25 08:05:23 +00004481 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004482 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004483 assert(!Result.isNull() && "substituting DependentTy can't fail");
4484 return DAR_Succeeded;
4485 }
Richard Smithb1efc9b2017-08-30 00:44:08 +00004486 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4487 return DAR_FailedAlreadyDiagnosed;
Richard Smith87d263e2016-12-25 08:05:23 +00004488 return DAR_Failed;
4489 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004490
Richard Smith707eab62017-01-05 04:08:31 +00004491 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4492
Richard Smith74801c82012-07-08 04:13:07 +00004493 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004494 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004495 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4496 // against that. Such deduction only succeeds if removing cv-qualifiers and
4497 // references results in std::initializer_list<T>.
4498 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4499 return DAR_Failed;
4500
Richard Smithb1efc9b2017-08-30 00:44:08 +00004501 SourceRange DeducedFromInitRange;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004502 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00004503 Expr *Init = InitList->getInit(i);
4504
4505 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4506 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
Richard Smithc92d2062017-01-05 23:02:44 +00004507 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4508 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004509 return DeductionFailed(TDK, {DeducedFromInitRange,
4510 Init->getSourceRange()});
4511
4512 if (DeducedFromInitRange.isInvalid() &&
4513 Deduced[0].getKind() != TemplateArgument::Null)
4514 DeducedFromInitRange = Init->getSourceRange();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004515 }
4516 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004517 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4518 Diag(Loc, diag::err_auto_bitfield);
4519 return DAR_FailedAlreadyDiagnosed;
4520 }
4521
Richard Smithb1efc9b2017-08-30 00:44:08 +00004522 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004523 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004524 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004525 return DeductionFailed(TDK, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004526 }
Richard Smith30482bc2011-02-20 03:19:35 +00004527
Richard Smith87d263e2016-12-25 08:05:23 +00004528 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004529 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smithb1efc9b2017-08-30 00:44:08 +00004530 return DeductionFailed(TDK_Incomplete, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004531
Eli Friedmane4310952012-11-06 23:56:42 +00004532 QualType DeducedType = Deduced[0].getAsType();
4533
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004534 if (InitList) {
4535 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4536 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004537 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004538 }
4539
Richard Smith60437622017-02-09 19:17:44 +00004540 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004541 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004542 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004543
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004544 // Check that the deduced argument type is compatible with the original
4545 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004546 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004547 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004548 assert((bool)InitList == OriginalArg.DecomposedParam &&
4549 "decomposed non-init-list in auto deduction?");
Richard Smithb1efc9b2017-08-30 00:44:08 +00004550 if (auto TDK =
4551 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004552 Result = QualType();
Richard Smithb1efc9b2017-08-30 00:44:08 +00004553 return DeductionFailed(TDK, {});
Richard Smith707eab62017-01-05 04:08:31 +00004554 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004555 }
4556
Sebastian Redl09edce02012-01-23 22:09:39 +00004557 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004558}
4559
Simon Pilgrim728134c2016-08-12 11:43:57 +00004560QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004561 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004562 if (TypeToReplaceAuto->isDependentType())
4563 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004564 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004565 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004566}
4567
Richard Smith60437622017-02-09 19:17:44 +00004568TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4569 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004570 if (TypeToReplaceAuto->isDependentType())
4571 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004572 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004573 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004574}
4575
Richard Smith33c33c32017-02-04 01:28:01 +00004576QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4577 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004578 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4579 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004580 .TransformType(TypeWithAuto);
4581}
4582
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004583void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4584 if (isa<InitListExpr>(Init))
4585 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004586 VDecl->isInitCapture()
4587 ? diag::err_init_capture_deduction_failure_from_init_list
4588 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004589 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4590 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004591 Diag(VDecl->getLocation(),
4592 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4593 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004594 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4595 << Init->getSourceRange();
4596}
4597
Richard Smith2a7d4812013-05-04 07:00:32 +00004598bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4599 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004600 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004601
Richard Smith50e291e2018-01-02 23:52:42 +00004602 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4603 // within the return type from the call operator's type.
4604 if (isLambdaConversionOperator(FD)) {
4605 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4606 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4607
Fangrui Song6907ce22018-07-30 19:24:48 +00004608 // For a generic lambda, instantiate the call operator if needed.
Richard Smith50e291e2018-01-02 23:52:42 +00004609 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4610 CallOp = InstantiateFunctionDeclaration(
4611 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4612 if (!CallOp || CallOp->isInvalidDecl())
4613 return true;
4614
4615 // We might need to deduce the return type by instantiating the definition
4616 // of the operator() function.
4617 if (CallOp->getReturnType()->isUndeducedType())
4618 InstantiateFunctionDefinition(Loc, CallOp);
4619 }
4620
4621 if (CallOp->isInvalidDecl())
4622 return true;
4623 assert(!CallOp->getReturnType()->isUndeducedType() &&
4624 "failed to deduce lambda return type");
4625
4626 // Build the new return type from scratch.
4627 QualType RetType = getLambdaConversionFunctionResultType(
4628 CallOp->getType()->castAs<FunctionProtoType>());
4629 if (FD->getReturnType()->getAs<PointerType>())
4630 RetType = Context.getPointerType(RetType);
4631 else {
4632 assert(FD->getReturnType()->getAs<BlockPointerType>());
4633 RetType = Context.getBlockPointerType(RetType);
4634 }
4635 Context.adjustDeducedFunctionResultType(FD, RetType);
4636 return false;
4637 }
4638
Richard Smith2a7d4812013-05-04 07:00:32 +00004639 if (FD->getTemplateInstantiationPattern())
4640 InstantiateFunctionDefinition(Loc, FD);
4641
Alp Toker314cc812014-01-25 16:55:45 +00004642 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004643 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4644 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4645 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4646 }
4647
4648 return StillUndeduced;
4649}
4650
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004651/// If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004652static void
4653AddImplicitObjectParameterType(ASTContext &Context,
4654 CXXMethodDecl *Method,
4655 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004656 // C++11 [temp.func.order]p3:
4657 // [...] The new parameter is of type "reference to cv A," where cv are
4658 // the cv-qualifiers of the function template (if any) and A is
4659 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004660 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004661 // The standard doesn't say explicitly, but we pick the appropriate kind of
4662 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004663 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00004664 ArgTy = Context.getQualifiedType(ArgTy, Method->getTypeQualifiers());
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004665 if (Method->getRefQualifier() == RQ_RValue)
4666 ArgTy = Context.getRValueReferenceType(ArgTy);
4667 else
4668 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004669 ArgTypes.push_back(ArgTy);
4670}
4671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004672/// Determine whether the function template \p FT1 is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004673/// specialized as \p FT2.
4674static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004675 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004676 FunctionTemplateDecl *FT1,
4677 FunctionTemplateDecl *FT2,
4678 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004679 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004680 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004681 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004682 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4683 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004685 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4686 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004687 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004688 Deduced.resize(TemplateParams->size());
4689
4690 // C++0x [temp.deduct.partial]p3:
4691 // The types used to determine the ordering depend on the context in which
4692 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004693 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004694 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004695 switch (TPOC) {
4696 case TPOC_Call: {
4697 // - In the context of a function call, the function parameter types are
4698 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004699 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4700 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004701
Eli Friedman3b5774a2012-09-19 23:27:04 +00004702 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004703 // [...] If only one of the function templates is a non-static
4704 // member, that function template is considered to have a new
4705 // first parameter inserted in its function parameter list. The
4706 // new parameter is of type "reference to cv A," where cv are
4707 // the cv-qualifiers of the function template (if any) and A is
4708 // the class of which the function template is a member.
4709 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004710 // Note that we interpret this to mean "if one of the function
4711 // templates is a non-static member and the other is a non-member";
4712 // otherwise, the ordering rules for static functions against non-static
4713 // functions don't make any sense.
4714 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004715 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4716 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004717 SmallVector<QualType, 4> Args1;
4718
Richard Smithe5b52202013-09-11 00:52:39 +00004719 unsigned NumComparedArguments = NumCallArguments1;
4720
4721 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004722 // Compare 'this' from Method1 against first parameter from Method2.
4723 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4724 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004725 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004726 // Compare 'this' from Method2 against first parameter from Method1.
4727 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004728 }
4729
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004730 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004731 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004732 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004733 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734
Douglas Gregorb837ea42011-01-11 17:34:58 +00004735 // C++ [temp.func.order]p5:
4736 // The presence of unused ellipsis and default arguments has no effect on
4737 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004738 if (Args1.size() > NumComparedArguments)
4739 Args1.resize(NumComparedArguments);
4740 if (Args2.size() > NumComparedArguments)
4741 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004742 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4743 Args1.data(), Args1.size(), Info, Deduced,
4744 TDF_None, /*PartialOrdering=*/true))
4745 return false;
4746
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004747 break;
4748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004750 case TPOC_Conversion:
4751 // - In the context of a call to a conversion operator, the return types
4752 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004753 if (DeduceTemplateArgumentsByTypeMatch(
4754 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4755 Info, Deduced, TDF_None,
4756 /*PartialOrdering=*/true))
4757 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004758 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004760 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004761 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004762 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004763 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4764 FD2->getType(), FD1->getType(),
4765 Info, Deduced, TDF_None,
4766 /*PartialOrdering=*/true))
4767 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004768 break;
4769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004771 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772 // In most cases, all template parameters must have values in order for
4773 // deduction to succeed, but for partial ordering purposes a template
4774 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004775 // types being used for partial ordering. [ Note: a template parameter used
4776 // in a non-deduced context is considered used. -end note]
4777 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4778 for (; ArgIdx != NumArgs; ++ArgIdx)
4779 if (Deduced[ArgIdx].isNull())
4780 break;
4781
Richard Smithf0393bf2017-02-16 04:22:56 +00004782 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4783 // to substitute the deduced arguments back into the template and check that
4784 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004785
Richard Smithf0393bf2017-02-16 04:22:56 +00004786 if (ArgIdx == NumArgs) {
4787 // All template arguments were deduced. FT1 is at least as specialized
4788 // as FT2.
4789 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004790 }
4791
Richard Smithf0393bf2017-02-16 04:22:56 +00004792 // Figure out which template parameters were used.
4793 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4794 switch (TPOC) {
4795 case TPOC_Call:
4796 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4797 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4798 TemplateParams->getDepth(),
4799 UsedParameters);
4800 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
Richard Smithf0393bf2017-02-16 04:22:56 +00004802 case TPOC_Conversion:
4803 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4804 TemplateParams->getDepth(), UsedParameters);
4805 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Richard Smithf0393bf2017-02-16 04:22:56 +00004807 case TPOC_Other:
4808 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4809 TemplateParams->getDepth(),
4810 UsedParameters);
4811 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004812 }
4813
Richard Smithf0393bf2017-02-16 04:22:56 +00004814 for (; ArgIdx != NumArgs; ++ArgIdx)
4815 // If this argument had no value deduced but was used in one of the types
4816 // used for partial ordering, then deduction fails.
4817 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4818 return false;
4819
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004820 return true;
4821}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004822
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004823/// Determine whether this a function template whose parameter-type-list
Douglas Gregorcef1a032011-01-16 16:03:23 +00004824/// ends with a function parameter pack.
4825static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4826 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4827 unsigned NumParams = Function->getNumParams();
4828 if (NumParams == 0)
4829 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregorcef1a032011-01-16 16:03:23 +00004831 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4832 if (!Last->isParameterPack())
4833 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Douglas Gregorcef1a032011-01-16 16:03:23 +00004835 // Make sure that no previous parameter is a parameter pack.
4836 while (--NumParams > 0) {
4837 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4838 return false;
4839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840
Douglas Gregorcef1a032011-01-16 16:03:23 +00004841 return true;
4842}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004844/// Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004845/// to the rules of function template partial ordering (C++ [temp.func.order]).
4846///
4847/// \param FT1 the first function template
4848///
4849/// \param FT2 the second function template
4850///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004851/// \param TPOC the context in which we are performing partial ordering of
4852/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004853///
Richard Smithe5b52202013-09-11 00:52:39 +00004854/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4855/// only when \c TPOC is \c TPOC_Call.
4856///
4857/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4858/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004859///
Douglas Gregorbe999392009-09-15 16:23:51 +00004860/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004861/// template is more specialized, returns NULL.
4862FunctionTemplateDecl *
4863Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4864 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004865 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004866 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004867 unsigned NumCallArguments1,
4868 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004870 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004871 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004872 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004874 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004875 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004877 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004878 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004879
Douglas Gregorcef1a032011-01-16 16:03:23 +00004880 // FIXME: This mimics what GCC implements, but doesn't match up with the
4881 // proposed resolution for core issue 692. This area needs to be sorted out,
4882 // but for now we attempt to maintain compatibility.
4883 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4884 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4885 if (Variadic1 != Variadic2)
4886 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887
Craig Topperc3ec1492014-05-26 06:22:03 +00004888 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004889}
Douglas Gregor9b146582009-07-08 20:55:45 +00004890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004891/// Determine if the two templates are equivalent.
Douglas Gregor450f00842009-09-25 18:43:00 +00004892static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4893 if (T1 == T2)
4894 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregor450f00842009-09-25 18:43:00 +00004896 if (!T1 || !T2)
4897 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898
Douglas Gregor450f00842009-09-25 18:43:00 +00004899 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4900}
4901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004902/// Retrieve the most specialized of the given function template
Douglas Gregor450f00842009-09-25 18:43:00 +00004903/// specializations.
4904///
John McCall58cc69d2010-01-27 01:50:18 +00004905/// \param SpecBegin the start iterator of the function template
4906/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004907///
John McCall58cc69d2010-01-27 01:50:18 +00004908/// \param SpecEnd the end iterator of the function template
4909/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004910///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004912/// diagnostic should occur.
4913///
4914/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4915/// no matching candidates.
4916///
4917/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4918/// occurs.
4919///
4920/// \param CandidateDiag partial diagnostic used for each function template
4921/// specialization that is a candidate in the ambiguous ordering. One parameter
4922/// in this diagnostic should be unbound, which will correspond to the string
4923/// describing the template arguments for the function template specialization.
4924///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004926/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004927UnresolvedSetIterator Sema::getMostSpecialized(
4928 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4929 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004930 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4931 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4932 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004933 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004934 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004935 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004936 FailedCandidates.NoteCandidates(*this, Loc);
4937 }
John McCall58cc69d2010-01-27 01:50:18 +00004938 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
4941 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004942 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943
Douglas Gregor450f00842009-09-25 18:43:00 +00004944 // Find the function template that is better than all of the templates it
4945 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004946 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004947 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004948 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004949 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004950 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4951 FunctionTemplateDecl *Challenger
4952 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004953 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004954 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004955 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004956 Challenger)) {
4957 Best = I;
4958 BestTemplate = Challenger;
4959 }
4960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Douglas Gregor450f00842009-09-25 18:43:00 +00004962 // Make sure that the "best" function template is more specialized than all
4963 // of the others.
4964 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004965 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4966 FunctionTemplateDecl *Challenger
4967 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004968 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004970 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004971 BestTemplate)) {
4972 Ambiguous = true;
4973 break;
4974 }
4975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004976
Douglas Gregor450f00842009-09-25 18:43:00 +00004977 if (!Ambiguous) {
4978 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004979 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
Douglas Gregor450f00842009-09-25 18:43:00 +00004982 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004983 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004984 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
Richard Smithb875c432013-05-04 01:51:08 +00004986 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004987 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4988 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004989 const auto *FD = cast<FunctionDecl>(*I);
4990 PD << FD << getTemplateArgumentBindingsText(
4991 FD->getPrimaryTemplate()->getTemplateParameters(),
4992 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004993 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004994 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004995 Diag((*I)->getLocation(), PD);
4996 }
Richard Smithb875c432013-05-04 01:51:08 +00004997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
John McCall58cc69d2010-01-27 01:50:18 +00004999 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00005000}
5001
Richard Smith0da6dc42016-12-24 16:40:51 +00005002/// Determine whether one partial specialization, P1, is at least as
5003/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00005004///
Richard Smith26b86ea2016-12-31 21:41:23 +00005005/// \tparam TemplateLikeDecl The kind of P2, which must be a
5006/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00005007/// \param T1 The injected-class-name of P1 (faked for a variable template).
5008/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00005009template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00005010static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00005011 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00005012 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005013 // C++ [temp.class.order]p1:
5014 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015 // specialized as the second if, given the following rewrite to two
5016 // function templates, the first function template is at least as
5017 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00005018 // templates (14.6.6.2):
5019 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020 // first partial specialization and has a single function parameter
5021 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00005022 // arguments of the first partial specialization, and
5023 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024 // second partial specialization and has a single function parameter
5025 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00005026 // arguments of the second partial specialization.
5027 //
Douglas Gregor684268d2010-04-29 06:21:43 +00005028 // Rather than synthesize function templates, we merely perform the
5029 // equivalent partial ordering by performing deduction directly on
5030 // the template arguments of the class template partial
5031 // specializations. This computation is slightly simpler than the
5032 // general problem of function template partial ordering, because
5033 // class template partial specializations are more constrained. We
5034 // know that every template parameter is deducible from the class
5035 // template partial specialization's template arguments, for
5036 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005037 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00005038
Richard Smith0da6dc42016-12-24 16:40:51 +00005039 // Determine whether P1 is at least as specialized as P2.
5040 Deduced.resize(P2->getTemplateParameters()->size());
5041 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
5042 T2, T1, Info, Deduced, TDF_None,
5043 /*PartialOrdering=*/true))
5044 return false;
5045
5046 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5047 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00005048 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5049 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00005050 auto *TST1 = T1->castAs<TemplateSpecializationType>();
5051 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00005052 S, P2, /*PartialOrdering=*/true,
5053 TemplateArgumentList(TemplateArgumentList::OnStack,
5054 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00005055 Deduced, Info))
5056 return false;
5057
5058 return true;
5059}
5060
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005061/// Returns the more specialized class template partial specialization
Richard Smith0da6dc42016-12-24 16:40:51 +00005062/// according to the rules of partial ordering of class template partial
5063/// specializations (C++ [temp.class.order]).
5064///
5065/// \param PS1 the first class template partial specialization
5066///
5067/// \param PS2 the second class template partial specialization
5068///
5069/// \returns the more specialized class template partial specialization. If
5070/// neither partial specialization is more specialized, returns NULL.
5071ClassTemplatePartialSpecializationDecl *
5072Sema::getMoreSpecializedPartialSpecialization(
5073 ClassTemplatePartialSpecializationDecl *PS1,
5074 ClassTemplatePartialSpecializationDecl *PS2,
5075 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00005076 QualType PT1 = PS1->getInjectedSpecializationType();
5077 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078
Richard Smith0e617ec2016-12-27 07:56:27 +00005079 TemplateDeductionInfo Info(Loc);
5080 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5081 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005082
5083 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005084 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005085
5086 return Better1 ? PS1 : PS2;
5087}
5088
Richard Smith0e617ec2016-12-27 07:56:27 +00005089bool Sema::isMoreSpecializedThanPrimary(
5090 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5091 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5092 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5093 QualType PartialT = Spec->getInjectedSpecializationType();
5094 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5095 return false;
5096 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5097 Info.clearSFINAEDiagnostic();
5098 return false;
5099 }
5100 return true;
5101}
5102
Larisse Voufo39a1e502013-08-06 01:03:05 +00005103VarTemplatePartialSpecializationDecl *
5104Sema::getMoreSpecializedPartialSpecialization(
5105 VarTemplatePartialSpecializationDecl *PS1,
5106 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00005107 // Pretend the variable template specializations are class template
5108 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00005109 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00005110 "the partial specializations being compared should specialize"
5111 " the same template.");
5112 TemplateName Name(PS1->getSpecializedTemplate());
5113 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5114 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005115 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005116 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005117 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005118
Richard Smith0e617ec2016-12-27 07:56:27 +00005119 TemplateDeductionInfo Info(Loc);
5120 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5121 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122
Douglas Gregorbe999392009-09-15 16:23:51 +00005123 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005124 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Richard Smith0da6dc42016-12-24 16:40:51 +00005126 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00005127}
5128
Richard Smith0e617ec2016-12-27 07:56:27 +00005129bool Sema::isMoreSpecializedThanPrimary(
5130 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5131 TemplateDecl *Primary = Spec->getSpecializedTemplate();
5132 // FIXME: Cache the injected template arguments rather than recomputing
5133 // them for each partial specialization.
5134 SmallVector<TemplateArgument, 8> PrimaryArgs;
5135 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5136 PrimaryArgs);
5137
5138 TemplateName CanonTemplate =
5139 Context.getCanonicalTemplateName(TemplateName(Primary));
5140 QualType PrimaryT = Context.getTemplateSpecializationType(
5141 CanonTemplate, PrimaryArgs);
5142 QualType PartialT = Context.getTemplateSpecializationType(
5143 CanonTemplate, Spec->getTemplateArgs().asArray());
5144 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5145 return false;
5146 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5147 Info.clearSFINAEDiagnostic();
5148 return false;
5149 }
5150 return true;
5151}
5152
Richard Smith26b86ea2016-12-31 21:41:23 +00005153bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5154 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5155 // C++1z [temp.arg.template]p4: (DR 150)
5156 // A template template-parameter P is at least as specialized as a
5157 // template template-argument A if, given the following rewrite to two
5158 // function templates...
5159
5160 // Rather than synthesize function templates, we merely perform the
5161 // equivalent partial ordering by performing deduction directly on
5162 // the template parameter lists of the template template parameters.
5163 //
5164 // Given an invented class template X with the template parameter list of
5165 // A (including default arguments):
5166 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5167 TemplateParameterList *A = AArg->getTemplateParameters();
5168
5169 // - Each function template has a single function parameter whose type is
5170 // a specialization of X with template arguments corresponding to the
5171 // template parameters from the respective function template
5172 SmallVector<TemplateArgument, 8> AArgs;
5173 Context.getInjectedTemplateArgs(A, AArgs);
5174
5175 // Check P's arguments against A's parameter list. This will fill in default
5176 // template arguments as needed. AArgs are already correct by construction.
5177 // We can't just use CheckTemplateIdType because that will expand alias
5178 // templates.
5179 SmallVector<TemplateArgument, 4> PArgs;
5180 {
5181 SFINAETrap Trap(*this);
5182
5183 Context.getInjectedTemplateArgs(P, PArgs);
5184 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5185 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5186 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5187 // expansions, to form an "as written" argument list.
5188 TemplateArgument Arg = PArgs[I];
5189 if (Arg.getKind() == TemplateArgument::Pack) {
5190 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5191 Arg = *Arg.pack_begin();
5192 }
5193 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5194 Arg, QualType(), P->getParam(I)->getLocation()));
5195 }
5196 PArgs.clear();
5197
5198 // C++1z [temp.arg.template]p3:
5199 // If the rewrite produces an invalid type, then P is not at least as
5200 // specialized as A.
5201 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5202 Trap.hasErrorOccurred())
5203 return false;
5204 }
5205
5206 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5207 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5208
Richard Smith26b86ea2016-12-31 21:41:23 +00005209 // ... the function template corresponding to P is at least as specialized
5210 // as the function template corresponding to A according to the partial
5211 // ordering rules for function templates.
5212 TemplateDeductionInfo Info(Loc, A->getDepth());
5213 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5214}
5215
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005216/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005217/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00005218static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005219MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005220 const Expr *E,
5221 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005222 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005223 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005224 // We can deduce from a pack expansion.
5225 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5226 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005227
Richard Smith34349002012-07-09 03:07:20 +00005228 // Skip through any implicit casts we added while type-checking, and any
5229 // substitutions performed by template alias expansion.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00005230 while (true) {
Richard Smith34349002012-07-09 03:07:20 +00005231 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5232 E = ICE->getSubExpr();
Fangrui Song407659a2018-11-30 23:41:18 +00005233 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
5234 E = CE->getSubExpr();
Richard Smith34349002012-07-09 03:07:20 +00005235 else if (const SubstNonTypeTemplateParmExpr *Subst =
5236 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5237 E = Subst->getReplacement();
5238 else
5239 break;
5240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005241
5242 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005243 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005244 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00005245 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00005246 return;
5247
Mike Stump11289f42009-09-09 15:08:12 +00005248 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00005249 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5250 if (!NTTP)
5251 return;
5252
Douglas Gregor21610382009-10-29 00:04:11 +00005253 if (NTTP->getDepth() == Depth)
5254 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00005255
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005256 // In C++17 mode, additional arguments may be deduced from the type of a
Richard Smith5f274382016-09-28 23:55:27 +00005257 // non-type argument.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005258 if (Ctx.getLangOpts().CPlusPlus17)
Richard Smith5f274382016-09-28 23:55:27 +00005259 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005260}
5261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005262/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005263/// nested name specifier.
5264static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005265MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005266 NestedNameSpecifier *NNS,
5267 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005268 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005269 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005270 if (!NNS)
5271 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005273 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005274 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005275 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005276 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005277}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005279/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005280/// template name.
5281static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005282MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005283 TemplateName Name,
5284 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005285 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005286 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005287 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5288 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005289 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5290 if (TTP->getDepth() == Depth)
5291 Used[TTP->getIndex()] = true;
5292 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005293 return;
5294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005296 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005297 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005298 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005299 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005300 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005301 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005302}
5303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005304/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005305/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005306static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005307MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005308 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005309 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005310 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005311 if (T.isNull())
5312 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005313
Douglas Gregor91772d12009-06-13 00:26:55 +00005314 // Non-dependent types have nothing deducible
5315 if (!T->isDependentType())
5316 return;
5317
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005318 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005319 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005320 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005321 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005322 cast<PointerType>(T)->getPointeeType(),
5323 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005324 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005325 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005326 break;
5327
5328 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005329 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005330 cast<BlockPointerType>(T)->getPointeeType(),
5331 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005332 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005333 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005334 break;
5335
5336 case Type::LValueReference:
5337 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005338 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005339 cast<ReferenceType>(T)->getPointeeType(),
5340 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005341 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005342 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005343 break;
5344
5345 case Type::MemberPointer: {
5346 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005347 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005348 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005349 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005350 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005351 break;
5352 }
5353
5354 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005355 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005356 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005357 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005358 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005359 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005360
5361 case Type::ConstantArray:
5362 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005363 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005364 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005365 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005366 break;
5367
5368 case Type::Vector:
5369 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005370 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005371 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005372 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005373 break;
5374
Erich Keanef702b022018-07-13 19:46:04 +00005375 case Type::DependentVector: {
5376 const auto *VecType = cast<DependentVectorType>(T);
5377 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5378 Depth, Used);
5379 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5380 Used);
5381 break;
5382 }
Douglas Gregor758a8692009-06-17 21:51:59 +00005383 case Type::DependentSizedExtVector: {
5384 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005385 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005386 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005387 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005388 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005389 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005390 break;
5391 }
5392
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005393 case Type::DependentAddressSpace: {
5394 const DependentAddressSpaceType *DependentASType =
5395 cast<DependentAddressSpaceType>(T);
5396 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5397 OnlyDeduced, Depth, Used);
5398 MarkUsedTemplateParameters(Ctx,
5399 DependentASType->getAddrSpaceExpr(),
5400 OnlyDeduced, Depth, Used);
5401 break;
5402 }
5403
Douglas Gregor91772d12009-06-13 00:26:55 +00005404 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005405 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005406 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5407 Used);
Richard Smithc379d1a2018-07-12 23:32:39 +00005408 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
5409 // C++17 [temp.deduct.type]p5:
5410 // The non-deduced contexts are: [...]
5411 // -- A function parameter pack that does not occur at the end of the
5412 // parameter-declaration-list.
5413 if (!OnlyDeduced || I + 1 == N ||
5414 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
5415 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5416 Depth, Used);
5417 } else {
5418 // FIXME: C++17 [temp.deduct.call]p1:
5419 // When a function parameter pack appears in a non-deduced context,
5420 // the type of that pack is never deduced.
5421 //
5422 // We should also track a set of "never deduced" parameters, and
5423 // subtract that from the list of deduced parameters after marking.
5424 }
5425 }
Richard Smithcd198152017-06-07 21:46:22 +00005426 if (auto *E = Proto->getNoexceptExpr())
5427 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005428 break;
5429 }
5430
Douglas Gregor21610382009-10-29 00:04:11 +00005431 case Type::TemplateTypeParm: {
5432 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5433 if (TTP->getDepth() == Depth)
5434 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005435 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005436 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005437
Douglas Gregorfb322d82011-01-14 05:11:40 +00005438 case Type::SubstTemplateTypeParmPack: {
5439 const SubstTemplateTypeParmPackType *Subst
5440 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005441 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005442 QualType(Subst->getReplacedParameter(), 0),
5443 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005444 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005445 OnlyDeduced, Depth, Used);
5446 break;
5447 }
5448
John McCall2408e322010-04-27 00:57:59 +00005449 case Type::InjectedClassName:
5450 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005451 LLVM_FALLTHROUGH;
John McCall2408e322010-04-27 00:57:59 +00005452
Douglas Gregor91772d12009-06-13 00:26:55 +00005453 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005454 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005455 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005456 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005457 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458
Douglas Gregord0ad2942010-12-23 01:24:45 +00005459 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005460 // If the template argument list of P contains a pack expansion that is
5461 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005462 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005464 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005465 break;
5466
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005467 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005468 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005469 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005470 break;
5471 }
5472
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005473 case Type::Complex:
5474 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005475 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005476 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005477 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005478 break;
5479
Eli Friedman0dfb8892011-10-06 23:00:33 +00005480 case Type::Atomic:
5481 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005482 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005483 cast<AtomicType>(T)->getValueType(),
5484 OnlyDeduced, Depth, Used);
5485 break;
5486
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005487 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005488 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005489 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005490 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005491 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005492 break;
5493
John McCallc392f372010-06-11 00:33:02 +00005494 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005495 // C++14 [temp.deduct.type]p5:
5496 // The non-deduced contexts are:
5497 // -- The nested-name-specifier of a type that was specified using a
5498 // qualified-id
5499 //
5500 // C++14 [temp.deduct.type]p6:
5501 // When a type name is specified in a way that includes a non-deduced
5502 // context, all of the types that comprise that type name are also
5503 // non-deduced.
5504 if (OnlyDeduced)
5505 break;
5506
John McCallc392f372010-06-11 00:33:02 +00005507 const DependentTemplateSpecializationType *Spec
5508 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005509
Richard Smith50d5b972015-12-30 20:56:05 +00005510 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5511 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005512
John McCallc392f372010-06-11 00:33:02 +00005513 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005514 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005515 Used);
5516 break;
5517 }
5518
John McCallbd8d9bd2010-03-01 23:49:17 +00005519 case Type::TypeOf:
5520 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005521 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005522 cast<TypeOfType>(T)->getUnderlyingType(),
5523 OnlyDeduced, Depth, Used);
5524 break;
5525
5526 case Type::TypeOfExpr:
5527 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005528 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005529 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5530 OnlyDeduced, Depth, Used);
5531 break;
5532
5533 case Type::Decltype:
5534 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005535 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005536 cast<DecltypeType>(T)->getUnderlyingExpr(),
5537 OnlyDeduced, Depth, Used);
5538 break;
5539
Alexis Hunte852b102011-05-24 22:41:36 +00005540 case Type::UnaryTransform:
5541 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005542 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005543 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005544 OnlyDeduced, Depth, Used);
5545 break;
5546
Douglas Gregord2fa7662010-12-20 02:24:11 +00005547 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005548 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005549 cast<PackExpansionType>(T)->getPattern(),
5550 OnlyDeduced, Depth, Used);
5551 break;
5552
Richard Smith30482bc2011-02-20 03:19:35 +00005553 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005554 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005555 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005556 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005557 OnlyDeduced, Depth, Used);
Adrian Prantl4b490852017-12-19 22:21:48 +00005558 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005559
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005560 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005561 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005562 case Type::VariableArray:
5563 case Type::FunctionNoProto:
5564 case Type::Record:
5565 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005566 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005567 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005568 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005569 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005570 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005571#define TYPE(Class, Base)
5572#define ABSTRACT_TYPE(Class, Base)
5573#define DEPENDENT_TYPE(Class, Base)
5574#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5575#include "clang/AST/TypeNodes.def"
5576 break;
5577 }
5578}
5579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005580/// Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005581/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005582static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005583MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005584 const TemplateArgument &TemplateArg,
5585 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005586 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005587 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005588 switch (TemplateArg.getKind()) {
5589 case TemplateArgument::Null:
5590 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005591 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005592 break;
Mike Stump11289f42009-09-09 15:08:12 +00005593
Eli Friedmanb826a002012-09-26 02:36:12 +00005594 case TemplateArgument::NullPtr:
5595 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5596 Depth, Used);
5597 break;
5598
Douglas Gregor91772d12009-06-13 00:26:55 +00005599 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005600 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005601 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005602 break;
5603
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005604 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005605 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005606 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005608 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005609 break;
5610
5611 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005612 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005613 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005614 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615
Anders Carlssonbc343912009-06-15 17:04:53 +00005616 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005617 for (const auto &P : TemplateArg.pack_elements())
5618 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005619 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005620 }
5621}
5622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005623/// Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005624/// template argument list.
5625///
5626/// \param TemplateArgs the template argument list from which template
5627/// parameters will be deduced.
5628///
James Dennett41725122012-06-22 10:16:05 +00005629/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005630/// to indicate when the corresponding template parameter will be
5631/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005632void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005633Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005634 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005635 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005636 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637 // If the template argument list of P contains a pack expansion that is not
5638 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005639 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005641 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005642 return;
5643
Douglas Gregor91772d12009-06-13 00:26:55 +00005644 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005645 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005646 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005647}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005649/// Marks all of the template parameters that will be deduced by a
Douglas Gregorce23bae2009-09-18 23:21:38 +00005650/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005651void Sema::MarkDeducedTemplateParameters(
5652 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5653 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005655 = FunctionTemplate->getTemplateParameters();
5656 Deduced.clear();
5657 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregorce23bae2009-09-18 23:21:38 +00005659 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5660 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005661 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005662 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005663}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005664
Richard Smithf0393bf2017-02-16 04:22:56 +00005665bool hasDeducibleTemplateParameters(Sema &S,
5666 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005667 QualType T) {
5668 if (!T->isDependentType())
5669 return false;
5670
Richard Smithf0393bf2017-02-16 04:22:56 +00005671 TemplateParameterList *TemplateParams
5672 = FunctionTemplate->getTemplateParameters();
5673 llvm::SmallBitVector Deduced(TemplateParams->size());
5674 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5675 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005676
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005677 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005678}