blob: 32e195b5b9707ba31c29501d2291b758d5143f2f [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
Richard Smithc92d2062017-01-05 23:02:44 +000022#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Sema.h"
25#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000026#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000027#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000028
29namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000030 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000031 /// \brief Various flags that control template argument deduction.
32 ///
33 /// These flags can be bitwise-OR'd together.
34 enum TemplateDeductionFlags {
35 /// \brief No template argument deduction flags, which indicates the
36 /// strictest results for template argument deduction (as used for, e.g.,
37 /// matching class template partial specializations).
38 TDF_None = 0,
39 /// \brief Within template argument deduction from a function call, we are
40 /// matching with a parameter type for which the original parameter was
41 /// a reference.
42 TDF_ParamWithReferenceType = 0x1,
43 /// \brief Within template argument deduction from a function call, we
44 /// are matching in a case where we ignore cv-qualifiers.
45 TDF_IgnoreQualifiers = 0x02,
46 /// \brief Within template argument deduction from a function call,
47 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000048 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000049 TDF_DerivedClass = 0x04,
50 /// \brief Allow non-dependent types to differ, e.g., when performing
51 /// template argument deduction from a function call where conversions
52 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000053 TDF_SkipNonDependent = 0x08,
54 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000055 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000056 TDF_TopLevelParameterTypeList = 0x10,
57 /// \brief Within template argument deduction from overload resolution per
58 /// C++ [over.over] allow matching function types that are compatible in
59 /// terms of noreturn and default calling convention adjustments.
60 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000061 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000062}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000063
Douglas Gregor55ca8f62009-06-04 00:03:07 +000064using namespace clang;
65
Douglas Gregor0a29a052010-03-26 05:50:28 +000066/// \brief Compare two APSInts, extending and switching the sign as
67/// necessary to compare their values regardless of underlying type.
68static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
69 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000070 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000071 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000072 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000073
74 // If there is a signedness mismatch, correct it.
75 if (X.isSigned() != Y.isSigned()) {
76 // If the signed value is negative, then the values cannot be the same.
77 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
78 return false;
79
80 Y.setIsSigned(true);
81 X.setIsSigned(true);
82 }
83
84 return X == Y;
85}
86
Douglas Gregor181aa4a2009-06-12 18:26:56 +000087static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000088DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000089 TemplateParameterList *TemplateParams,
90 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000091 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000092 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000093 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000094
Douglas Gregor7baabef2010-12-22 18:17:10 +000095static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000096DeduceTemplateArgumentsByTypeMatch(Sema &S,
97 TemplateParameterList *TemplateParams,
98 QualType Param,
99 QualType Arg,
100 TemplateDeductionInfo &Info,
101 SmallVectorImpl<DeducedTemplateArgument> &
102 Deduced,
103 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000104 bool PartialOrdering = false,
105 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000106
107static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000108DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000109 ArrayRef<TemplateArgument> Params,
110 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000111 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000112 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
113 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000114
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000115/// \brief If the given expression is of a form that permits the deduction
116/// of a non-type template parameter, return the declaration of that
117/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000118static NonTypeTemplateParmDecl *
119getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000120 // If we are within an alias template, the expression may have undergone
121 // any number of parameter substitutions already.
122 while (1) {
123 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
124 E = IC->getSubExpr();
125 else if (SubstNonTypeTemplateParmExpr *Subst =
126 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
127 E = Subst->getReplacement();
128 else
129 break;
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000132 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000133 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
134 if (NTTP->getDepth() == Info.getDeducedDepth())
135 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Craig Topperc3ec1492014-05-26 06:22:03 +0000137 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000138}
139
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000140/// \brief Determine whether two declaration pointers refer to the same
141/// declaration.
142static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000143 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
144 X = NX->getUnderlyingDecl();
145 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
146 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000147
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000148 return X->getCanonicalDecl() == Y->getCanonicalDecl();
149}
150
151/// \brief Verify that the given, deduced template arguments are compatible.
152///
153/// \returns The deduced template argument, or a NULL template argument if
154/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000155static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000156checkDeducedTemplateArguments(ASTContext &Context,
157 const DeducedTemplateArgument &X,
158 const DeducedTemplateArgument &Y) {
159 // We have no deduction for one or both of the arguments; they're compatible.
160 if (X.isNull())
161 return Y;
162 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000163 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000164
Richard Smith593d6a12016-12-23 01:30:39 +0000165 // If we have two non-type template argument values deduced for the same
166 // parameter, they must both match the type of the parameter, and thus must
167 // match each other's type. As we're only keeping one of them, we must check
168 // for that now. The exception is that if either was deduced from an array
169 // bound, the type is permitted to differ.
170 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
171 QualType XType = X.getNonTypeTemplateArgumentType();
172 if (!XType.isNull()) {
173 QualType YType = Y.getNonTypeTemplateArgumentType();
174 if (YType.isNull() || !Context.hasSameType(XType, YType))
175 return DeducedTemplateArgument();
176 }
177 }
178
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000179 switch (X.getKind()) {
180 case TemplateArgument::Null:
181 llvm_unreachable("Non-deduced template arguments handled above");
182
183 case TemplateArgument::Type:
184 // If two template type arguments have the same type, they're compatible.
185 if (Y.getKind() == TemplateArgument::Type &&
186 Context.hasSameType(X.getAsType(), Y.getAsType()))
187 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000188
Richard Smith5f274382016-09-28 23:55:27 +0000189 // If one of the two arguments was deduced from an array bound, the other
190 // supersedes it.
191 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
192 return X.wasDeducedFromArrayBound() ? Y : X;
193
194 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000195 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000196
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000197 case TemplateArgument::Integral:
198 // If we deduced a constant in one case and either a dependent expression or
199 // declaration in another case, keep the integral constant.
200 // If both are integral constants with the same value, keep that value.
201 if (Y.getKind() == TemplateArgument::Expression ||
202 Y.getKind() == TemplateArgument::Declaration ||
203 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000204 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000205 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000206
207 // All other combinations are incompatible.
208 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000209
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000210 case TemplateArgument::Template:
211 if (Y.getKind() == TemplateArgument::Template &&
212 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
213 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000214
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000215 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000216 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000217
218 case TemplateArgument::TemplateExpansion:
219 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000220 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000221 Y.getAsTemplateOrTemplatePattern()))
222 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000224 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000225 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000226
Richard Smith593d6a12016-12-23 01:30:39 +0000227 case TemplateArgument::Expression: {
228 if (Y.getKind() != TemplateArgument::Expression)
229 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230
Richard Smith593d6a12016-12-23 01:30:39 +0000231 // Compare the expressions for equality
232 llvm::FoldingSetNodeID ID1, ID2;
233 X.getAsExpr()->Profile(ID1, Context, true);
234 Y.getAsExpr()->Profile(ID2, Context, true);
235 if (ID1 == ID2)
236 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Richard Smith593d6a12016-12-23 01:30:39 +0000238 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000239 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000241
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000242 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000243 assert(!X.wasDeducedFromArrayBound());
244
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000245 // If we deduced a declaration and a dependent expression, keep the
246 // declaration.
247 if (Y.getKind() == TemplateArgument::Expression)
248 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000249
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000250 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000251 // integral constant and whichever type did not come from an array
252 // bound.
253 if (Y.getKind() == TemplateArgument::Integral) {
254 if (Y.wasDeducedFromArrayBound())
255 return TemplateArgument(Context, Y.getAsIntegral(),
256 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000257 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000260 // If we deduced two declarations, make sure they they refer to the
261 // same declaration.
262 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000263 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000264 return X;
265
266 // All other combinations are incompatible.
267 return DeducedTemplateArgument();
268
269 case TemplateArgument::NullPtr:
270 // If we deduced a null pointer and a dependent expression, keep the
271 // null pointer.
272 if (Y.getKind() == TemplateArgument::Expression)
273 return X;
274
275 // If we deduced a null pointer and an integral constant, keep the
276 // integral constant.
277 if (Y.getKind() == TemplateArgument::Integral)
278 return Y;
279
Richard Smith593d6a12016-12-23 01:30:39 +0000280 // If we deduced two null pointers, they are the same.
281 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000282 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000284 // All other combinations are incompatible.
285 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000287 case TemplateArgument::Pack:
288 if (Y.getKind() != TemplateArgument::Pack ||
289 X.pack_size() != Y.pack_size())
290 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000291
Richard Smith539e8e32017-01-04 01:48:55 +0000292 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000294 XAEnd = X.pack_end(),
295 YA = Y.pack_begin();
296 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000297 TemplateArgument Merged = checkDeducedTemplateArguments(
298 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
299 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
300 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000301 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000302 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000304
Richard Smith539e8e32017-01-04 01:48:55 +0000305 return DeducedTemplateArgument(
306 TemplateArgument::CreatePackCopy(Context, NewPack),
307 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
David Blaikiee4d798f2012-01-20 21:50:17 +0000310 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311}
312
Mike Stump11289f42009-09-09 15:08:12 +0000313/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000314/// as the given deduced template argument. All non-type template parameter
315/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000316static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000317 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000318 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
319 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000320 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000321 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
322 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000323
Richard Smith5d102892016-12-27 03:59:58 +0000324 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
325 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000326 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000327 Info.Param = NTTP;
328 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000329 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 Deduced[NTTP->getIndex()] = Result;
Richard Smithd92eddf2016-12-27 06:14:37 +0000334 if (!S.getLangOpts().CPlusPlus1z)
335 return Sema::TDK_Success;
336
337 // FIXME: It's not clear how deduction of a parameter of reference
338 // type from an argument (of non-reference type) should be performed.
339 // For now, we just remove reference types from both sides and let
340 // the final check for matching types sort out the mess.
341 return DeduceTemplateArgumentsByTypeMatch(
342 S, TemplateParams, NTTP->getType().getNonReferenceType(),
343 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
344 /*PartialOrdering=*/false,
345 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000346}
347
Mike Stump11289f42009-09-09 15:08:12 +0000348/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000349/// from the given integral constant.
350static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
351 Sema &S, TemplateParameterList *TemplateParams,
352 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
353 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
354 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
355 return DeduceNonTypeTemplateArgument(
356 S, TemplateParams, NTTP,
357 DeducedTemplateArgument(S.Context, Value, ValueType,
358 DeducedFromArrayBound),
359 ValueType, Info, Deduced);
360}
361
362/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000363/// from the given null pointer template argument type.
364static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000365 Sema &S, TemplateParameterList *TemplateParams,
366 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000367 TemplateDeductionInfo &Info,
368 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
369 Expr *Value =
370 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
371 S.Context.NullPtrTy, NTTP->getLocation()),
372 NullPtrType, CK_NullToPointer)
373 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000374 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
375 DeducedTemplateArgument(Value),
376 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000377}
378
379/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000380/// from the given type- or value-dependent expression.
381///
382/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000383static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
384 Sema &S, TemplateParameterList *TemplateParams,
385 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
386 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000387 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
388 DeducedTemplateArgument(Value),
389 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000390}
391
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000392/// \brief Deduce the value of the given non-type template parameter
393/// from the given declaration.
394///
395/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000396static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
397 Sema &S, TemplateParameterList *TemplateParams,
398 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
399 TemplateDeductionInfo &Info,
400 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000401 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000402 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000403 return DeduceNonTypeTemplateArgument(
404 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000405}
406
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000407static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000408DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000409 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000410 TemplateName Param,
411 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000412 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000413 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000414 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000415 if (!ParamDecl) {
416 // The parameter type is dependent and is not a template template parameter,
417 // so there is nothing that we can deduce.
418 return Sema::TDK_Success;
419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
Douglas Gregoradee3e32009-11-11 23:06:43 +0000421 if (TemplateTemplateParmDecl *TempParam
422 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000423 // If we're not deducing at this depth, there's nothing to deduce.
424 if (TempParam->getDepth() != Info.getDeducedDepth())
425 return Sema::TDK_Success;
426
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000427 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000429 Deduced[TempParam->getIndex()],
430 NewDeduced);
431 if (Result.isNull()) {
432 Info.Param = TempParam;
433 Info.FirstArg = Deduced[TempParam->getIndex()];
434 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000438 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000443 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000444 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregoradee3e32009-11-11 23:06:43 +0000446 // Mismatch of non-dependent template parameter to argument.
447 Info.FirstArg = TemplateArgument(Param);
448 Info.SecondArg = TemplateArgument(Arg);
449 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000450}
451
Mike Stump11289f42009-09-09 15:08:12 +0000452/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000453/// type (which is a template-id) with the template argument type.
454///
Chandler Carruthc1263112010-02-07 21:33:28 +0000455/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000456///
457/// \param TemplateParams the template parameters that we are deducing
458///
459/// \param Param the parameter type
460///
461/// \param Arg the argument type
462///
463/// \param Info information about the template argument deduction itself
464///
465/// \param Deduced the deduced template arguments
466///
467/// \returns the result of template argument deduction so far. Note that a
468/// "success" result means that template argument deduction has not yet failed,
469/// but it may still fail, later, for other reasons.
470static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000471DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 TemplateParameterList *TemplateParams,
473 const TemplateSpecializationType *Param,
474 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000475 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000476 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000477 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000478
Douglas Gregore81f3e72009-07-07 23:09:34 +0000479 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000480 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000481 = dyn_cast<TemplateSpecializationType>(Arg)) {
482 // Perform template argument deduction for the template name.
483 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000484 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000485 Param->getTemplateName(),
486 SpecArg->getTemplateName(),
487 Info, Deduced))
488 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregore81f3e72009-07-07 23:09:34 +0000491 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000492 // argument. Ignore any missing/extra arguments, since they could be
493 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000494 return DeduceTemplateArguments(S, TemplateParams,
495 Param->template_arguments(),
496 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000497 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregore81f3e72009-07-07 23:09:34 +0000500 // If the argument type is a class template specialization, we
501 // perform template argument deduction using its template
502 // arguments.
503 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000504 if (!RecordArg) {
505 Info.FirstArg = TemplateArgument(QualType(Param, 0));
506 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000507 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
510 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000511 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000512 if (!SpecArg) {
513 Info.FirstArg = TemplateArgument(QualType(Param, 0));
514 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000515 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregore81f3e72009-07-07 23:09:34 +0000518 // Perform template argument deduction for the template name.
519 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000520 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000521 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000522 Param->getTemplateName(),
523 TemplateName(SpecArg->getSpecializedTemplate()),
524 Info, Deduced))
525 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Douglas Gregor7baabef2010-12-22 18:17:10 +0000527 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000528 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
529 SpecArg->getTemplateArgs().asArray(), Info,
530 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000531}
532
John McCall08569062010-08-28 22:14:41 +0000533/// \brief Determines whether the given type is an opaque type that
534/// might be more qualified when instantiated.
535static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
536 switch (T->getTypeClass()) {
537 case Type::TypeOfExpr:
538 case Type::TypeOf:
539 case Type::DependentName:
540 case Type::Decltype:
541 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000542 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000543 return true;
544
545 case Type::ConstantArray:
546 case Type::IncompleteArray:
547 case Type::VariableArray:
548 case Type::DependentSizedArray:
549 return IsPossiblyOpaquelyQualifiedType(
550 cast<ArrayType>(T)->getElementType());
551
552 default:
553 return false;
554 }
555}
556
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000557/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000559getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
561 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor5499af42011-01-05 23:12:31 +0000563 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
564 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor5499af42011-01-05 23:12:31 +0000566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
567 return std::make_pair(TTP->getDepth(), TTP->getIndex());
568}
569
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000570/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000572getDepthAndIndex(UnexpandedParameterPack UPP) {
573 if (const TemplateTypeParmType *TTP
574 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
575 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000577 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
578}
579
Douglas Gregor5499af42011-01-05 23:12:31 +0000580/// \brief Helper function to build a TemplateParameter when we don't
581/// know its type statically.
582static TemplateParameter makeTemplateParameter(Decl *D) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
584 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000585 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000586 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor5499af42011-01-05 23:12:31 +0000588 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
589}
590
Richard Smith0a80d572014-05-29 01:12:14 +0000591/// A pack that we're currently deducing.
592struct clang::DeducedPack {
593 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000594
Richard Smith0a80d572014-05-29 01:12:14 +0000595 // The index of the pack.
596 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000597
Richard Smith0a80d572014-05-29 01:12:14 +0000598 // The old value of the pack before we started deducing it.
599 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000600
Richard Smith0a80d572014-05-29 01:12:14 +0000601 // A deferred value of this pack from an inner deduction, that couldn't be
602 // deduced because this deduction hadn't happened yet.
603 DeducedTemplateArgument DeferredDeduction;
604
605 // The new value of the pack.
606 SmallVector<DeducedTemplateArgument, 4> New;
607
608 // The outer deduction for this pack, if any.
609 DeducedPack *Outer;
610};
611
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000612namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000613/// A scope in which we're performing pack deduction.
614class PackDeductionScope {
615public:
616 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
617 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
618 TemplateDeductionInfo &Info, TemplateArgument Pattern)
619 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
620 // Compute the set of template parameter indices that correspond to
621 // parameter packs expanded by the pack expansion.
622 {
623 llvm::SmallBitVector SawIndices(TemplateParams->size());
624 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
625 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
626 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
627 unsigned Depth, Index;
628 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000629 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000630 SawIndices[Index] = true;
631
632 // Save the deduced template argument for the parameter pack expanded
633 // by this pack expansion, then clear out the deduction.
634 DeducedPack Pack(Index);
635 Pack.Saved = Deduced[Index];
636 Deduced[Index] = TemplateArgument();
637
638 Packs.push_back(Pack);
639 }
640 }
641 }
642 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
643
644 for (auto &Pack : Packs) {
645 if (Info.PendingDeducedPacks.size() > Pack.Index)
646 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
647 else
648 Info.PendingDeducedPacks.resize(Pack.Index + 1);
649 Info.PendingDeducedPacks[Pack.Index] = &Pack;
650
651 if (S.CurrentInstantiationScope) {
652 // If the template argument pack was explicitly specified, add that to
653 // the set of deduced arguments.
654 const TemplateArgument *ExplicitArgs;
655 unsigned NumExplicitArgs;
656 NamedDecl *PartiallySubstitutedPack =
657 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
658 &ExplicitArgs, &NumExplicitArgs);
659 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000660 getDepthAndIndex(PartiallySubstitutedPack) ==
661 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000662 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
663 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000664 }
665 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000666
Richard Smith0a80d572014-05-29 01:12:14 +0000667 ~PackDeductionScope() {
668 for (auto &Pack : Packs)
669 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Richard Smithde0d34a2017-01-09 07:14:40 +0000672 /// Determine whether this pack has already been partially expanded into a
673 /// sequence of (prior) function parameters / template arguments.
674 bool isPartiallyExpanded() {
675 if (Packs.size() != 1 || !S.CurrentInstantiationScope)
676 return false;
677
678 auto *PartiallySubstitutedPack =
679 S.CurrentInstantiationScope->getPartiallySubstitutedPack();
680 return PartiallySubstitutedPack &&
681 getDepthAndIndex(PartiallySubstitutedPack) ==
682 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
683 }
684
Richard Smith0a80d572014-05-29 01:12:14 +0000685 /// Move to deducing the next element in each pack that is being deduced.
686 void nextPackElement() {
687 // Capture the deduced template arguments for each parameter pack expanded
688 // by this pack expansion, add them to the list of arguments we've deduced
689 // for that pack, then clear out the deduced argument.
690 for (auto &Pack : Packs) {
691 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000692 if (!Pack.New.empty() || !DeducedArg.isNull()) {
693 while (Pack.New.size() < PackElements)
694 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith0a80d572014-05-29 01:12:14 +0000695 Pack.New.push_back(DeducedArg);
696 DeducedArg = DeducedTemplateArgument();
697 }
698 }
Richard Smith539e8e32017-01-04 01:48:55 +0000699 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000700 }
701
702 /// \brief Finish template argument deduction for a set of argument packs,
703 /// producing the argument packs and checking for consistency with prior
704 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000705 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000706 // Build argument packs for each of the parameter packs expanded by this
707 // pack expansion.
708 for (auto &Pack : Packs) {
709 // Put back the old value for this pack.
710 Deduced[Pack.Index] = Pack.Saved;
711
712 // Build or find a new value for this pack.
713 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000714 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000715 if (Pack.DeferredDeduction.isNull()) {
716 // We were not able to deduce anything for this parameter pack
717 // (because it only appeared in non-deduced contexts), so just
718 // restore the saved argument pack.
719 continue;
720 }
721
722 NewPack = Pack.DeferredDeduction;
723 Pack.DeferredDeduction = TemplateArgument();
724 } else if (Pack.New.empty()) {
725 // If we deduced an empty argument pack, create it now.
726 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
727 } else {
728 TemplateArgument *ArgumentPack =
729 new (S.Context) TemplateArgument[Pack.New.size()];
730 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
731 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000732 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000733 // FIXME: This is wrong, it's possible that some pack elements are
734 // deduced from an array bound and others are not:
735 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
736 // g({1, 2, 3}, {{}, {}});
737 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000738 Pack.New[0].wasDeducedFromArrayBound());
739 }
740
741 // Pick where we're going to put the merged pack.
742 DeducedTemplateArgument *Loc;
743 if (Pack.Outer) {
744 if (Pack.Outer->DeferredDeduction.isNull()) {
745 // Defer checking this pack until we have a complete pack to compare
746 // it against.
747 Pack.Outer->DeferredDeduction = NewPack;
748 continue;
749 }
750 Loc = &Pack.Outer->DeferredDeduction;
751 } else {
752 Loc = &Deduced[Pack.Index];
753 }
754
755 // Check the new pack matches any previous value.
756 DeducedTemplateArgument OldPack = *Loc;
757 DeducedTemplateArgument Result =
758 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
759
760 // If we deferred a deduction of this pack, check that one now too.
761 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
762 OldPack = Result;
763 NewPack = Pack.DeferredDeduction;
764 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
765 }
766
767 if (Result.isNull()) {
768 Info.Param =
769 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
770 Info.FirstArg = OldPack;
771 Info.SecondArg = NewPack;
772 return Sema::TDK_Inconsistent;
773 }
774
775 *Loc = Result;
776 }
777
778 return Sema::TDK_Success;
779 }
780
781private:
782 Sema &S;
783 TemplateParameterList *TemplateParams;
784 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
785 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000786 unsigned PackElements = 0;
Richard Smith0a80d572014-05-29 01:12:14 +0000787
788 SmallVector<DeducedPack, 2> Packs;
789};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000790} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000791
Douglas Gregor5499af42011-01-05 23:12:31 +0000792/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793/// types to the list of argument types, as in the parameter-type-lists of
794/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000795///
796/// \param S The semantic analysis object within which we are deducing
797///
798/// \param TemplateParams The template parameters that we are deducing
799///
800/// \param Params The list of parameter types
801///
802/// \param NumParams The number of types in \c Params
803///
804/// \param Args The list of argument types
805///
806/// \param NumArgs The number of types in \c Args
807///
808/// \param Info information about the template argument deduction itself
809///
810/// \param Deduced the deduced template arguments
811///
812/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
813/// how template argument deduction is performed.
814///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000815/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000817/// (C++0x [temp.deduct.partial]).
818///
Douglas Gregor5499af42011-01-05 23:12:31 +0000819/// \returns the result of template argument deduction so far. Note that a
820/// "success" result means that template argument deduction has not yet failed,
821/// but it may still fail, later, for other reasons.
822static Sema::TemplateDeductionResult
823DeduceTemplateArguments(Sema &S,
824 TemplateParameterList *TemplateParams,
825 const QualType *Params, unsigned NumParams,
826 const QualType *Args, unsigned NumArgs,
827 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000828 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000829 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000830 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000831 // Fast-path check to see if we have too many/too few arguments.
832 if (NumParams != NumArgs &&
833 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
834 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000835 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000836
Douglas Gregor5499af42011-01-05 23:12:31 +0000837 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838 // Similarly, if P has a form that contains (T), then each parameter type
839 // Pi of the respective parameter-type- list of P is compared with the
840 // corresponding parameter type Ai of the corresponding parameter-type-list
841 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000842 unsigned ArgIdx = 0, ParamIdx = 0;
843 for (; ParamIdx != NumParams; ++ParamIdx) {
844 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000846 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
847 if (!Expansion) {
848 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849
Douglas Gregor5499af42011-01-05 23:12:31 +0000850 // Make sure we have an argument.
851 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000852 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000854 if (isa<PackExpansionType>(Args[ArgIdx])) {
855 // C++0x [temp.deduct.type]p22:
856 // If the original function parameter associated with A is a function
857 // parameter pack and the function parameter associated with P is not
858 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000859 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000860 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861
Douglas Gregor5499af42011-01-05 23:12:31 +0000862 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000863 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
864 Params[ParamIdx], Args[ArgIdx],
865 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000866 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000867 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Douglas Gregor5499af42011-01-05 23:12:31 +0000869 ++ArgIdx;
870 continue;
871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000872
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000873 // C++0x [temp.deduct.type]p5:
874 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000876 // parameter-declaration-clause.
877 if (ParamIdx + 1 < NumParams)
878 return Sema::TDK_Success;
879
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000882 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000884 // comparison deduces template arguments for subsequent positions in the
885 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000886
Douglas Gregor5499af42011-01-05 23:12:31 +0000887 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000888 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Douglas Gregor5499af42011-01-05 23:12:31 +0000890 for (; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000891 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000893 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
894 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000895 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000896 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000897
Richard Smith0a80d572014-05-29 01:12:14 +0000898 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Douglas Gregor5499af42011-01-05 23:12:31 +0000901 // Build argument packs for each of the parameter packs expanded by this
902 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +0000903 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000904 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906
Douglas Gregor5499af42011-01-05 23:12:31 +0000907 // Make sure we don't have any extra arguments.
908 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000909 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000910
Douglas Gregor5499af42011-01-05 23:12:31 +0000911 return Sema::TDK_Success;
912}
913
Douglas Gregor1d684c22011-04-28 00:56:09 +0000914/// \brief Determine whether the parameter has qualifiers that are either
915/// inconsistent with or a superset of the argument's qualifiers.
916static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
917 QualType ArgType) {
918 Qualifiers ParamQs = ParamType.getQualifiers();
919 Qualifiers ArgQs = ArgType.getQualifiers();
920
921 if (ParamQs == ArgQs)
922 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000923
Douglas Gregor1d684c22011-04-28 00:56:09 +0000924 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000925 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000926 ParamQs.hasObjCGCAttr())
927 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000928
Douglas Gregor1d684c22011-04-28 00:56:09 +0000929 // Mismatched (but not missing) address spaces.
930 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
931 ParamQs.hasAddressSpace())
932 return true;
933
John McCall31168b02011-06-15 23:02:42 +0000934 // Mismatched (but not missing) Objective-C lifetime qualifiers.
935 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
936 ParamQs.hasObjCLifetime())
937 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000938
Douglas Gregor1d684c22011-04-28 00:56:09 +0000939 // CVR qualifier superset.
940 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
941 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
942 == ParamQs.getCVRQualifiers());
943}
944
Douglas Gregor19a41f12013-04-17 08:45:07 +0000945/// \brief Compare types for equality with respect to possibly compatible
946/// function types (noreturn adjustment, implicit calling conventions). If any
947/// of parameter and argument is not a function, just perform type comparison.
948///
949/// \param Param the template parameter type.
950///
951/// \param Arg the argument type.
952bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
953 CanQualType Arg) {
954 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
955 *ArgFunction = Arg->getAs<FunctionType>();
956
957 // Just compare if not functions.
958 if (!ParamFunction || !ArgFunction)
959 return Param == Arg;
960
Richard Smith3c4f8d22016-10-16 17:54:23 +0000961 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000962 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000963 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000964 return Arg == Context.getCanonicalType(AdjustedParam);
965
966 // FIXME: Compatible calling conventions.
967
968 return Param == Arg;
969}
970
Richard Smith32918772017-02-14 00:25:28 +0000971/// Get the index of the first template parameter that was originally from the
972/// innermost template-parameter-list. This is 0 except when we concatenate
973/// the template parameter lists of a class template and a constructor template
974/// when forming an implicit deduction guide.
975static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +0000976 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
977 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +0000978 return 0;
Richard Smithbc491202017-02-17 20:05:37 +0000979 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +0000980}
981
982/// Determine whether a type denotes a forwarding reference.
983static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
984 // C++1z [temp.deduct.call]p3:
985 // A forwarding reference is an rvalue reference to a cv-unqualified
986 // template parameter that does not represent a template parameter of a
987 // class template.
988 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
989 if (ParamRef->getPointeeType().getQualifiers())
990 return false;
991 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
992 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
993 }
994 return false;
995}
996
Douglas Gregorcceb9752009-06-26 18:27:22 +0000997/// \brief Deduce the template arguments by comparing the parameter type and
998/// the argument type (C++ [temp.deduct.type]).
999///
Chandler Carruthc1263112010-02-07 21:33:28 +00001000/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001001///
1002/// \param TemplateParams the template parameters that we are deducing
1003///
1004/// \param ParamIn the parameter type
1005///
1006/// \param ArgIn the argument type
1007///
1008/// \param Info information about the template argument deduction itself
1009///
1010/// \param Deduced the deduced template arguments
1011///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001012/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001013/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001014///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001015/// \param PartialOrdering Whether we're performing template argument deduction
1016/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1017///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001018/// \returns the result of template argument deduction so far. Note that a
1019/// "success" result means that template argument deduction has not yet failed,
1020/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001021static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001022DeduceTemplateArgumentsByTypeMatch(Sema &S,
1023 TemplateParameterList *TemplateParams,
1024 QualType ParamIn, QualType ArgIn,
1025 TemplateDeductionInfo &Info,
1026 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1027 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001028 bool PartialOrdering,
1029 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001030 // We only want to look at the canonical types, since typedefs and
1031 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001032 QualType Param = S.Context.getCanonicalType(ParamIn);
1033 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001034
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001035 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001037 if (const PackExpansionType *ArgExpansion
1038 = dyn_cast<PackExpansionType>(Arg))
1039 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040
Douglas Gregorb837ea42011-01-11 17:34:58 +00001041 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001042 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043 // Before the partial ordering is done, certain transformations are
1044 // performed on the types used for partial ordering:
1045 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001046 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1047 if (ParamRef)
1048 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049
Douglas Gregorb837ea42011-01-11 17:34:58 +00001050 // - If A is a reference type, A is replaced by the type referred to.
1051 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1052 if (ArgRef)
1053 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054
Richard Smithed563c22015-02-20 04:45:22 +00001055 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1056 // C++11 [temp.deduct.partial]p9:
1057 // If, for a given type, deduction succeeds in both directions (i.e.,
1058 // the types are identical after the transformations above) and both
1059 // P and A were reference types [...]:
1060 // - if [one type] was an lvalue reference and [the other type] was
1061 // not, [the other type] is not considered to be at least as
1062 // specialized as [the first type]
1063 // - if [one type] is more cv-qualified than [the other type],
1064 // [the other type] is not considered to be at least as specialized
1065 // as [the first type]
1066 // Objective-C ARC adds:
1067 // - [one type] has non-trivial lifetime, [the other type] has
1068 // __unsafe_unretained lifetime, and the types are otherwise
1069 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001070 //
Richard Smithed563c22015-02-20 04:45:22 +00001071 // A is "considered to be at least as specialized" as P iff deduction
1072 // succeeds, so we model this as a deduction failure. Note that
1073 // [the first type] is P and [the other type] is A here; the standard
1074 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001075 Qualifiers ParamQuals = Param.getQualifiers();
1076 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001077 if ((ParamRef->isLValueReferenceType() &&
1078 !ArgRef->isLValueReferenceType()) ||
1079 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1080 (ParamQuals.hasNonTrivialObjCLifetime() &&
1081 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1082 ParamQuals.withoutObjCLifetime() ==
1083 ArgQuals.withoutObjCLifetime())) {
1084 Info.FirstArg = TemplateArgument(ParamIn);
1085 Info.SecondArg = TemplateArgument(ArgIn);
1086 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001087 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089
Richard Smithed563c22015-02-20 04:45:22 +00001090 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001091 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001092 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001093 // version of P.
1094 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001095 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001096 // version of A.
1097 Arg = Arg.getUnqualifiedType();
1098 } else {
1099 // C++0x [temp.deduct.call]p4 bullet 1:
1100 // - If the original P is a reference type, the deduced A (i.e., the type
1101 // referred to by the reference) can be more cv-qualified than the
1102 // transformed A.
1103 if (TDF & TDF_ParamWithReferenceType) {
1104 Qualifiers Quals;
1105 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1106 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001107 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001108 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001110
Douglas Gregor85f240c2011-01-25 17:19:08 +00001111 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1112 // C++0x [temp.deduct.type]p10:
1113 // If P and A are function types that originated from deduction when
1114 // taking the address of a function template (14.8.2.2) or when deducing
1115 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001117 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1118 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001119 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001120 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1121 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001122 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001123 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001124 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1125 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001126 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001129 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001130 // A template type argument T, a template template argument TT or a
1131 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001132 // the following forms:
1133 //
1134 // T
1135 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001136 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001137 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001138 // Just skip any attempts to deduce from a placeholder type or a parameter
1139 // at a different depth.
1140 if (Arg->isPlaceholderType() ||
1141 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001142 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001143
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001144 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001145 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregor60454822009-07-22 20:02:25 +00001147 // If the argument type is an array type, move the qualifiers up to the
1148 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001149 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001150 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001151 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001152 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001153 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001154 RecanonicalizeArg = true;
1155 }
1156 }
Mike Stump11289f42009-09-09 15:08:12 +00001157
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001158 // The argument type can not be less qualified than the parameter
1159 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001160 if (!(TDF & TDF_IgnoreQualifiers) &&
1161 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001162 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001163 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001164 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001165 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001166 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001167
Richard Smith87d263e2016-12-25 08:05:23 +00001168 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1169 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001170 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001171 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001172
Douglas Gregor1d684c22011-04-28 00:56:09 +00001173 // Remove any qualifiers on the parameter from the deduced type.
1174 // We checked the qualifiers for consistency above.
1175 Qualifiers DeducedQs = DeducedType.getQualifiers();
1176 Qualifiers ParamQs = Param.getQualifiers();
1177 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1178 if (ParamQs.hasObjCGCAttr())
1179 DeducedQs.removeObjCGCAttr();
1180 if (ParamQs.hasAddressSpace())
1181 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001182 if (ParamQs.hasObjCLifetime())
1183 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001184
Douglas Gregore46db902011-06-17 22:11:49 +00001185 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001186 // If template deduction would produce a lifetime qualifier on a type
1187 // that is not a lifetime type, template argument deduction fails.
1188 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1189 !DeducedType->isDependentType()) {
1190 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1191 Info.FirstArg = TemplateArgument(Param);
1192 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001193 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001194 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001195
Douglas Gregora4f2b432011-07-26 14:53:44 +00001196 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001197 // If template deduction would produce an argument type with lifetime type
1198 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001199 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001200 DeducedType->isObjCLifetimeType() &&
1201 !DeducedQs.hasObjCLifetime())
1202 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001203
Douglas Gregor1d684c22011-04-28 00:56:09 +00001204 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1205 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001206
Douglas Gregord6605db2009-07-22 21:30:48 +00001207 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001208 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Richard Smith5f274382016-09-28 23:55:27 +00001210 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001212 Deduced[Index],
1213 NewDeduced);
1214 if (Result.isNull()) {
1215 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1216 Info.FirstArg = Deduced[Index];
1217 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001220
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001221 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001222 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001223 }
1224
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001225 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001226 Info.FirstArg = TemplateArgument(ParamIn);
1227 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001228
Douglas Gregorfb322d82011-01-14 05:11:40 +00001229 // If the parameter is an already-substituted template parameter
1230 // pack, do nothing: we don't know which of its arguments to look
1231 // at, so we have to wait until all of the parameter packs in this
1232 // expansion have arguments.
1233 if (isa<SubstTemplateTypeParmPackType>(Param))
1234 return Sema::TDK_Success;
1235
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001236 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001237 CanQualType CanParam = S.Context.getCanonicalType(Param);
1238 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001239 if (!(TDF & TDF_IgnoreQualifiers)) {
1240 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001241 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001242 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001243 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001244 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001245 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001246 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001247
Douglas Gregor194ea692012-03-11 03:29:50 +00001248 // If the parameter type is not dependent, there is nothing to deduce.
1249 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001250 if (!(TDF & TDF_SkipNonDependent)) {
1251 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1252 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1253 Param != Arg;
1254 if (NonDeduced) {
1255 return Sema::TDK_NonDeducedMismatch;
1256 }
1257 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001258 return Sema::TDK_Success;
1259 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001260 } else if (!Param->isDependentType()) {
1261 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1262 ArgUnqualType = CanArg.getUnqualifiedType();
1263 bool Success = (TDF & TDF_InOverloadResolution)?
1264 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1265 ArgUnqualType) :
1266 ParamUnqualType == ArgUnqualType;
1267 if (Success)
1268 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001269 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001270
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001271 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001272 // Non-canonical types cannot appear here.
1273#define NON_CANONICAL_TYPE(Class, Base) \
1274 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1275#define TYPE(Class, Base)
1276#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001277
Douglas Gregor39c02722011-06-15 16:02:29 +00001278 case Type::TemplateTypeParm:
1279 case Type::SubstTemplateTypeParmPack:
1280 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001281
1282 // These types cannot be dependent, so simply check whether the types are
1283 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001284 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001285 case Type::VariableArray:
1286 case Type::Vector:
1287 case Type::FunctionNoProto:
1288 case Type::Record:
1289 case Type::Enum:
1290 case Type::ObjCObject:
1291 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001292 case Type::ObjCObjectPointer: {
1293 if (TDF & TDF_SkipNonDependent)
1294 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001295
Douglas Gregor194ea692012-03-11 03:29:50 +00001296 if (TDF & TDF_IgnoreQualifiers) {
1297 Param = Param.getUnqualifiedType();
1298 Arg = Arg.getUnqualifiedType();
1299 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001300
Douglas Gregor194ea692012-03-11 03:29:50 +00001301 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1302 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001303
1304 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001305 case Type::Complex:
1306 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001307 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1308 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001309 ComplexArg->getElementType(),
1310 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001311
1312 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001313
1314 // _Atomic T [extension]
1315 case Type::Atomic:
1316 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001317 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001318 cast<AtomicType>(Param)->getValueType(),
1319 AtomicArg->getValueType(),
1320 Info, Deduced, TDF);
1321
1322 return Sema::TDK_NonDeducedMismatch;
1323
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001324 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001325 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001326 QualType PointeeType;
1327 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1328 PointeeType = PointerArg->getPointeeType();
1329 } else if (const ObjCObjectPointerType *PointerArg
1330 = Arg->getAs<ObjCObjectPointerType>()) {
1331 PointeeType = PointerArg->getPointeeType();
1332 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001333 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001334 }
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregorfc516c92009-06-26 23:27:24 +00001336 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1338 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001339 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001340 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001343 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001344 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001345 const LValueReferenceType *ReferenceArg =
1346 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001347 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001348 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001350 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001351 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001352 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001353 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001354
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001355 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001356 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001357 const RValueReferenceType *ReferenceArg =
1358 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001359 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001360 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001361
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001362 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1363 cast<RValueReferenceType>(Param)->getPointeeType(),
1364 ReferenceArg->getPointeeType(),
1365 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001368 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001369 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001370 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001371 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001372 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001373 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001374
John McCallf7332682010-08-19 00:20:19 +00001375 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001376 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1377 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1378 IncompleteArrayArg->getElementType(),
1379 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001380 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001381
1382 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001383 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001384 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001385 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001386 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001387 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001388
1389 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001390 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001391 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001392 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001393
John McCallf7332682010-08-19 00:20:19 +00001394 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001395 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1396 ConstantArrayParm->getElementType(),
1397 ConstantArrayArg->getElementType(),
1398 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001399 }
1400
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001401 // type [i]
1402 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001403 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001404 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001405 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001406
John McCallf7332682010-08-19 00:20:19 +00001407 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1408
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001409 // Check the element type of the arrays
1410 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001411 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001412 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001413 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1414 DependentArrayParm->getElementType(),
1415 ArrayArg->getElementType(),
1416 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001417 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001419 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001420 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001421 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001422 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001423 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001424
1425 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001426 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001427 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1428 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001429 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001430 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1431 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001432 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001433 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001434 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001435 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001436 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001437 if (const DependentSizedArrayType *DependentArrayArg
1438 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001439 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001440 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001441 DependentArrayArg->getSizeExpr(),
1442 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001443
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001444 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001445 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001446 }
Mike Stump11289f42009-09-09 15:08:12 +00001447
1448 // type(*)(T)
1449 // T(*)()
1450 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001451 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001452 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001453 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001454 dyn_cast<FunctionProtoType>(Arg);
1455 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001456 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001457
1458 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001459 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001460
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001461 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001462 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001463 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001464 != FunctionProtoArg->getRefQualifier() ||
1465 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001466 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001467
Anders Carlsson2128ec72009-06-08 15:19:08 +00001468 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001469 if (Sema::TemplateDeductionResult Result =
1470 DeduceTemplateArgumentsByTypeMatch(
1471 S, TemplateParams, FunctionProtoParam->getReturnType(),
1472 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001473 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001474
Alp Toker9cacbab2014-01-20 20:26:09 +00001475 return DeduceTemplateArguments(
1476 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1477 FunctionProtoParam->getNumParams(),
1478 FunctionProtoArg->param_type_begin(),
1479 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
John McCalle78aac42010-03-10 03:28:59 +00001482 case Type::InjectedClassName: {
1483 // Treat a template's injected-class-name as if the template
1484 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001485 Param = cast<InjectedClassNameType>(Param)
1486 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001487 assert(isa<TemplateSpecializationType>(Param) &&
1488 "injected class name is not a template specialization type");
1489 // fall through
1490 }
1491
Douglas Gregor705c9002009-06-26 20:57:09 +00001492 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001493 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001494 // TT<T>
1495 // TT<i>
1496 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001497 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001498 const TemplateSpecializationType *SpecParam =
1499 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001500
Richard Smith9b296e32016-04-25 19:09:05 +00001501 // When Arg cannot be a derived class, we can just try to deduce template
1502 // arguments from the template-id.
1503 const RecordType *RecordT = Arg->getAs<RecordType>();
1504 if (!(TDF & TDF_DerivedClass) || !RecordT)
1505 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1506 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Richard Smith9b296e32016-04-25 19:09:05 +00001508 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1509 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001510
Richard Smith9b296e32016-04-25 19:09:05 +00001511 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1512 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001513
Richard Smith9b296e32016-04-25 19:09:05 +00001514 if (Result == Sema::TDK_Success)
1515 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001516
Richard Smith9b296e32016-04-25 19:09:05 +00001517 // We cannot inspect base classes as part of deduction when the type
1518 // is incomplete, so either instantiate any templates necessary to
1519 // complete the type, or skip over it if it cannot be completed.
1520 if (!S.isCompleteType(Info.getLocation(), Arg))
1521 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001522
Richard Smith9b296e32016-04-25 19:09:05 +00001523 // C++14 [temp.deduct.call] p4b3:
1524 // If P is a class and P has the form simple-template-id, then the
1525 // transformed A can be a derived class of the deduced A. Likewise if
1526 // P is a pointer to a class of the form simple-template-id, the
1527 // transformed A can be a pointer to a derived class pointed to by the
1528 // deduced A.
1529 //
1530 // These alternatives are considered only if type deduction would
1531 // otherwise fail. If they yield more than one possible deduced A, the
1532 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001533
Faisal Vali683b0742016-05-19 02:28:21 +00001534 // Reset the incorrectly deduced argument from above.
1535 Deduced = DeducedOrig;
1536
1537 // Use data recursion to crawl through the list of base classes.
1538 // Visited contains the set of nodes we have already visited, while
1539 // ToVisit is our stack of records that we still need to visit.
1540 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1541 SmallVector<const RecordType *, 8> ToVisit;
1542 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001543 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001544 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001545 while (!ToVisit.empty()) {
1546 // Retrieve the next class in the inheritance hierarchy.
1547 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001548
Faisal Vali683b0742016-05-19 02:28:21 +00001549 // If we have already seen this type, skip it.
1550 if (!Visited.insert(NextT).second)
1551 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001552
Faisal Vali683b0742016-05-19 02:28:21 +00001553 // If this is a base class, try to perform template argument
1554 // deduction from it.
1555 if (NextT != RecordT) {
1556 TemplateDeductionInfo BaseInfo(Info.getLocation());
1557 Sema::TemplateDeductionResult BaseResult =
1558 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1559 QualType(NextT, 0), BaseInfo, Deduced);
1560
1561 // If template argument deduction for this base was successful,
1562 // note that we had some success. Otherwise, ignore any deductions
1563 // from this base class.
1564 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001565 // If we've already seen some success, then deduction fails due to
1566 // an ambiguity (temp.deduct.call p5).
1567 if (Successful)
1568 return Sema::TDK_MiscellaneousDeductionFailure;
1569
Faisal Vali683b0742016-05-19 02:28:21 +00001570 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001571 std::swap(SuccessfulDeduced, Deduced);
1572
Faisal Vali683b0742016-05-19 02:28:21 +00001573 Info.Param = BaseInfo.Param;
1574 Info.FirstArg = BaseInfo.FirstArg;
1575 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001576 }
1577
1578 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001579 }
Mike Stump11289f42009-09-09 15:08:12 +00001580
Faisal Vali683b0742016-05-19 02:28:21 +00001581 // Visit base classes
1582 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1583 for (const auto &Base : Next->bases()) {
1584 assert(Base.getType()->isRecordType() &&
1585 "Base class that isn't a record?");
1586 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1587 }
1588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001590 if (Successful) {
1591 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001592 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001593 }
Richard Smith9b296e32016-04-25 19:09:05 +00001594
Douglas Gregore81f3e72009-07-07 23:09:34 +00001595 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001596 }
1597
Douglas Gregor637d9982009-06-10 23:47:09 +00001598 // T type::*
1599 // T T::*
1600 // T (type::*)()
1601 // type (T::*)()
1602 // type (type::*)(T)
1603 // type (T::*)(T)
1604 // T (type::*)(T)
1605 // T (T::*)()
1606 // T (T::*)(T)
1607 case Type::MemberPointer: {
1608 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1609 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1610 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001611 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001612
David Majnemera381cda2015-11-30 20:34:28 +00001613 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1614 if (ParamPointeeType->isFunctionType())
1615 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1616 /*IsCtorOrDtor=*/false, Info.getLocation());
1617 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1618 if (ArgPointeeType->isFunctionType())
1619 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1620 /*IsCtorOrDtor=*/false, Info.getLocation());
1621
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001622 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001623 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001624 ParamPointeeType,
1625 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001626 Info, Deduced,
1627 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001628 return Result;
1629
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001630 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1631 QualType(MemPtrParam->getClass(), 0),
1632 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001633 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001634 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001635 }
1636
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001637 // (clang extension)
1638 //
Mike Stump11289f42009-09-09 15:08:12 +00001639 // type(^)(T)
1640 // T(^)()
1641 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001642 case Type::BlockPointer: {
1643 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1644 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001645
Anders Carlssona767eee2009-06-12 16:23:10 +00001646 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001647 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001648
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001649 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1650 BlockPtrParam->getPointeeType(),
1651 BlockPtrArg->getPointeeType(),
1652 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001653 }
1654
Douglas Gregor39c02722011-06-15 16:02:29 +00001655 // (clang extension)
1656 //
1657 // T __attribute__(((ext_vector_type(<integral constant>))))
1658 case Type::ExtVector: {
1659 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1660 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1661 // Make sure that the vectors have the same number of elements.
1662 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1663 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001664
Douglas Gregor39c02722011-06-15 16:02:29 +00001665 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001666 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1667 VectorParam->getElementType(),
1668 VectorArg->getElementType(),
1669 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001670 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001671
1672 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001673 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1674 // We can't check the number of elements, since the argument has a
1675 // dependent number of elements. This can only occur during partial
1676 // ordering.
1677
1678 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001679 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1680 VectorParam->getElementType(),
1681 VectorArg->getElementType(),
1682 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001683 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001684
Douglas Gregor39c02722011-06-15 16:02:29 +00001685 return Sema::TDK_NonDeducedMismatch;
1686 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001687
Douglas Gregor39c02722011-06-15 16:02:29 +00001688 // (clang extension)
1689 //
1690 // T __attribute__(((ext_vector_type(N))))
1691 case Type::DependentSizedExtVector: {
1692 const DependentSizedExtVectorType *VectorParam
1693 = cast<DependentSizedExtVectorType>(Param);
1694
1695 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1696 // Perform deduction on the element types.
1697 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001698 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1699 VectorParam->getElementType(),
1700 VectorArg->getElementType(),
1701 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001702 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001703
Douglas Gregor39c02722011-06-15 16:02:29 +00001704 // Perform deduction on the vector size, if we can.
1705 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001706 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001707 if (!NTTP)
1708 return Sema::TDK_Success;
1709
1710 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1711 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001712 // Note that we use the "array bound" rules here; just like in that
1713 // case, we don't have any particular type for the vector size, but
1714 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001715 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001716 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001717 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001718 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001719
1720 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001721 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1722 // Perform deduction on the element types.
1723 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001724 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1725 VectorParam->getElementType(),
1726 VectorArg->getElementType(),
1727 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001728 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001729
Douglas Gregor39c02722011-06-15 16:02:29 +00001730 // Perform deduction on the vector size, if we can.
1731 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001732 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001733 if (!NTTP)
1734 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001735
Richard Smith5f274382016-09-28 23:55:27 +00001736 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1737 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001738 Info, Deduced);
1739 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001740
Douglas Gregor39c02722011-06-15 16:02:29 +00001741 return Sema::TDK_NonDeducedMismatch;
1742 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001743
Douglas Gregor637d9982009-06-10 23:47:09 +00001744 case Type::TypeOfExpr:
1745 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001746 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001747 case Type::UnresolvedUsing:
1748 case Type::Decltype:
1749 case Type::UnaryTransform:
1750 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001751 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00001752 case Type::DependentTemplateSpecialization:
1753 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001754 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001755 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001756 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001757 }
1758
David Blaikiee4d798f2012-01-20 21:50:17 +00001759 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001760}
1761
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001762static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001763DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001764 TemplateParameterList *TemplateParams,
1765 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001766 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001767 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001768 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001769 // If the template argument is a pack expansion, perform template argument
1770 // deduction against the pattern of that expansion. This only occurs during
1771 // partial ordering.
1772 if (Arg.isPackExpansion())
1773 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001775 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001776 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001777 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001778
1779 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001780 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001781 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1782 Param.getAsType(),
1783 Arg.getAsType(),
1784 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001785 Info.FirstArg = Param;
1786 Info.SecondArg = Arg;
1787 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001788
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001789 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001790 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001792 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001793 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001794 Info.FirstArg = Param;
1795 Info.SecondArg = Arg;
1796 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001797
1798 case TemplateArgument::TemplateExpansion:
1799 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001801 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001802 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001803 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001804 return Sema::TDK_Success;
1805
1806 Info.FirstArg = Param;
1807 Info.SecondArg = Arg;
1808 return Sema::TDK_NonDeducedMismatch;
1809
1810 case TemplateArgument::NullPtr:
1811 if (Arg.getKind() == TemplateArgument::NullPtr &&
1812 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001813 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001815 Info.FirstArg = Param;
1816 Info.SecondArg = Arg;
1817 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001818
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001819 case TemplateArgument::Integral:
1820 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001821 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001822 return Sema::TDK_Success;
1823
1824 Info.FirstArg = Param;
1825 Info.SecondArg = Arg;
1826 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001827 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001828
1829 if (Arg.getKind() == TemplateArgument::Expression) {
1830 Info.FirstArg = Param;
1831 Info.SecondArg = Arg;
1832 return Sema::TDK_NonDeducedMismatch;
1833 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001834
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001835 Info.FirstArg = Param;
1836 Info.SecondArg = Arg;
1837 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001838
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001839 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001840 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001841 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001842 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001843 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001844 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001845 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001846 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001847 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001848 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001849 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1850 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001851 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001852 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001853 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1854 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001855 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001856 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1857 Arg.getAsDecl(),
1858 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001859 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001861 Info.FirstArg = Param;
1862 Info.SecondArg = Arg;
1863 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001864 }
Mike Stump11289f42009-09-09 15:08:12 +00001865
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001866 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001867 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001868 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001869 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001870 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001871 }
Mike Stump11289f42009-09-09 15:08:12 +00001872
David Blaikiee4d798f2012-01-20 21:50:17 +00001873 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001874}
1875
Douglas Gregor7baabef2010-12-22 18:17:10 +00001876/// \brief Determine whether there is a template argument to be used for
1877/// deduction.
1878///
1879/// This routine "expands" argument packs in-place, overriding its input
1880/// parameters so that \c Args[ArgIdx] will be the available template argument.
1881///
1882/// \returns true if there is another template argument (which will be at
1883/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001884static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1885 unsigned &ArgIdx) {
1886 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001887 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Douglas Gregor7baabef2010-12-22 18:17:10 +00001889 const TemplateArgument &Arg = Args[ArgIdx];
1890 if (Arg.getKind() != TemplateArgument::Pack)
1891 return true;
1892
Richard Smith0bda5b52016-12-23 23:46:56 +00001893 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1894 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001896 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001897}
1898
Douglas Gregord0ad2942010-12-23 01:24:45 +00001899/// \brief Determine whether the given set of template arguments has a pack
1900/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001901static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1902 bool FoundPackExpansion = false;
1903 for (const auto &A : Args) {
1904 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001905 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001906
1907 if (A.getKind() == TemplateArgument::Pack)
1908 return hasPackExpansionBeforeEnd(A.pack_elements());
1909
1910 if (A.isPackExpansion())
1911 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913
Douglas Gregord0ad2942010-12-23 01:24:45 +00001914 return false;
1915}
1916
Douglas Gregor7baabef2010-12-22 18:17:10 +00001917static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001918DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001919 ArrayRef<TemplateArgument> Params,
1920 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001921 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001922 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1923 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001924 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925 // If the template argument list of P contains a pack expansion that is not
1926 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001928 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001929 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001931 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932 // If P has a form that contains <T> or <i>, then each argument Pi of the
1933 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001934 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001935 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001936 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001937 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001938 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Douglas Gregor7baabef2010-12-22 18:17:10 +00001940 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001941 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00001942 return NumberOfArgumentsMustMatch
1943 ? Sema::TDK_MiscellaneousDeductionFailure
1944 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
Richard Smith26b86ea2016-12-31 21:41:23 +00001946 // C++1z [temp.deduct.type]p9:
1947 // During partial ordering, if Ai was originally a pack expansion [and]
1948 // Pi is not a pack expansion, template argument deduction fails.
1949 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001950 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001952 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001953 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001954 = DeduceTemplateArguments(S, TemplateParams,
1955 Params[ParamIdx], Args[ArgIdx],
1956 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957 return Result;
1958
Douglas Gregor7baabef2010-12-22 18:17:10 +00001959 // Move to the next argument.
1960 ++ArgIdx;
1961 continue;
1962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001964 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001966 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967 // If Pi is a pack expansion, then the pattern of Pi is compared with
1968 // each remaining argument in the template argument list of A. Each
1969 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001970 // template parameter packs expanded by Pi.
1971 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001973 // FIXME: If there are no remaining arguments, we can bail out early
1974 // and set any deduced parameter packs to an empty argument pack.
1975 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Richard Smith0a80d572014-05-29 01:12:14 +00001977 // Prepare to deduce the packs within the pattern.
1978 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001979
1980 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001982 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00001983 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001984 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001985 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001986 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1987 Info, Deduced))
1988 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001989
Richard Smith0a80d572014-05-29 01:12:14 +00001990 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001993 // Build argument packs for each of the parameter packs expanded by this
1994 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001995 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998
Douglas Gregor7baabef2010-12-22 18:17:10 +00001999 return Sema::TDK_Success;
2000}
2001
Mike Stump11289f42009-09-09 15:08:12 +00002002static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002003DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002004 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002005 const TemplateArgumentList &ParamList,
2006 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002007 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002008 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002009 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002010 ArgList.asArray(), Info, Deduced,
2011 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002012}
2013
Douglas Gregor705c9002009-06-26 20:57:09 +00002014/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002015static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002016 TemplateArgument X,
2017 const TemplateArgument &Y,
2018 bool PackExpansionMatchesPack = false) {
2019 // If we're checking deduced arguments (X) against original arguments (Y),
2020 // we will have flattened packs to non-expansions in X.
2021 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2022 X = X.getPackExpansionPattern();
2023
Douglas Gregor705c9002009-06-26 20:57:09 +00002024 if (X.getKind() != Y.getKind())
2025 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregor705c9002009-06-26 20:57:09 +00002027 switch (X.getKind()) {
2028 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002029 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002030
Douglas Gregor705c9002009-06-26 20:57:09 +00002031 case TemplateArgument::Type:
2032 return Context.getCanonicalType(X.getAsType()) ==
2033 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregor705c9002009-06-26 20:57:09 +00002035 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002036 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002037
2038 case TemplateArgument::NullPtr:
2039 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002041 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002042 case TemplateArgument::TemplateExpansion:
2043 return Context.getCanonicalTemplateName(
2044 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2045 Context.getCanonicalTemplateName(
2046 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Douglas Gregor705c9002009-06-26 20:57:09 +00002048 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002049 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002050
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002051 case TemplateArgument::Expression: {
2052 llvm::FoldingSetNodeID XID, YID;
2053 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002055 return XID == YID;
2056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
Douglas Gregor705c9002009-06-26 20:57:09 +00002058 case TemplateArgument::Pack:
2059 if (X.pack_size() != Y.pack_size())
2060 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002061
2062 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2063 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002064 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002065 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002066 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002067 return false;
2068
2069 return true;
2070 }
2071
David Blaikiee4d798f2012-01-20 21:50:17 +00002072 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002073}
2074
Douglas Gregorca4686d2011-01-04 23:35:54 +00002075/// \brief Allocate a TemplateArgumentLoc where all locations have
2076/// been initialized to the given location.
2077///
James Dennett634962f2012-06-14 21:40:34 +00002078/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002079/// location information for.
2080///
2081/// \param NTTPType For a declaration template argument, the type of
2082/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002083/// argument. Can be null if no type sugar is available to add to the
2084/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002085///
2086/// \param Loc The source location to use for the resulting template
2087/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002088TemplateArgumentLoc
2089Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2090 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002091 switch (Arg.getKind()) {
2092 case TemplateArgument::Null:
2093 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Douglas Gregorca4686d2011-01-04 23:35:54 +00002095 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002096 return TemplateArgumentLoc(
2097 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Douglas Gregorca4686d2011-01-04 23:35:54 +00002099 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002100 if (NTTPType.isNull())
2101 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002102 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2103 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002104 return TemplateArgumentLoc(TemplateArgument(E), E);
2105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106
Eli Friedmanb826a002012-09-26 02:36:12 +00002107 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002108 if (NTTPType.isNull())
2109 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002110 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2111 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002112 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2113 E);
2114 }
2115
Douglas Gregorca4686d2011-01-04 23:35:54 +00002116 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002117 Expr *E =
2118 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002119 return TemplateArgumentLoc(TemplateArgument(E), E);
2120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor9d802122011-03-02 17:09:35 +00002122 case TemplateArgument::Template:
2123 case TemplateArgument::TemplateExpansion: {
2124 NestedNameSpecifierLocBuilder Builder;
2125 TemplateName Template = Arg.getAsTemplate();
2126 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002127 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002128 else if (QualifiedTemplateName *QTN =
2129 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002130 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002131
Douglas Gregor9d802122011-03-02 17:09:35 +00002132 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002133 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002134 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002135
2136 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002137 Loc, Loc);
2138 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002139
Douglas Gregorca4686d2011-01-04 23:35:54 +00002140 case TemplateArgument::Expression:
2141 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
Douglas Gregorca4686d2011-01-04 23:35:54 +00002143 case TemplateArgument::Pack:
2144 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
David Blaikiee4d798f2012-01-20 21:50:17 +00002147 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002148}
2149
2150
2151/// \brief Convert the given deduced template argument and add it to the set of
2152/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002153static bool
2154ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2155 DeducedTemplateArgument Arg,
2156 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002157 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002158 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002159 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002160 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2161 unsigned ArgumentPackIndex) {
2162 // Convert the deduced template argument into a template
2163 // argument that we can check, almost as if the user had written
2164 // the template argument explicitly.
2165 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002166 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002167
2168 // Check the template argument, converting it as necessary.
2169 return S.CheckTemplateArgument(
2170 Param, ArgLoc, Template, Template->getLocation(),
2171 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002172 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002173 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2174 : Sema::CTAK_Deduced)
2175 : Sema::CTAK_Specified);
2176 };
2177
Douglas Gregorca4686d2011-01-04 23:35:54 +00002178 if (Arg.getKind() == TemplateArgument::Pack) {
2179 // This is a template argument pack, so check each of its arguments against
2180 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002181 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002182 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002183 // When converting the deduced template argument, append it to the
2184 // general output list. We need to do this so that the template argument
2185 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002186 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002187 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002188 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2189 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002190 if (P.isNull()) {
2191 // We deduced arguments for some elements of this pack, but not for
2192 // all of them. This happens if we get a conditionally-non-deduced
2193 // context in a pack expansion (such as an overload set in one of the
2194 // arguments).
2195 S.Diag(Param->getLocation(),
2196 diag::err_template_arg_deduced_incomplete_pack)
2197 << Arg << Param;
2198 return true;
2199 }
Richard Smith37acb792016-02-03 20:15:01 +00002200 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002201 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202
Douglas Gregor51bc5712011-01-05 20:52:18 +00002203 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002204 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002206
Richard Smithdf18ee92016-02-03 20:40:30 +00002207 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002208 // itself, in case that substitution fails.
2209 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002210 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002211 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002212 MultiLevelTemplateArgumentList Args(TemplateArgs);
2213
2214 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2215 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2216 NTTP, Output,
2217 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002218 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002219 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2220 NTTP->getDeclName()).isNull())
2221 return true;
2222 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2223 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2224 TTP, Output,
2225 Template->getSourceRange());
2226 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2227 return true;
2228 }
2229 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002230 }
Richard Smith37acb792016-02-03 20:15:01 +00002231
Douglas Gregorca4686d2011-01-04 23:35:54 +00002232 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002233 Output.push_back(
2234 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002235 return false;
2236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
Richard Smith37acb792016-02-03 20:15:01 +00002238 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002239}
2240
Richard Smith1f5be4d2016-12-21 01:10:31 +00002241// FIXME: This should not be a template, but
2242// ClassTemplatePartialSpecializationDecl sadly does not derive from
2243// TemplateDecl.
2244template<typename TemplateDeclT>
2245static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002246 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002247 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2248 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2249 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002250 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002251 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2252
2253 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2254 NamedDecl *Param = TemplateParams->getParam(I);
2255
2256 if (!Deduced[I].isNull()) {
2257 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002258 // We may have had explicitly-specified template arguments for a
2259 // template parameter pack (that may or may not have been extended
2260 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002261 if (Param->isParameterPack() && CurrentInstantiationScope &&
2262 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2263 // Forget the partially-substituted pack; its substitution is now
2264 // complete.
2265 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2266 // We still need to check the argument in case it was extended by
2267 // deduction.
2268 } else {
2269 // We have already fully type-checked and converted this
2270 // argument, because it was explicitly-specified. Just record the
2271 // presence of this argument.
2272 Builder.push_back(Deduced[I]);
2273 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002274 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002275 }
2276
Richard Smith9c0c9862017-01-05 20:27:28 +00002277 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002278 // checked and converted.
2279 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002280 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002281 Info.Param = makeTemplateParameter(Param);
2282 // FIXME: These template arguments are temporary. Free them!
2283 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2284 return Sema::TDK_SubstitutionFailure;
2285 }
2286
2287 continue;
2288 }
2289
2290 // C++0x [temp.arg.explicit]p3:
2291 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2292 // be deduced to an empty sequence of template arguments.
2293 // FIXME: Where did the word "trailing" come from?
2294 if (Param->isTemplateParameterPack()) {
2295 // We may have had explicitly-specified template arguments for this
2296 // template parameter pack. If so, our empty deduction extends the
2297 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2298 const TemplateArgument *ExplicitArgs;
2299 unsigned NumExplicitArgs;
2300 if (CurrentInstantiationScope &&
2301 CurrentInstantiationScope->getPartiallySubstitutedPack(
2302 &ExplicitArgs, &NumExplicitArgs) == Param) {
2303 Builder.push_back(TemplateArgument(
2304 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2305
2306 // Forget the partially-substituted pack; its substitution is now
2307 // complete.
2308 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2309 } else {
2310 // Go through the motions of checking the empty argument pack against
2311 // the parameter pack.
2312 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002313 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2314 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002315 Info.Param = makeTemplateParameter(Param);
2316 // FIXME: These template arguments are temporary. Free them!
2317 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2318 return Sema::TDK_SubstitutionFailure;
2319 }
2320 }
2321 continue;
2322 }
2323
2324 // Substitute into the default template argument, if available.
2325 bool HasDefaultArg = false;
2326 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2327 if (!TD) {
2328 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2329 return Sema::TDK_Incomplete;
2330 }
2331
2332 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2333 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2334 HasDefaultArg);
2335
2336 // If there was no default argument, deduction is incomplete.
2337 if (DefArg.getArgument().isNull()) {
2338 Info.Param = makeTemplateParameter(
2339 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2340 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002341 if (PartialOverloading) break;
2342
Richard Smith1f5be4d2016-12-21 01:10:31 +00002343 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2344 : Sema::TDK_Incomplete;
2345 }
2346
2347 // Check whether we can actually use the default argument.
2348 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2349 TD->getSourceRange().getEnd(), 0, Builder,
2350 Sema::CTAK_Specified)) {
2351 Info.Param = makeTemplateParameter(
2352 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2353 // FIXME: These template arguments are temporary. Free them!
2354 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2355 return Sema::TDK_SubstitutionFailure;
2356 }
2357
2358 // If we get here, we successfully used the default template argument.
2359 }
2360
2361 return Sema::TDK_Success;
2362}
2363
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002364static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002365 if (auto *DC = dyn_cast<DeclContext>(D))
2366 return DC;
2367 return D->getDeclContext();
2368}
2369
2370template<typename T> struct IsPartialSpecialization {
2371 static constexpr bool value = false;
2372};
2373template<>
2374struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2375 static constexpr bool value = true;
2376};
2377template<>
2378struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2379 static constexpr bool value = true;
2380};
2381
2382/// Complete template argument deduction for a partial specialization.
2383template <typename T>
2384static typename std::enable_if<IsPartialSpecialization<T>::value,
2385 Sema::TemplateDeductionResult>::type
2386FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002387 Sema &S, T *Partial, bool IsPartialOrdering,
2388 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002389 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2390 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002391 // Unevaluated SFINAE context.
2392 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002393 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002394
Richard Smith0da6dc42016-12-24 16:40:51 +00002395 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002396
2397 // C++ [temp.deduct.type]p2:
2398 // [...] or if any template argument remains neither deduced nor
2399 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002400 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002401 if (auto Result = ConvertDeducedTemplateArguments(
2402 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002403 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404
Douglas Gregor684268d2010-04-29 06:21:43 +00002405 // Form the template argument list from the deduced template arguments.
2406 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002407 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002408
Douglas Gregor684268d2010-04-29 06:21:43 +00002409 Info.reset(DeducedArgumentList);
2410
2411 // Substitute the deduced template arguments into the template
2412 // arguments of the class template partial specialization, and
2413 // verify that the instantiated template arguments are both valid
2414 // and are equivalent to the template arguments originally provided
2415 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002416 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002417 auto *Template = Partial->getSpecializedTemplate();
2418 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2419 Partial->getTemplateArgsAsWritten();
2420 const TemplateArgumentLoc *PartialTemplateArgs =
2421 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002422
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002423 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2424 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002425
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002426 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002427 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2428 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2429 if (ParamIdx >= Partial->getTemplateParameters()->size())
2430 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2431
Richard Smith0da6dc42016-12-24 16:40:51 +00002432 Decl *Param = const_cast<NamedDecl *>(
2433 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002434 Info.Param = makeTemplateParameter(Param);
2435 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2436 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002437 }
2438
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002439 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002440 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2441 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002442 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002443
Richard Smith0da6dc42016-12-24 16:40:51 +00002444 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002445 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002446 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002447 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002448 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002449 Info.FirstArg = TemplateArgs[I];
2450 Info.SecondArg = InstArg;
2451 return Sema::TDK_NonDeducedMismatch;
2452 }
2453 }
2454
2455 if (Trap.hasErrorOccurred())
2456 return Sema::TDK_SubstitutionFailure;
2457
2458 return Sema::TDK_Success;
2459}
2460
Richard Smith0e617ec2016-12-27 07:56:27 +00002461/// Complete template argument deduction for a class or variable template,
2462/// when partial ordering against a partial specialization.
2463// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002464static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002465 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2466 const TemplateArgumentList &TemplateArgs,
2467 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2468 TemplateDeductionInfo &Info) {
2469 // Unevaluated SFINAE context.
2470 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2471 Sema::SFINAETrap Trap(S);
2472
2473 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2474
2475 // C++ [temp.deduct.type]p2:
2476 // [...] or if any template argument remains neither deduced nor
2477 // explicitly specified, template argument deduction fails.
2478 SmallVector<TemplateArgument, 4> Builder;
2479 if (auto Result = ConvertDeducedTemplateArguments(
2480 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2481 return Result;
2482
2483 // Check that we produced the correct argument list.
2484 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2485 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2486 TemplateArgument InstArg = Builder[I];
2487 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2488 /*PackExpansionMatchesPack*/true)) {
2489 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2490 Info.FirstArg = TemplateArgs[I];
2491 Info.SecondArg = InstArg;
2492 return Sema::TDK_NonDeducedMismatch;
2493 }
2494 }
2495
2496 if (Trap.hasErrorOccurred())
2497 return Sema::TDK_SubstitutionFailure;
2498
2499 return Sema::TDK_Success;
2500}
2501
2502
Douglas Gregor170bc422009-06-12 22:31:52 +00002503/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002504/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002505/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002506Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002507Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002508 const TemplateArgumentList &TemplateArgs,
2509 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002510 if (Partial->isInvalidDecl())
2511 return TDK_Invalid;
2512
Douglas Gregor170bc422009-06-12 22:31:52 +00002513 // C++ [temp.class.spec.match]p2:
2514 // A partial specialization matches a given actual template
2515 // argument list if the template arguments of the partial
2516 // specialization can be deduced from the actual template argument
2517 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002518
2519 // Unevaluated SFINAE context.
2520 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002521 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002522
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002523 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002524 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002525 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002526 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002527 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002528 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002529 TemplateArgs, Info, Deduced))
2530 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002531
Richard Smith80934652012-07-16 01:09:10 +00002532 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002533 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2534 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002535 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002536 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002537
Douglas Gregore1416332009-06-14 08:02:22 +00002538 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002539 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002540
Richard Smith87d263e2016-12-25 08:05:23 +00002541 return ::FinishTemplateArgumentDeduction(
2542 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002543}
Douglas Gregor91772d12009-06-13 00:26:55 +00002544
Larisse Voufo39a1e502013-08-06 01:03:05 +00002545/// \brief Perform template argument deduction to determine whether
2546/// the given template arguments match the given variable template
2547/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002548Sema::TemplateDeductionResult
2549Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2550 const TemplateArgumentList &TemplateArgs,
2551 TemplateDeductionInfo &Info) {
2552 if (Partial->isInvalidDecl())
2553 return TDK_Invalid;
2554
2555 // C++ [temp.class.spec.match]p2:
2556 // A partial specialization matches a given actual template
2557 // argument list if the template arguments of the partial
2558 // specialization can be deduced from the actual template argument
2559 // list (14.8.2).
2560
2561 // Unevaluated SFINAE context.
2562 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2563 SFINAETrap Trap(*this);
2564
2565 SmallVector<DeducedTemplateArgument, 4> Deduced;
2566 Deduced.resize(Partial->getTemplateParameters()->size());
2567 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2568 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2569 TemplateArgs, Info, Deduced))
2570 return Result;
2571
2572 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002573 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2574 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002575 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002576 return TDK_InstantiationDepth;
2577
2578 if (Trap.hasErrorOccurred())
2579 return Sema::TDK_SubstitutionFailure;
2580
Richard Smith87d263e2016-12-25 08:05:23 +00002581 return ::FinishTemplateArgumentDeduction(
2582 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002583}
2584
Douglas Gregorfc516c92009-06-26 23:27:24 +00002585/// \brief Determine whether the given type T is a simple-template-id type.
2586static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002587 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002588 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002589 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Douglas Gregorfc516c92009-06-26 23:27:24 +00002591 return false;
2592}
Douglas Gregor9b146582009-07-08 20:55:45 +00002593
Richard Smithde0d34a2017-01-09 07:14:40 +00002594static void
2595MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
2596 bool OnlyDeduced,
2597 unsigned Level,
2598 llvm::SmallBitVector &Deduced);
2599
Douglas Gregor9b146582009-07-08 20:55:45 +00002600/// \brief Substitute the explicitly-provided template arguments into the
2601/// given function template according to C++ [temp.arg.explicit].
2602///
2603/// \param FunctionTemplate the function template into which the explicit
2604/// template arguments will be substituted.
2605///
James Dennett634962f2012-06-14 21:40:34 +00002606/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002607/// arguments.
2608///
Mike Stump11289f42009-09-09 15:08:12 +00002609/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002610/// with the converted and checked explicit template arguments.
2611///
Mike Stump11289f42009-09-09 15:08:12 +00002612/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002613/// parameters.
2614///
2615/// \param FunctionType if non-NULL, the result type of the function template
2616/// will also be instantiated and the pointed-to value will be updated with
2617/// the instantiated function type.
2618///
2619/// \param Info if substitution fails for any reason, this object will be
2620/// populated with more information about the failure.
2621///
2622/// \returns TDK_Success if substitution was successful, or some failure
2623/// condition.
2624Sema::TemplateDeductionResult
2625Sema::SubstituteExplicitTemplateArguments(
2626 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002627 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002628 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2629 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002630 QualType *FunctionType,
2631 TemplateDeductionInfo &Info) {
2632 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2633 TemplateParameterList *TemplateParams
2634 = FunctionTemplate->getTemplateParameters();
2635
John McCall6b51f282009-11-23 01:53:49 +00002636 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002637 // No arguments to substitute; just copy over the parameter types and
2638 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002639 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002640 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002641
Douglas Gregor9b146582009-07-08 20:55:45 +00002642 if (FunctionType)
2643 *FunctionType = Function->getType();
2644 return TDK_Success;
2645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
Eli Friedman77dcc722012-02-08 03:07:05 +00002647 // Unevaluated SFINAE context.
2648 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002649 SFINAETrap Trap(*this);
2650
Douglas Gregor9b146582009-07-08 20:55:45 +00002651 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002652 // Template arguments that are present shall be specified in the
2653 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002654 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002655 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002656 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002657
2658 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002659 // explicitly-specified template arguments against this function template,
2660 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002661 SmallVector<TemplateArgument, 4> DeducedArgs;
Nick Lewycky56412332014-01-11 02:37:12 +00002662 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2663 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002664 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2665 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002666 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002667 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002668
Richard Smith11255ec2017-01-18 19:19:22 +00002669 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2670 ExplicitTemplateArgs, true, Builder, false) ||
2671 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002672 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002673 if (Index >= TemplateParams->size())
2674 Index = TemplateParams->size() - 1;
2675 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002676 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002677 }
Mike Stump11289f42009-09-09 15:08:12 +00002678
Douglas Gregor9b146582009-07-08 20:55:45 +00002679 // Form the template argument list from the explicitly-specified
2680 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002681 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002682 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002683 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002684
John McCall036855a2010-10-12 19:40:14 +00002685 // Template argument deduction and the final substitution should be
2686 // done in the context of the templated declaration. Explicit
2687 // argument substitution, on the other hand, needs to happen in the
2688 // calling context.
2689 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2690
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002691 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002692 // note that the template argument pack is partially substituted and record
2693 // the explicit template arguments. They'll be used as part of deduction
2694 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002695 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2696 const TemplateArgument &Arg = Builder[I];
2697 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002698 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002699 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002700 Arg.pack_begin(),
2701 Arg.pack_size());
2702 break;
2703 }
2704 }
2705
Richard Smith5e580292012-02-10 09:58:53 +00002706 const FunctionProtoType *Proto
2707 = Function->getType()->getAs<FunctionProtoType>();
2708 assert(Proto && "Function template does not have a prototype?");
2709
Richard Smith70b13042015-01-09 01:19:56 +00002710 // Isolate our substituted parameters from our caller.
2711 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2712
John McCallc8e321d2016-03-01 02:09:25 +00002713 ExtParameterInfoBuilder ExtParamInfos;
2714
Douglas Gregor9b146582009-07-08 20:55:45 +00002715 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002716 // explicitly-specified template arguments. If the function has a trailing
2717 // return type, substitute it after the arguments to ensure we substitute
2718 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002719 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002720 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002721 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002722 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002723 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002724 return TDK_SubstitutionFailure;
2725 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002726
Richard Smith5e580292012-02-10 09:58:53 +00002727 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002728 QualType ResultType;
2729 {
2730 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002731 // If a declaration declares a member function or member function
2732 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002733 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002734 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002735 // declarator.
2736 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002737 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2739 ThisContext = Method->getParent();
2740 ThisTypeQuals = Method->getTypeQualifiers();
2741 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002742
Douglas Gregor3024f072012-04-16 07:05:22 +00002743 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002744 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002745
2746 ResultType =
2747 SubstType(Proto->getReturnType(),
2748 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2749 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002750 if (ResultType.isNull() || Trap.hasErrorOccurred())
2751 return TDK_SubstitutionFailure;
2752 }
John McCallc8e321d2016-03-01 02:09:25 +00002753
Richard Smith5e580292012-02-10 09:58:53 +00002754 // Instantiate the types of each of the function parameters given the
2755 // explicitly-specified template arguments if we didn't do so earlier.
2756 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002757 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002758 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002759 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002760 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002761 return TDK_SubstitutionFailure;
2762
Douglas Gregor9b146582009-07-08 20:55:45 +00002763 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002764 auto EPI = Proto->getExtProtoInfo();
2765 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002766 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002767 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002768 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002769 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002770 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2771 return TDK_SubstitutionFailure;
2772 }
Mike Stump11289f42009-09-09 15:08:12 +00002773
Douglas Gregor9b146582009-07-08 20:55:45 +00002774 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002775 // Trailing template arguments that can be deduced (14.8.2) may be
2776 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002777 // template arguments can be deduced, they may all be omitted; in this
2778 // case, the empty template argument list <> itself may also be omitted.
2779 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002780 // Take all of the explicitly-specified arguments and put them into
2781 // the set of deduced template arguments. Explicitly-specified
2782 // parameter packs, however, will be set to NULL since the deduction
2783 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002784 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002785 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2786 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2787 if (Arg.getKind() == TemplateArgument::Pack)
2788 Deduced.push_back(DeducedTemplateArgument());
2789 else
2790 Deduced.push_back(Arg);
2791 }
Mike Stump11289f42009-09-09 15:08:12 +00002792
Douglas Gregor9b146582009-07-08 20:55:45 +00002793 return TDK_Success;
2794}
2795
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002796/// \brief Check whether the deduced argument type for a call to a function
2797/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002798static bool
2799CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002800 QualType DeducedA) {
2801 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002802
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002803 QualType A = OriginalArg.OriginalArgType;
2804 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002805
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002806 // Check for type equality (top-level cv-qualifiers are ignored).
2807 if (Context.hasSameUnqualifiedType(A, DeducedA))
2808 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002809
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002810 // Strip off references on the argument types; they aren't needed for
2811 // the following checks.
2812 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2813 DeducedA = DeducedARef->getPointeeType();
2814 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2815 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002816
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002817 // C++ [temp.deduct.call]p4:
2818 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002819 // - If the original P is a reference type, the deduced A (i.e., the
2820 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002821 // the transformed A.
2822 if (const ReferenceType *OriginalParamRef
2823 = OriginalParamType->getAs<ReferenceType>()) {
2824 // We don't want to keep the reference around any more.
2825 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002826
Richard Smith1be59c52016-10-22 01:32:19 +00002827 // FIXME: Resolve core issue (no number yet): if the original P is a
2828 // reference type and the transformed A is function type "noexcept F",
2829 // the deduced A can be F.
2830 QualType Tmp;
2831 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2832 return false;
2833
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002834 Qualifiers AQuals = A.getQualifiers();
2835 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002836
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002837 // Under Objective-C++ ARC, the deduced type may have implicitly
2838 // been given strong or (when dealing with a const reference)
2839 // unsafe_unretained lifetime. If so, update the original
2840 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002841 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002842 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2843 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2844 (DeducedAQuals.hasConst() &&
2845 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2846 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002847 }
2848
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002849 if (AQuals == DeducedAQuals) {
2850 // Qualifiers match; there's nothing to do.
2851 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002852 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002853 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002854 // Qualifiers are compatible, so have the argument type adopt the
2855 // deduced argument type's qualifiers as if we had performed the
2856 // qualification conversion.
2857 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2858 }
2859 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002860
2861 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002862 // type that can be converted to the deduced A via a function pointer
2863 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002864 //
Richard Smith1be59c52016-10-22 01:32:19 +00002865 // Also allow conversions which merely strip __attribute__((noreturn)) from
2866 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002867 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002868 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002869 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002870 (S.IsQualificationConversion(A, DeducedA, false,
2871 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002872 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002873 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002874
Simon Pilgrim728134c2016-08-12 11:43:57 +00002875 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002876 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002877 // [...] Likewise, if P is a pointer to a class of the form
2878 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002879 // derived class pointed to by the deduced A.
2880 if (const PointerType *OriginalParamPtr
2881 = OriginalParamType->getAs<PointerType>()) {
2882 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2883 if (const PointerType *APtr = A->getAs<PointerType>()) {
2884 if (A->getPointeeType()->isRecordType()) {
2885 OriginalParamType = OriginalParamPtr->getPointeeType();
2886 DeducedA = DeducedAPtr->getPointeeType();
2887 A = APtr->getPointeeType();
2888 }
2889 }
2890 }
2891 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002892
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002893 if (Context.hasSameUnqualifiedType(A, DeducedA))
2894 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002895
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002896 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002897 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002898 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002899
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002900 return true;
2901}
2902
Richard Smithc92d2062017-01-05 23:02:44 +00002903/// Find the pack index for a particular parameter index in an instantiation of
2904/// a function template with specific arguments.
2905///
2906/// \return The pack index for whichever pack produced this parameter, or -1
2907/// if this was not produced by a parameter. Intended to be used as the
2908/// ArgumentPackSubstitutionIndex for further substitutions.
2909// FIXME: We should track this in OriginalCallArgs so we don't need to
2910// reconstruct it here.
2911static unsigned getPackIndexForParam(Sema &S,
2912 FunctionTemplateDecl *FunctionTemplate,
2913 const MultiLevelTemplateArgumentList &Args,
2914 unsigned ParamIdx) {
2915 unsigned Idx = 0;
2916 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2917 if (PD->isParameterPack()) {
2918 unsigned NumExpansions =
2919 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2920 if (Idx + NumExpansions > ParamIdx)
2921 return ParamIdx - Idx;
2922 Idx += NumExpansions;
2923 } else {
2924 if (Idx == ParamIdx)
2925 return -1; // Not a pack expansion
2926 ++Idx;
2927 }
2928 }
2929
2930 llvm_unreachable("parameter index would not be produced from template");
2931}
2932
Mike Stump11289f42009-09-09 15:08:12 +00002933/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002934/// checking the deduced template arguments for completeness and forming
2935/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002936///
2937/// \param OriginalCallArgs If non-NULL, the original call arguments against
2938/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00002939Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
2940 FunctionTemplateDecl *FunctionTemplate,
2941 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2942 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
2943 TemplateDeductionInfo &Info,
2944 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2945 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002946 // Unevaluated SFINAE context.
2947 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002948 SFINAETrap Trap(*this);
2949
Douglas Gregor9b146582009-07-08 20:55:45 +00002950 // Enter a new template instantiation context while we instantiate the
2951 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002952 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002953 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2954 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002955 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2956 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002957 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002958 return TDK_InstantiationDepth;
2959
John McCalle23b8712010-04-29 01:18:58 +00002960 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002961
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002962 // C++ [temp.deduct.type]p2:
2963 // [...] or if any template argument remains neither deduced nor
2964 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002965 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002966 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002967 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002968 CurrentInstantiationScope, NumExplicitlySpecified,
2969 PartialOverloading))
2970 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002971
Richard Smith6eedfe72017-01-09 08:01:21 +00002972 // C++ [temp.deduct.call]p10: [DR1391]
2973 // If deduction succeeds for all parameters that contain
2974 // template-parameters that participate in template argument deduction,
2975 // and all template arguments are explicitly specified, deduced, or
2976 // obtained from default template arguments, remaining parameters are then
2977 // compared with the corresponding arguments. For each remaining parameter
2978 // P with a type that was non-dependent before substitution of any
2979 // explicitly-specified template arguments, if the corresponding argument
2980 // A cannot be implicitly converted to P, deduction fails.
2981 if (CheckNonDependent())
2982 return TDK_NonDependentConversionFailure;
2983
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002984 // Form the template argument list from the deduced template arguments.
2985 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002986 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002987 Info.reset(DeducedArgumentList);
2988
Mike Stump11289f42009-09-09 15:08:12 +00002989 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002990 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002991 DeclContext *Owner = FunctionTemplate->getDeclContext();
2992 if (FunctionTemplate->getFriendObjectKind())
2993 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00002994 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00002995 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00002996 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002997 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002998 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002999
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003001 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
Mike Stump11289f42009-09-09 15:08:12 +00003003 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003004 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003005 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3006 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003007 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003008
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003009 // There may have been an error that did not prevent us from constructing a
3010 // declaration. Mark the declaration invalid and return with a substitution
3011 // failure.
3012 if (Trap.hasErrorOccurred()) {
3013 Specialization->setInvalidDecl(true);
3014 return TDK_SubstitutionFailure;
3015 }
3016
Douglas Gregore65aacb2011-06-16 16:50:48 +00003017 if (OriginalCallArgs) {
3018 // C++ [temp.deduct.call]p4:
3019 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003020 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003021 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003022 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003023 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3024 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003025
Richard Smithc92d2062017-01-05 23:02:44 +00003026 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003027 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003028 // FIXME: This presumably means a pack ended up smaller than we
3029 // expected while deducing. Should this not result in deduction
3030 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003031 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003032
Richard Smithc92d2062017-01-05 23:02:44 +00003033 QualType DeducedA;
3034 if (!OriginalArg.DecomposedParam) {
3035 // P is one of the function parameters, just look up its substituted
3036 // type.
3037 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3038 } else {
3039 // P is a decomposed element of a parameter corresponding to a
3040 // braced-init-list argument. Substitute back into P to find the
3041 // deduced A.
3042 QualType &CacheEntry =
3043 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3044 if (CacheEntry.isNull()) {
3045 ArgumentPackSubstitutionIndexRAII PackIndex(
3046 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3047 ParamIdx));
3048 CacheEntry =
3049 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3050 Specialization->getTypeSpecStartLoc(),
3051 Specialization->getDeclName());
3052 }
3053 DeducedA = CacheEntry;
3054 }
3055
Richard Smith9b534542015-12-31 02:02:54 +00003056 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3057 Info.FirstArg = TemplateArgument(DeducedA);
3058 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3059 Info.CallArgIndex = OriginalArg.ArgIdx;
Richard Smithc92d2062017-01-05 23:02:44 +00003060 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3061 : TDK_DeducedMismatch;
Richard Smith9b534542015-12-31 02:02:54 +00003062 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003063 }
3064 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003065
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003066 // If we suppressed any diagnostics while performing template argument
3067 // deduction, and if we haven't already instantiated this declaration,
3068 // keep track of these diagnostics. They'll be emitted if this specialization
3069 // is actually used.
3070 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003071 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003072 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3073 if (Pos == SuppressedDiagnostics.end())
3074 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3075 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003077
Mike Stump11289f42009-09-09 15:08:12 +00003078 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003079}
3080
John McCall8d08b9b2010-08-27 09:08:28 +00003081/// Gets the type of a function for template-argument-deducton
3082/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003083static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003084 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003085 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003086 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003087 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003088 return QualType();
3089
John McCallc1f69982010-02-02 02:21:27 +00003090 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003091 if (Method->isInstance()) {
3092 // An instance method that's referenced in a form that doesn't
3093 // look like a member pointer is just invalid.
3094 if (!R.HasFormOfMemberPointer) return QualType();
3095
Richard Smith2a7d4812013-05-04 07:00:32 +00003096 return S.Context.getMemberPointerType(Fn->getType(),
3097 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003098 }
3099
3100 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003101 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003102}
3103
3104/// Apply the deduction rules for overload sets.
3105///
3106/// \return the null type if this argument should be treated as an
3107/// undeduced context
3108static QualType
3109ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003110 Expr *Arg, QualType ParamType,
3111 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112
John McCall8d08b9b2010-08-27 09:08:28 +00003113 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003114
John McCall8d08b9b2010-08-27 09:08:28 +00003115 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003116
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003117 // C++0x [temp.deduct.call]p4
3118 unsigned TDF = 0;
3119 if (ParamWasReference)
3120 TDF |= TDF_ParamWithReferenceType;
3121 if (R.IsAddressOfOperand)
3122 TDF |= TDF_IgnoreQualifiers;
3123
John McCallc1f69982010-02-02 02:21:27 +00003124 // C++0x [temp.deduct.call]p6:
3125 // When P is a function type, pointer to function type, or pointer
3126 // to member function type:
3127
3128 if (!ParamType->isFunctionType() &&
3129 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003130 !ParamType->isMemberFunctionPointerType()) {
3131 if (Ovl->hasExplicitTemplateArgs()) {
3132 // But we can still look for an explicit specialization.
3133 if (FunctionDecl *ExplicitSpec
3134 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003135 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003136 }
John McCallc1f69982010-02-02 02:21:27 +00003137
George Burgess IVcc2f3552016-03-19 21:51:45 +00003138 DeclAccessPair DAP;
3139 if (FunctionDecl *Viable =
3140 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3141 return GetTypeOfFunction(S, R, Viable);
3142
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003143 return QualType();
3144 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003145
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003146 // Gather the explicit template arguments, if any.
3147 TemplateArgumentListInfo ExplicitTemplateArgs;
3148 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003149 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003150 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003151 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3152 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003153 NamedDecl *D = (*I)->getUnderlyingDecl();
3154
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003155 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3156 // - If the argument is an overload set containing one or more
3157 // function templates, the parameter is treated as a
3158 // non-deduced context.
3159 if (!Ovl->hasExplicitTemplateArgs())
3160 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003161
3162 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003163 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003164 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003165 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3166 Specialization, Info))
3167 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003168
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003169 D = Specialization;
3170 }
John McCallc1f69982010-02-02 02:21:27 +00003171
3172 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003173 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003174 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003175
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003176 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003178 ArgType->isFunctionType())
3179 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
John McCallc1f69982010-02-02 02:21:27 +00003181 // - If the argument is an overload set (not containing function
3182 // templates), trial argument deduction is attempted using each
3183 // of the members of the set. If deduction succeeds for only one
3184 // of the overload set members, that member is used as the
3185 // argument value for the deduction. If deduction succeeds for
3186 // more than one member of the overload set the parameter is
3187 // treated as a non-deduced context.
3188
3189 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3190 // Type deduction is done independently for each P/A pair, and
3191 // the deduced template argument values are then combined.
3192 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003193 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003194 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003195 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003196 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003197 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3198 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003199 if (Result) continue;
3200 if (!Match.isNull()) return QualType();
3201 Match = ArgType;
3202 }
3203
3204 return Match;
3205}
3206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003208/// described in C++ [temp.deduct.call].
3209///
3210/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003211/// argument deduction based on this P/A pair because the argument is an
3212/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003213static bool AdjustFunctionParmAndArgTypesForDeduction(
3214 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3215 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003216 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003217 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003218 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003219 if (ParamType.hasQualifiers())
3220 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003221
3222 // [...] If P is a reference type, the type referred to by P is
3223 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003224 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003225 if (ParamRefType)
3226 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003227
Nathan Sidwell96090022015-01-16 15:20:14 +00003228 // Overload sets usually make this parameter an undeduced context,
3229 // but there are sometimes special circumstances. Typically
3230 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003231 if (ArgType == S.Context.OverloadTy) {
3232 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3233 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003234 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003235 if (ArgType.isNull())
3236 return true;
3237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238
Douglas Gregor7825bf32011-01-06 22:09:01 +00003239 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003240 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003241 if (ArgType->isIncompleteArrayType()) {
3242 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003243 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003244 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003245
Richard Smith32918772017-02-14 00:25:28 +00003246 // C++1z [temp.deduct.call]p3:
3247 // If P is a forwarding reference and the argument is an lvalue, the type
3248 // "lvalue reference to A" is used in place of A for type deduction.
3249 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003250 Arg->isLValue())
3251 ArgType = S.Context.getLValueReferenceType(ArgType);
3252 } else {
3253 // C++ [temp.deduct.call]p2:
3254 // If P is not a reference type:
3255 // - If A is an array type, the pointer type produced by the
3256 // array-to-pointer standard conversion (4.2) is used in place of
3257 // A for type deduction; otherwise,
3258 if (ArgType->isArrayType())
3259 ArgType = S.Context.getArrayDecayedType(ArgType);
3260 // - If A is a function type, the pointer type produced by the
3261 // function-to-pointer standard conversion (4.3) is used in place
3262 // of A for type deduction; otherwise,
3263 else if (ArgType->isFunctionType())
3264 ArgType = S.Context.getPointerType(ArgType);
3265 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003266 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003267 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003268 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003269 }
3270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271
Douglas Gregor7825bf32011-01-06 22:09:01 +00003272 // C++0x [temp.deduct.call]p4:
3273 // In general, the deduction process attempts to find template argument
3274 // values that will make the deduced A identical to A (after the type A
3275 // is transformed as described above). [...]
3276 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277
Douglas Gregor7825bf32011-01-06 22:09:01 +00003278 // - If the original P is a reference type, the deduced A (i.e., the
3279 // type referred to by the reference) can be more cv-qualified than
3280 // the transformed A.
3281 if (ParamRefType)
3282 TDF |= TDF_ParamWithReferenceType;
3283 // - The transformed A can be another pointer or pointer to member
3284 // type that can be converted to the deduced A via a qualification
3285 // conversion (4.4).
3286 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3287 ArgType->isObjCObjectPointerType())
3288 TDF |= TDF_IgnoreQualifiers;
3289 // - If P is a class and P has the form simple-template-id, then the
3290 // transformed A can be a derived class of the deduced A. Likewise,
3291 // if P is a pointer to a class of the form simple-template-id, the
3292 // transformed A can be a pointer to a derived class pointed to by
3293 // the deduced A.
3294 if (isSimpleTemplateIdType(ParamType) ||
3295 (isa<PointerType>(ParamType) &&
3296 isSimpleTemplateIdType(
3297 ParamType->getAs<PointerType>()->getPointeeType())))
3298 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003299
Douglas Gregor7825bf32011-01-06 22:09:01 +00003300 return false;
3301}
3302
Richard Smithf0393bf2017-02-16 04:22:56 +00003303static bool
3304hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3305 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003306
Richard Smith707eab62017-01-05 04:08:31 +00003307static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003308 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3309 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003310 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3311 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003312 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003313
3314/// \brief Attempt template argument deduction from an initializer list
3315/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003316static Sema::TemplateDeductionResult DeduceFromInitializerList(
3317 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3318 InitListExpr *ILE, TemplateDeductionInfo &Info,
3319 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003320 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3321 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003322 // C++ [temp.deduct.call]p1: (CWG 1591)
3323 // If removing references and cv-qualifiers from P gives
3324 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3325 // a non-empty initializer list, then deduction is performed instead for
3326 // each element of the initializer list, taking P0 as a function template
3327 // parameter type and the initializer element as its argument
3328 //
Richard Smith707eab62017-01-05 04:08:31 +00003329 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003330 if (!ILE->getNumInits())
3331 return Sema::TDK_Success;
3332
Richard Smitha7d5ec92017-01-04 19:47:19 +00003333 QualType ElTy;
3334 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3335 if (ArrTy)
3336 ElTy = ArrTy->getElementType();
3337 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3338 // Otherwise, an initializer list argument causes the parameter to be
3339 // considered a non-deduced context
3340 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003341 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003342
Faisal Valif6dfdb32015-12-10 05:36:39 +00003343 // Deduction only needs to be done for dependent types.
3344 if (ElTy->isDependentType()) {
3345 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003346 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003347 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003348 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003349 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003350 }
3351 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003352
3353 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3354 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003355 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003356 // Determine the array bound is something we can deduce.
3357 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003358 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003359 // We can perform template argument deduction for the given non-type
3360 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003361 // C++ [temp.deduct.type]p13:
3362 // The type of N in the type T[N] is std::size_t.
3363 QualType T = S.Context.getSizeType();
3364 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003365 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003366 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003367 /*ArrayBound=*/true, Info, Deduced))
3368 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003369 }
3370 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003371
3372 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003373}
3374
Richard Smith707eab62017-01-05 04:08:31 +00003375/// \brief Perform template argument deduction per [temp.deduct.call] for a
3376/// single parameter / argument pair.
3377static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003378 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3379 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003380 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3381 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003382 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003383 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003384 QualType OrigParamType = ParamType;
3385
3386 // If P is a reference type [...]
3387 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003388 if (AdjustFunctionParmAndArgTypesForDeduction(
3389 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003390 return Sema::TDK_Success;
3391
Richard Smith707eab62017-01-05 04:08:31 +00003392 // If [...] the argument is a non-empty initializer list [...]
3393 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3394 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003395 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003396
3397 // [...] the deduction process attempts to find template argument values
3398 // that will make the deduced A identical to A
3399 //
3400 // Keep track of the argument type and corresponding parameter index,
3401 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003402 OriginalCallArgs.push_back(
3403 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003404 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003405 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003406}
3407
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003408/// \brief Perform template argument deduction from a function call
3409/// (C++ [temp.deduct.call]).
3410///
3411/// \param FunctionTemplate the function template for which we are performing
3412/// template argument deduction.
3413///
James Dennett18348b62012-06-22 08:52:37 +00003414/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003415/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003416///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003417/// \param Args the function call arguments
3418///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003419/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003420/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003421/// template argument deduction.
3422///
3423/// \param Info the argument will be updated to provide additional information
3424/// about template argument deduction.
3425///
Richard Smith6eedfe72017-01-09 08:01:21 +00003426/// \param CheckNonDependent A callback to invoke to check conversions for
3427/// non-dependent parameters, between deduction and substitution, per DR1391.
3428/// If this returns true, substitution will be skipped and we return
3429/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3430/// types (after substituting explicit template arguments).
3431///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003432/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003433Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3434 FunctionTemplateDecl *FunctionTemplate,
3435 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003436 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003437 bool PartialOverloading,
3438 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003439 if (FunctionTemplate->isInvalidDecl())
3440 return TDK_Invalid;
3441
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003442 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003443 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003444
Richard Smith32918772017-02-14 00:25:28 +00003445 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3446
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003447 // C++ [temp.deduct.call]p1:
3448 // Template argument deduction is done by comparing each function template
3449 // parameter type (call it P) with the type of the corresponding argument
3450 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003451 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003452 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003453 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003454 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003455 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003456 if (Proto->isTemplateVariadic())
3457 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003458 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003459 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Douglas Gregor89026b52009-06-30 23:57:56 +00003462 // The types of the parameters from which we will perform template argument
3463 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003464 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003465 TemplateParameterList *TemplateParams
3466 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003467 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003468 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003469 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003470 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003471 TemplateDeductionResult Result =
3472 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003473 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003474 Deduced,
3475 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003476 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003477 Info);
3478 if (Result)
3479 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003480
3481 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003482 } else {
3483 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003484 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003485 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3486 }
Mike Stump11289f42009-09-09 15:08:12 +00003487
Richard Smith6eedfe72017-01-09 08:01:21 +00003488 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003489
3490 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3491 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003492 // C++ [demp.deduct.call]p1: (DR1391)
3493 // Template argument deduction is done by comparing each function template
3494 // parameter that contains template-parameters that participate in
3495 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003496 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003497 return Sema::TDK_Success;
3498
Richard Smith707eab62017-01-05 04:08:31 +00003499 // ... with the type of the corresponding argument
3500 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003501 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003502 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003503 };
3504
Douglas Gregor89026b52009-06-30 23:57:56 +00003505 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003506 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003507 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003508 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003509 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003510 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003511
Richard Smitha7d5ec92017-01-04 19:47:19 +00003512 const PackExpansionType *ParamExpansion =
3513 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003514 if (!ParamExpansion) {
3515 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003516 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003517 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Richard Smith6eedfe72017-01-09 08:01:21 +00003519 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003520 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003521 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003522
Douglas Gregor7825bf32011-01-06 22:09:01 +00003523 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Richard Smithde0d34a2017-01-09 07:14:40 +00003526 QualType ParamPattern = ParamExpansion->getPattern();
3527 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3528 ParamPattern);
3529
Douglas Gregor7825bf32011-01-06 22:09:01 +00003530 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531 // For a function parameter pack that occurs at the end of the
3532 // parameter-declaration-list, the type A of each remaining argument of
3533 // the call is compared with the type P of the declarator-id of the
3534 // function parameter pack. Each comparison deduces template arguments
3535 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003536 // the function parameter pack. When a function parameter pack appears
3537 // in a non-deduced context [not at the end of the list], the type of
3538 // that parameter pack is never deduced.
3539 //
3540 // FIXME: The above rule allows the size of the parameter pack to change
3541 // after we skip it (in the non-deduced case). That makes no sense, so
3542 // we instead notionally deduce the pack against N arguments, where N is
3543 // the length of the explicitly-specified pack if it's expanded by the
3544 // parameter pack and 0 otherwise, and we treat each deduction as a
3545 // non-deduced context.
3546 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003547 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3548 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003549 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3550 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003551 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003552 } else {
3553 // If the parameter type contains an explicitly-specified pack that we
3554 // could not expand, skip the number of parameters notionally created
3555 // by the expansion.
3556 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003557 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003558 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003559 ++I, ++ArgIdx) {
3560 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003561 // FIXME: Should we add OriginalCallArgs for these? What if the
3562 // corresponding argument is a list?
3563 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003564 }
3565 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567
Douglas Gregor7825bf32011-01-06 22:09:01 +00003568 // Build argument packs for each of the parameter packs expanded by this
3569 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003570 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003572 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003573
Richard Smith6eedfe72017-01-09 08:01:21 +00003574 return FinishTemplateArgumentDeduction(
3575 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3576 &OriginalCallArgs, PartialOverloading,
3577 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003578}
3579
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003580QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003581 QualType FunctionType,
3582 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003583 if (ArgFunctionType.isNull())
3584 return ArgFunctionType;
3585
3586 const FunctionProtoType *FunctionTypeP =
3587 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003588 const FunctionProtoType *ArgFunctionTypeP =
3589 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003590
3591 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3592 bool Rebuild = false;
3593
3594 CallingConv CC = FunctionTypeP->getCallConv();
3595 if (EPI.ExtInfo.getCC() != CC) {
3596 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3597 Rebuild = true;
3598 }
3599
3600 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3601 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3602 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3603 Rebuild = true;
3604 }
3605
3606 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3607 ArgFunctionTypeP->hasExceptionSpec())) {
3608 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3609 Rebuild = true;
3610 }
3611
3612 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003613 return ArgFunctionType;
3614
Richard Smithbaa47832016-12-01 02:11:49 +00003615 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3616 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003617}
3618
Douglas Gregor9b146582009-07-08 20:55:45 +00003619/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003620/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3621/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003622///
3623/// \param FunctionTemplate the function template for which we are performing
3624/// template argument deduction.
3625///
James Dennett18348b62012-06-22 08:52:37 +00003626/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003627/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003628///
3629/// \param ArgFunctionType the function type that will be used as the
3630/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003631/// function template's function type. This type may be NULL, if there is no
3632/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003633///
3634/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003635/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003636/// template argument deduction.
3637///
3638/// \param Info the argument will be updated to provide additional information
3639/// about template argument deduction.
3640///
Richard Smithbaa47832016-12-01 02:11:49 +00003641/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3642/// the address of a function template per [temp.deduct.funcaddr] and
3643/// [over.over]. If \c false, we are looking up a function template
3644/// specialization based on its signature, per [temp.deduct.decl].
3645///
Douglas Gregor9b146582009-07-08 20:55:45 +00003646/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003647Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3648 FunctionTemplateDecl *FunctionTemplate,
3649 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3650 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3651 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003652 if (FunctionTemplate->isInvalidDecl())
3653 return TDK_Invalid;
3654
Douglas Gregor9b146582009-07-08 20:55:45 +00003655 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3656 TemplateParameterList *TemplateParams
3657 = FunctionTemplate->getTemplateParameters();
3658 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003659
3660 // When taking the address of a function, we require convertibility of
3661 // the resulting function type. Otherwise, we allow arbitrary mismatches
3662 // of calling convention, noreturn, and noexcept.
3663 if (!IsAddressOfFunction)
3664 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3665 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003666
Douglas Gregor9b146582009-07-08 20:55:45 +00003667 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003668 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003669 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003670 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003671 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003672 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003673 if (TemplateDeductionResult Result
3674 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003675 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003676 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003677 &FunctionType, Info))
3678 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003679
3680 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003681 }
3682
Eli Friedman77dcc722012-02-08 03:07:05 +00003683 // Unevaluated SFINAE context.
3684 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003685 SFINAETrap Trap(*this);
3686
John McCallc1f69982010-02-02 02:21:27 +00003687 Deduced.resize(TemplateParams->size());
3688
Richard Smith2a7d4812013-05-04 07:00:32 +00003689 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003690 // type so that we treat it as a non-deduced context in what follows. If we
3691 // are looking up by signature, the signature type should also have a deduced
3692 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003693 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003694 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003695 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003696 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003697 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003698 }
3699
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003700 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003701 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003702 if (IsAddressOfFunction)
3703 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003704 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003705 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003706 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003707 FunctionType, ArgFunctionType,
3708 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003709 return Result;
3710 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003711
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003712 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003713 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3714 NumExplicitlySpecified,
3715 Specialization, Info))
3716 return Result;
3717
Richard Smith2a7d4812013-05-04 07:00:32 +00003718 // If the function has a deduced return type, deduce it now, so we can check
3719 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003720 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003721 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003722 DeduceReturnType(Specialization, Info.getLocation(), false))
3723 return TDK_MiscellaneousDeductionFailure;
3724
Richard Smith9095e5b2016-11-01 01:31:23 +00003725 // If the function has a dependent exception specification, resolve it now,
3726 // so we can check that the exception specification matches.
3727 auto *SpecializationFPT =
3728 Specialization->getType()->castAs<FunctionProtoType>();
3729 if (getLangOpts().CPlusPlus1z &&
3730 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3731 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3732 return TDK_MiscellaneousDeductionFailure;
3733
Richard Smithbaa47832016-12-01 02:11:49 +00003734 // Adjust the exception specification of the argument again to match the
3735 // substituted and resolved type we just formed. (Calling convention and
3736 // noreturn can't be dependent, so we don't actually need this for them
3737 // right now.)
3738 QualType SpecializationType = Specialization->getType();
3739 if (!IsAddressOfFunction)
3740 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3741 /*AdjustExceptionSpec*/true);
3742
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003743 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003744 // specialization with respect to arguments of compatible pointer to function
3745 // types, template argument deduction fails.
3746 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003747 if (IsAddressOfFunction &&
3748 !isSameOrCompatibleFunctionType(
3749 Context.getCanonicalType(SpecializationType),
3750 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003751 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003752
3753 if (!IsAddressOfFunction &&
3754 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003755 return TDK_MiscellaneousDeductionFailure;
3756 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003757
3758 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003759}
3760
Simon Pilgrim728134c2016-08-12 11:43:57 +00003761/// \brief Given a function declaration (e.g. a generic lambda conversion
3762/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003763/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3764/// to replace 'auto' with and not the actual result type you want
3765/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003766static inline void
3767SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003768 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003769 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003770 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003771 assert(AutoResultType->getContainedAutoType());
3772 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003773 TypeToReplaceAutoWith);
3774 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3775}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776
Simon Pilgrim728134c2016-08-12 11:43:57 +00003777/// \brief Given a specialized conversion operator of a generic lambda
3778/// create the corresponding specializations of the call operator and
3779/// the static-invoker. If the return type of the call operator is auto,
3780/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003781/// return type of the destination function ptr.
3782
Simon Pilgrim728134c2016-08-12 11:43:57 +00003783static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003784SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3785 CXXConversionDecl *ConversionSpecialized,
3786 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3787 QualType ReturnTypeOfDestFunctionPtr,
3788 TemplateDeductionInfo &TDInfo,
3789 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003790
Faisal Vali2b3a3012013-10-24 23:40:02 +00003791 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003792 assert(LambdaClass && LambdaClass->isGenericLambda());
3793
Faisal Vali2b3a3012013-10-24 23:40:02 +00003794 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003795 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003796 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003797 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003798
3799 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003800 CallOpGeneric->getDescribedFunctionTemplate();
3801
Craig Topperc3ec1492014-05-26 06:22:03 +00003802 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003803 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003804 // generic lambda's call operator.
3805 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003806 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3807 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003808 0, CallOpSpecialized, TDInfo))
3809 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003810
Faisal Vali2b3a3012013-10-24 23:40:02 +00003811 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003812 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3813 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003814 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003815 CallOpSpecialized->getPointOfInstantiation(),
3816 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003817
Faisal Vali2b3a3012013-10-24 23:40:02 +00003818 // Check to see if the return type of the destination ptr-to-function
3819 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003820 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003821 ReturnTypeOfDestFunctionPtr))
3822 return Sema::TDK_NonDeducedMismatch;
3823 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003824 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003825 // specialized our corresponding call operator, we are ready to
3826 // specialize the static invoker with the deduced arguments of our
3827 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003828 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003829 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3830 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3831
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003832#ifndef NDEBUG
3833 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3834#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003835 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003836 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003837 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003838 "If the call operator succeeded so should the invoker!");
3839 // Set the result type to match the corresponding call operator
3840 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003841 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3842 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003843 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003844 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003845 // to substitute into the 'auto' of the invoker and conversion
3846 // function.
3847 // For e.g.
3848 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3849 // We don't want to subst 'int*' into 'auto' to get int**.
3850
Alp Toker314cc812014-01-25 16:55:45 +00003851 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3852 ->getContainedAutoType()
3853 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003854 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3855 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003856 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003857 TypeToReplaceAutoWith, S);
3858 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003859
Faisal Vali2b3a3012013-10-24 23:40:02 +00003860 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003861 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003862 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003863 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003864 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3865 getType().getTypePtr()->castAs<FunctionProtoType>();
3866 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3867 EPI.TypeQuals = 0;
3868 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003869 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003870 return Sema::TDK_Success;
3871}
Douglas Gregor05155d82009-08-21 23:19:43 +00003872/// \brief Deduce template arguments for a templated conversion
3873/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3874/// conversion function template specialization.
3875Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003876Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003877 QualType ToType,
3878 CXXConversionDecl *&Specialization,
3879 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003880 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003881 return TDK_Invalid;
3882
Faisal Vali2b3a3012013-10-24 23:40:02 +00003883 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003884 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3885
Faisal Vali2b3a3012013-10-24 23:40:02 +00003886 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003887
3888 // Canonicalize the types for deduction.
3889 QualType P = Context.getCanonicalType(FromType);
3890 QualType A = Context.getCanonicalType(ToType);
3891
Douglas Gregord99609a2011-03-06 09:03:20 +00003892 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003893 // If P is a reference type, the type referred to by P is used for
3894 // type deduction.
3895 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3896 P = PRef->getPointeeType();
3897
Douglas Gregord99609a2011-03-06 09:03:20 +00003898 // C++0x [temp.deduct.conv]p4:
3899 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003900 // for type deduction.
3901 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003902 A = ARef->getPointeeType().getUnqualifiedType();
3903 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003904 //
Mike Stump11289f42009-09-09 15:08:12 +00003905 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003906 else {
3907 assert(!A->isReferenceType() && "Reference types were handled above");
3908
3909 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003910 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003911 // of P for type deduction; otherwise,
3912 if (P->isArrayType())
3913 P = Context.getArrayDecayedType(P);
3914 // - If P is a function type, the pointer type produced by the
3915 // function-to-pointer standard conversion (4.3) is used in
3916 // place of P for type deduction; otherwise,
3917 else if (P->isFunctionType())
3918 P = Context.getPointerType(P);
3919 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003920 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003921 else
3922 P = P.getUnqualifiedType();
3923
Douglas Gregord99609a2011-03-06 09:03:20 +00003924 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003925 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003926 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003927 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003928 A = A.getUnqualifiedType();
3929 }
3930
Eli Friedman77dcc722012-02-08 03:07:05 +00003931 // Unevaluated SFINAE context.
3932 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003933 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003934
3935 // C++ [temp.deduct.conv]p1:
3936 // Template argument deduction is done by comparing the return
3937 // type of the template conversion function (call it P) with the
3938 // type that is required as the result of the conversion (call it
3939 // A) as described in 14.8.2.4.
3940 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003941 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003942 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003943 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003944
3945 // C++0x [temp.deduct.conv]p4:
3946 // In general, the deduction process attempts to find template
3947 // argument values that will make the deduced A identical to
3948 // A. However, there are two cases that allow a difference:
3949 unsigned TDF = 0;
3950 // - If the original A is a reference type, A can be more
3951 // cv-qualified than the deduced A (i.e., the type referred to
3952 // by the reference)
3953 if (ToType->isReferenceType())
3954 TDF |= TDF_ParamWithReferenceType;
3955 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003956 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003957 // conversion.
3958 //
3959 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3960 // both P and A are pointers or member pointers. In this case, we
3961 // just ignore cv-qualifiers completely).
3962 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003963 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003964 TDF |= TDF_IgnoreQualifiers;
3965 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003966 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3967 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003968 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003969
3970 // Create an Instantiation Scope for finalizing the operator.
3971 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003972 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003973 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003974 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003975 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003976 ConversionSpecialized, Info);
3977 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3978
3979 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003980 // to a ptr-to-function, use the deduced arguments from the conversion
3981 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003982 // e.g., int (*fp)(int) = [](auto a) { return a; };
3983 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003984
Faisal Vali2b3a3012013-10-24 23:40:02 +00003985 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003986 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003987 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003988 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003989 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003990 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003991 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003992 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3993
Simon Pilgrim728134c2016-08-12 11:43:57 +00003994 // Create the corresponding specializations of the call operator and
3995 // the static-invoker; and if the return type is auto,
3996 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003997 // DestFunctionPtrReturnType.
3998 // For instance:
3999 // auto L = [](auto a) { return f(a); };
4000 // int (*fp)(int) = L;
4001 // char (*fp2)(int) = L; <-- Not OK.
4002
4003 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00004004 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004005 Info, *this);
4006 }
Douglas Gregor05155d82009-08-21 23:19:43 +00004007 return Result;
4008}
4009
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004010/// \brief Deduce template arguments for a function template when there is
4011/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4012///
4013/// \param FunctionTemplate the function template for which we are performing
4014/// template argument deduction.
4015///
James Dennett18348b62012-06-22 08:52:37 +00004016/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004017/// arguments.
4018///
4019/// \param Specialization if template argument deduction was successful,
4020/// this will be set to the function template specialization produced by
4021/// template argument deduction.
4022///
4023/// \param Info the argument will be updated to provide additional information
4024/// about template argument deduction.
4025///
Richard Smithbaa47832016-12-01 02:11:49 +00004026/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4027/// the address of a function template in a context where we do not have a
4028/// target type, per [over.over]. If \c false, we are looking up a function
4029/// template specialization based on its signature, which only happens when
4030/// deducing a function parameter type from an argument that is a template-id
4031/// naming a function template specialization.
4032///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004033/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004034Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4035 FunctionTemplateDecl *FunctionTemplate,
4036 TemplateArgumentListInfo *ExplicitTemplateArgs,
4037 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4038 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004039 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004040 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004041 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004042}
4043
Richard Smith30482bc2011-02-20 03:19:35 +00004044namespace {
Richard Smith60437622017-02-09 19:17:44 +00004045 /// Substitute the 'auto' specifier or deduced template specialization type
4046 /// specifier within a type for a given replacement type.
4047 class SubstituteDeducedTypeTransform :
4048 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004049 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004050 bool UseTypeSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00004051 public:
Richard Smith60437622017-02-09 19:17:44 +00004052 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4053 bool UseTypeSugar = true)
4054 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4055 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4056
4057 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4058 assert(isa<TemplateTypeParmType>(Replacement) &&
4059 "unexpected unsugared replacement kind");
4060 QualType Result = Replacement;
4061 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4062 NewTL.setNameLoc(TL.getNameLoc());
4063 return Result;
4064 }
Nico Weberc153d242014-07-28 00:02:09 +00004065
Richard Smith30482bc2011-02-20 03:19:35 +00004066 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4067 // If we're building the type pattern to deduce against, don't wrap the
4068 // substituted type in an AutoType. Certain template deduction rules
4069 // apply only when a template type parameter appears directly (and not if
4070 // the parameter is found through desugaring). For instance:
4071 // auto &&lref = lvalue;
4072 // must transform into "rvalue reference to T" not "rvalue reference to
4073 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004074 //
4075 // FIXME: Is this still necessary?
4076 if (!UseTypeSugar)
4077 return TransformDesugared(TLB, TL);
4078
4079 QualType Result = SemaRef.Context.getAutoType(
4080 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4081 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4082 NewTL.setNameLoc(TL.getNameLoc());
4083 return Result;
4084 }
4085
4086 QualType TransformDeducedTemplateSpecializationType(
4087 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4088 if (!UseTypeSugar)
4089 return TransformDesugared(TLB, TL);
4090
4091 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4092 TL.getTypePtr()->getTemplateName(),
4093 Replacement, Replacement.isNull());
4094 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4095 NewTL.setNameLoc(TL.getNameLoc());
4096 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004097 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004098
4099 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4100 // Lambdas never need to be transformed.
4101 return E;
4102 }
Richard Smith061f1e22013-04-30 21:23:01 +00004103
Richard Smith2a7d4812013-05-04 07:00:32 +00004104 QualType Apply(TypeLoc TL) {
4105 // Create some scratch storage for the transformed type locations.
4106 // FIXME: We're just going to throw this information away. Don't build it.
4107 TypeLocBuilder TLB;
4108 TLB.reserve(TL.getFullDataSize());
4109 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004110 }
Richard Smith30482bc2011-02-20 03:19:35 +00004111 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004112}
Richard Smith30482bc2011-02-20 03:19:35 +00004113
Richard Smith2a7d4812013-05-04 07:00:32 +00004114Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004115Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4116 Optional<unsigned> DependentDeductionDepth) {
4117 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4118 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004119}
4120
Richard Smith061f1e22013-04-30 21:23:01 +00004121/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004122///
Richard Smith87d263e2016-12-25 08:05:23 +00004123/// Note that this is done even if the initializer is dependent. (This is
4124/// necessary to support partial ordering of templates using 'auto'.)
4125/// A dependent type will be produced when deducing from a dependent type.
4126///
Richard Smith30482bc2011-02-20 03:19:35 +00004127/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004128/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004129/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004130/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004131/// \param DependentDeductionDepth Set if we should permit deduction in
4132/// dependent cases. This is necessary for template partial ordering with
4133/// 'auto' template parameters. The value specified is the template
4134/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004135Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004136Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4137 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004138 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004139 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4140 if (NonPlaceholder.isInvalid())
4141 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004142 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004143 }
4144
Richard Smith87d263e2016-12-25 08:05:23 +00004145 if (!DependentDeductionDepth &&
4146 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004147 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004148 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004149 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004150 }
4151
Richard Smith87d263e2016-12-25 08:05:23 +00004152 // Find the depth of template parameter to synthesize.
4153 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4154
Richard Smith74aeef52013-04-26 16:15:35 +00004155 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4156 // Since 'decltype(auto)' can only occur at the top of the type, we
4157 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004158 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004159 if (AT->isDecltypeAuto()) {
4160 if (isa<InitListExpr>(Init)) {
4161 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4162 return DAR_FailedAlreadyDiagnosed;
4163 }
4164
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004165 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004166 if (Deduced.isNull())
4167 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004168 // FIXME: Support a non-canonical deduced type for 'auto'.
4169 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004170 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004171 if (Result.isNull())
4172 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004173 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004174 } else if (!getLangOpts().CPlusPlus) {
4175 if (isa<InitListExpr>(Init)) {
4176 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4177 return DAR_FailedAlreadyDiagnosed;
4178 }
Richard Smith74aeef52013-04-26 16:15:35 +00004179 }
4180 }
4181
Richard Smith30482bc2011-02-20 03:19:35 +00004182 SourceLocation Loc = Init->getExprLoc();
4183
4184 LocalInstantiationScope InstScope(*this);
4185
4186 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004187 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4188 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004189 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4190 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004191 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4192 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004193
Richard Smith87d263e2016-12-25 08:05:23 +00004194 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004195 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004196 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004197 assert(!FuncParam.isNull() &&
4198 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004199
4200 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004201 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004202 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004203
Richard Smith87d263e2016-12-25 08:05:23 +00004204 TemplateDeductionInfo Info(Loc, Depth);
4205
4206 // If deduction failed, don't diagnose if the initializer is dependent; it
4207 // might acquire a matching type in the instantiation.
4208 auto DeductionFailed = [&]() -> DeduceAutoResult {
4209 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004210 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004211 assert(!Result.isNull() && "substituting DependentTy can't fail");
4212 return DAR_Succeeded;
4213 }
4214 return DAR_Failed;
4215 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004216
Richard Smith707eab62017-01-05 04:08:31 +00004217 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4218
Richard Smith74801c82012-07-08 04:13:07 +00004219 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004220 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004221 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4222 // against that. Such deduction only succeeds if removing cv-qualifiers and
4223 // references results in std::initializer_list<T>.
4224 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4225 return DAR_Failed;
4226
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004227 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004228 if (DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004229 *this, TemplateParamsSt.get(), 0, TemplArg, InitList->getInit(i),
Richard Smithc92d2062017-01-05 23:02:44 +00004230 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4231 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004232 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004233 }
4234 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004235 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4236 Diag(Loc, diag::err_auto_bitfield);
4237 return DAR_FailedAlreadyDiagnosed;
4238 }
4239
Richard Smith707eab62017-01-05 04:08:31 +00004240 if (DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004241 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004242 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004243 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004244 }
Richard Smith30482bc2011-02-20 03:19:35 +00004245
Richard Smith87d263e2016-12-25 08:05:23 +00004246 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004247 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004248 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004249
Eli Friedmane4310952012-11-06 23:56:42 +00004250 QualType DeducedType = Deduced[0].getAsType();
4251
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004252 if (InitList) {
4253 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4254 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004255 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004256 }
4257
Richard Smith60437622017-02-09 19:17:44 +00004258 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004259 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004260 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004261
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004262 // Check that the deduced argument type is compatible with the original
4263 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004264 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004265 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004266 assert((bool)InitList == OriginalArg.DecomposedParam &&
4267 "decomposed non-init-list in auto deduction?");
4268 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004269 Result = QualType();
4270 return DeductionFailed();
4271 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004272 }
4273
Sebastian Redl09edce02012-01-23 22:09:39 +00004274 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004275}
4276
Simon Pilgrim728134c2016-08-12 11:43:57 +00004277QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004278 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004279 if (TypeToReplaceAuto->isDependentType())
4280 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004281 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004282 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004283}
4284
Richard Smith60437622017-02-09 19:17:44 +00004285TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4286 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004287 if (TypeToReplaceAuto->isDependentType())
4288 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004289 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004290 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004291}
4292
Richard Smith33c33c32017-02-04 01:28:01 +00004293QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4294 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004295 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4296 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004297 .TransformType(TypeWithAuto);
4298}
4299
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004300void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4301 if (isa<InitListExpr>(Init))
4302 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004303 VDecl->isInitCapture()
4304 ? diag::err_init_capture_deduction_failure_from_init_list
4305 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004306 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4307 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004308 Diag(VDecl->getLocation(),
4309 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4310 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004311 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4312 << Init->getSourceRange();
4313}
4314
Richard Smith2a7d4812013-05-04 07:00:32 +00004315bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4316 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004317 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004318
4319 if (FD->getTemplateInstantiationPattern())
4320 InstantiateFunctionDefinition(Loc, FD);
4321
Alp Toker314cc812014-01-25 16:55:45 +00004322 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004323 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4324 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4325 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4326 }
4327
4328 return StillUndeduced;
4329}
4330
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004332static void
4333AddImplicitObjectParameterType(ASTContext &Context,
4334 CXXMethodDecl *Method,
4335 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004336 // C++11 [temp.func.order]p3:
4337 // [...] The new parameter is of type "reference to cv A," where cv are
4338 // the cv-qualifiers of the function template (if any) and A is
4339 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004340 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004341 // The standard doesn't say explicitly, but we pick the appropriate kind of
4342 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004343 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4344 ArgTy = Context.getQualifiedType(ArgTy,
4345 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004346 if (Method->getRefQualifier() == RQ_RValue)
4347 ArgTy = Context.getRValueReferenceType(ArgTy);
4348 else
4349 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004350 ArgTypes.push_back(ArgTy);
4351}
4352
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004353/// \brief Determine whether the function template \p FT1 is at least as
4354/// specialized as \p FT2.
4355static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004356 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004357 FunctionTemplateDecl *FT1,
4358 FunctionTemplateDecl *FT2,
4359 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004360 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004361 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004363 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4364 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004366 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4367 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004368 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004369 Deduced.resize(TemplateParams->size());
4370
4371 // C++0x [temp.deduct.partial]p3:
4372 // The types used to determine the ordering depend on the context in which
4373 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004374 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004375 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004376 switch (TPOC) {
4377 case TPOC_Call: {
4378 // - In the context of a function call, the function parameter types are
4379 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004380 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4381 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004382
Eli Friedman3b5774a2012-09-19 23:27:04 +00004383 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004384 // [...] If only one of the function templates is a non-static
4385 // member, that function template is considered to have a new
4386 // first parameter inserted in its function parameter list. The
4387 // new parameter is of type "reference to cv A," where cv are
4388 // the cv-qualifiers of the function template (if any) and A is
4389 // the class of which the function template is a member.
4390 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004391 // Note that we interpret this to mean "if one of the function
4392 // templates is a non-static member and the other is a non-member";
4393 // otherwise, the ordering rules for static functions against non-static
4394 // functions don't make any sense.
4395 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004396 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4397 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004398 SmallVector<QualType, 4> Args1;
4399
Richard Smithe5b52202013-09-11 00:52:39 +00004400 unsigned NumComparedArguments = NumCallArguments1;
4401
4402 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004403 // Compare 'this' from Method1 against first parameter from Method2.
4404 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4405 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004406 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004407 // Compare 'this' from Method2 against first parameter from Method1.
4408 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004409 }
4410
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004411 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004412 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004413 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004414 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415
Douglas Gregorb837ea42011-01-11 17:34:58 +00004416 // C++ [temp.func.order]p5:
4417 // The presence of unused ellipsis and default arguments has no effect on
4418 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004419 if (Args1.size() > NumComparedArguments)
4420 Args1.resize(NumComparedArguments);
4421 if (Args2.size() > NumComparedArguments)
4422 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004423 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4424 Args1.data(), Args1.size(), Info, Deduced,
4425 TDF_None, /*PartialOrdering=*/true))
4426 return false;
4427
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004428 break;
4429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004431 case TPOC_Conversion:
4432 // - In the context of a call to a conversion operator, the return types
4433 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004434 if (DeduceTemplateArgumentsByTypeMatch(
4435 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4436 Info, Deduced, TDF_None,
4437 /*PartialOrdering=*/true))
4438 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004439 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004441 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004442 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004443 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004444 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4445 FD2->getType(), FD1->getType(),
4446 Info, Deduced, TDF_None,
4447 /*PartialOrdering=*/true))
4448 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004449 break;
4450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004452 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453 // In most cases, all template parameters must have values in order for
4454 // deduction to succeed, but for partial ordering purposes a template
4455 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004456 // types being used for partial ordering. [ Note: a template parameter used
4457 // in a non-deduced context is considered used. -end note]
4458 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4459 for (; ArgIdx != NumArgs; ++ArgIdx)
4460 if (Deduced[ArgIdx].isNull())
4461 break;
4462
Richard Smithf0393bf2017-02-16 04:22:56 +00004463 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4464 // to substitute the deduced arguments back into the template and check that
4465 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004466
Richard Smithf0393bf2017-02-16 04:22:56 +00004467 if (ArgIdx == NumArgs) {
4468 // All template arguments were deduced. FT1 is at least as specialized
4469 // as FT2.
4470 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004471 }
4472
Richard Smithf0393bf2017-02-16 04:22:56 +00004473 // Figure out which template parameters were used.
4474 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4475 switch (TPOC) {
4476 case TPOC_Call:
4477 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4478 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4479 TemplateParams->getDepth(),
4480 UsedParameters);
4481 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Richard Smithf0393bf2017-02-16 04:22:56 +00004483 case TPOC_Conversion:
4484 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4485 TemplateParams->getDepth(), UsedParameters);
4486 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004487
Richard Smithf0393bf2017-02-16 04:22:56 +00004488 case TPOC_Other:
4489 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4490 TemplateParams->getDepth(),
4491 UsedParameters);
4492 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004493 }
4494
Richard Smithf0393bf2017-02-16 04:22:56 +00004495 for (; ArgIdx != NumArgs; ++ArgIdx)
4496 // If this argument had no value deduced but was used in one of the types
4497 // used for partial ordering, then deduction fails.
4498 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4499 return false;
4500
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004501 return true;
4502}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregorcef1a032011-01-16 16:03:23 +00004504/// \brief Determine whether this a function template whose parameter-type-list
4505/// ends with a function parameter pack.
4506static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4507 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4508 unsigned NumParams = Function->getNumParams();
4509 if (NumParams == 0)
4510 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Douglas Gregorcef1a032011-01-16 16:03:23 +00004512 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4513 if (!Last->isParameterPack())
4514 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515
Douglas Gregorcef1a032011-01-16 16:03:23 +00004516 // Make sure that no previous parameter is a parameter pack.
4517 while (--NumParams > 0) {
4518 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4519 return false;
4520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
Douglas Gregorcef1a032011-01-16 16:03:23 +00004522 return true;
4523}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
Douglas Gregorbe999392009-09-15 16:23:51 +00004525/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004526/// to the rules of function template partial ordering (C++ [temp.func.order]).
4527///
4528/// \param FT1 the first function template
4529///
4530/// \param FT2 the second function template
4531///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004532/// \param TPOC the context in which we are performing partial ordering of
4533/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004534///
Richard Smithe5b52202013-09-11 00:52:39 +00004535/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4536/// only when \c TPOC is \c TPOC_Call.
4537///
4538/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4539/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004540///
Douglas Gregorbe999392009-09-15 16:23:51 +00004541/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004542/// template is more specialized, returns NULL.
4543FunctionTemplateDecl *
4544Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4545 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004546 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004547 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004548 unsigned NumCallArguments1,
4549 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004551 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004553 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004555 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004556 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004558 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004559 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004560
Douglas Gregorcef1a032011-01-16 16:03:23 +00004561 // FIXME: This mimics what GCC implements, but doesn't match up with the
4562 // proposed resolution for core issue 692. This area needs to be sorted out,
4563 // but for now we attempt to maintain compatibility.
4564 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4565 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4566 if (Variadic1 != Variadic2)
4567 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Craig Topperc3ec1492014-05-26 06:22:03 +00004569 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004570}
Douglas Gregor9b146582009-07-08 20:55:45 +00004571
Douglas Gregor450f00842009-09-25 18:43:00 +00004572/// \brief Determine if the two templates are equivalent.
4573static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4574 if (T1 == T2)
4575 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
Douglas Gregor450f00842009-09-25 18:43:00 +00004577 if (!T1 || !T2)
4578 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004579
Douglas Gregor450f00842009-09-25 18:43:00 +00004580 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4581}
4582
4583/// \brief Retrieve the most specialized of the given function template
4584/// specializations.
4585///
John McCall58cc69d2010-01-27 01:50:18 +00004586/// \param SpecBegin the start iterator of the function template
4587/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004588///
John McCall58cc69d2010-01-27 01:50:18 +00004589/// \param SpecEnd the end iterator of the function template
4590/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004591///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004592/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004593/// diagnostic should occur.
4594///
4595/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4596/// no matching candidates.
4597///
4598/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4599/// occurs.
4600///
4601/// \param CandidateDiag partial diagnostic used for each function template
4602/// specialization that is a candidate in the ambiguous ordering. One parameter
4603/// in this diagnostic should be unbound, which will correspond to the string
4604/// describing the template arguments for the function template specialization.
4605///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004607/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004608UnresolvedSetIterator Sema::getMostSpecialized(
4609 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4610 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004611 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4612 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4613 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004614 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004615 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004616 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004617 FailedCandidates.NoteCandidates(*this, Loc);
4618 }
John McCall58cc69d2010-01-27 01:50:18 +00004619 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
4622 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004623 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624
Douglas Gregor450f00842009-09-25 18:43:00 +00004625 // Find the function template that is better than all of the templates it
4626 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004627 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004629 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004630 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004631 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4632 FunctionTemplateDecl *Challenger
4633 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004634 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004635 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004636 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004637 Challenger)) {
4638 Best = I;
4639 BestTemplate = Challenger;
4640 }
4641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642
Douglas Gregor450f00842009-09-25 18:43:00 +00004643 // Make sure that the "best" function template is more specialized than all
4644 // of the others.
4645 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004646 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4647 FunctionTemplateDecl *Challenger
4648 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004649 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004651 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004652 BestTemplate)) {
4653 Ambiguous = true;
4654 break;
4655 }
4656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregor450f00842009-09-25 18:43:00 +00004658 if (!Ambiguous) {
4659 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004660 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Douglas Gregor450f00842009-09-25 18:43:00 +00004663 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004664 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004665 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666
Richard Smithb875c432013-05-04 01:51:08 +00004667 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004668 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4669 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004670 const auto *FD = cast<FunctionDecl>(*I);
4671 PD << FD << getTemplateArgumentBindingsText(
4672 FD->getPrimaryTemplate()->getTemplateParameters(),
4673 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004674 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004675 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004676 Diag((*I)->getLocation(), PD);
4677 }
Richard Smithb875c432013-05-04 01:51:08 +00004678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679
John McCall58cc69d2010-01-27 01:50:18 +00004680 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004681}
4682
Richard Smith0da6dc42016-12-24 16:40:51 +00004683/// Determine whether one partial specialization, P1, is at least as
4684/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004685///
Richard Smith26b86ea2016-12-31 21:41:23 +00004686/// \tparam TemplateLikeDecl The kind of P2, which must be a
4687/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004688/// \param T1 The injected-class-name of P1 (faked for a variable template).
4689/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004690template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004691static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004692 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004693 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004694 // C++ [temp.class.order]p1:
4695 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004696 // specialized as the second if, given the following rewrite to two
4697 // function templates, the first function template is at least as
4698 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004699 // templates (14.6.6.2):
4700 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701 // first partial specialization and has a single function parameter
4702 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004703 // arguments of the first partial specialization, and
4704 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705 // second partial specialization and has a single function parameter
4706 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004707 // arguments of the second partial specialization.
4708 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004709 // Rather than synthesize function templates, we merely perform the
4710 // equivalent partial ordering by performing deduction directly on
4711 // the template arguments of the class template partial
4712 // specializations. This computation is slightly simpler than the
4713 // general problem of function template partial ordering, because
4714 // class template partial specializations are more constrained. We
4715 // know that every template parameter is deducible from the class
4716 // template partial specialization's template arguments, for
4717 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004718 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004719
Richard Smith0da6dc42016-12-24 16:40:51 +00004720 // Determine whether P1 is at least as specialized as P2.
4721 Deduced.resize(P2->getTemplateParameters()->size());
4722 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4723 T2, T1, Info, Deduced, TDF_None,
4724 /*PartialOrdering=*/true))
4725 return false;
4726
4727 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4728 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004729 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4730 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004731 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4732 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004733 S, P2, /*PartialOrdering=*/true,
4734 TemplateArgumentList(TemplateArgumentList::OnStack,
4735 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004736 Deduced, Info))
4737 return false;
4738
4739 return true;
4740}
4741
4742/// \brief Returns the more specialized class template partial specialization
4743/// according to the rules of partial ordering of class template partial
4744/// specializations (C++ [temp.class.order]).
4745///
4746/// \param PS1 the first class template partial specialization
4747///
4748/// \param PS2 the second class template partial specialization
4749///
4750/// \returns the more specialized class template partial specialization. If
4751/// neither partial specialization is more specialized, returns NULL.
4752ClassTemplatePartialSpecializationDecl *
4753Sema::getMoreSpecializedPartialSpecialization(
4754 ClassTemplatePartialSpecializationDecl *PS1,
4755 ClassTemplatePartialSpecializationDecl *PS2,
4756 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004757 QualType PT1 = PS1->getInjectedSpecializationType();
4758 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Richard Smith0e617ec2016-12-27 07:56:27 +00004760 TemplateDeductionInfo Info(Loc);
4761 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4762 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004763
4764 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004765 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004766
4767 return Better1 ? PS1 : PS2;
4768}
4769
Richard Smith0e617ec2016-12-27 07:56:27 +00004770bool Sema::isMoreSpecializedThanPrimary(
4771 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4772 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4773 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4774 QualType PartialT = Spec->getInjectedSpecializationType();
4775 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4776 return false;
4777 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4778 Info.clearSFINAEDiagnostic();
4779 return false;
4780 }
4781 return true;
4782}
4783
Larisse Voufo39a1e502013-08-06 01:03:05 +00004784VarTemplatePartialSpecializationDecl *
4785Sema::getMoreSpecializedPartialSpecialization(
4786 VarTemplatePartialSpecializationDecl *PS1,
4787 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004788 // Pretend the variable template specializations are class template
4789 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004790 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004791 "the partial specializations being compared should specialize"
4792 " the same template.");
4793 TemplateName Name(PS1->getSpecializedTemplate());
4794 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4795 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004796 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004797 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004798 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004799
Richard Smith0e617ec2016-12-27 07:56:27 +00004800 TemplateDeductionInfo Info(Loc);
4801 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4802 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Douglas Gregorbe999392009-09-15 16:23:51 +00004804 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004805 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Richard Smith0da6dc42016-12-24 16:40:51 +00004807 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004808}
4809
Richard Smith0e617ec2016-12-27 07:56:27 +00004810bool Sema::isMoreSpecializedThanPrimary(
4811 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4812 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4813 // FIXME: Cache the injected template arguments rather than recomputing
4814 // them for each partial specialization.
4815 SmallVector<TemplateArgument, 8> PrimaryArgs;
4816 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4817 PrimaryArgs);
4818
4819 TemplateName CanonTemplate =
4820 Context.getCanonicalTemplateName(TemplateName(Primary));
4821 QualType PrimaryT = Context.getTemplateSpecializationType(
4822 CanonTemplate, PrimaryArgs);
4823 QualType PartialT = Context.getTemplateSpecializationType(
4824 CanonTemplate, Spec->getTemplateArgs().asArray());
4825 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4826 return false;
4827 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4828 Info.clearSFINAEDiagnostic();
4829 return false;
4830 }
4831 return true;
4832}
4833
Richard Smith26b86ea2016-12-31 21:41:23 +00004834bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4835 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4836 // C++1z [temp.arg.template]p4: (DR 150)
4837 // A template template-parameter P is at least as specialized as a
4838 // template template-argument A if, given the following rewrite to two
4839 // function templates...
4840
4841 // Rather than synthesize function templates, we merely perform the
4842 // equivalent partial ordering by performing deduction directly on
4843 // the template parameter lists of the template template parameters.
4844 //
4845 // Given an invented class template X with the template parameter list of
4846 // A (including default arguments):
4847 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4848 TemplateParameterList *A = AArg->getTemplateParameters();
4849
4850 // - Each function template has a single function parameter whose type is
4851 // a specialization of X with template arguments corresponding to the
4852 // template parameters from the respective function template
4853 SmallVector<TemplateArgument, 8> AArgs;
4854 Context.getInjectedTemplateArgs(A, AArgs);
4855
4856 // Check P's arguments against A's parameter list. This will fill in default
4857 // template arguments as needed. AArgs are already correct by construction.
4858 // We can't just use CheckTemplateIdType because that will expand alias
4859 // templates.
4860 SmallVector<TemplateArgument, 4> PArgs;
4861 {
4862 SFINAETrap Trap(*this);
4863
4864 Context.getInjectedTemplateArgs(P, PArgs);
4865 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4866 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4867 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4868 // expansions, to form an "as written" argument list.
4869 TemplateArgument Arg = PArgs[I];
4870 if (Arg.getKind() == TemplateArgument::Pack) {
4871 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4872 Arg = *Arg.pack_begin();
4873 }
4874 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4875 Arg, QualType(), P->getParam(I)->getLocation()));
4876 }
4877 PArgs.clear();
4878
4879 // C++1z [temp.arg.template]p3:
4880 // If the rewrite produces an invalid type, then P is not at least as
4881 // specialized as A.
4882 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4883 Trap.hasErrorOccurred())
4884 return false;
4885 }
4886
4887 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4888 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4889
Richard Smith26b86ea2016-12-31 21:41:23 +00004890 // ... the function template corresponding to P is at least as specialized
4891 // as the function template corresponding to A according to the partial
4892 // ordering rules for function templates.
4893 TemplateDeductionInfo Info(Loc, A->getDepth());
4894 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4895}
4896
Mike Stump11289f42009-09-09 15:08:12 +00004897static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004898MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004899 const TemplateArgument &TemplateArg,
4900 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004901 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004902 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004903
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004904/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004905/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004906static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004907MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004908 const Expr *E,
4909 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004910 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004911 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004912 // We can deduce from a pack expansion.
4913 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4914 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Richard Smith34349002012-07-09 03:07:20 +00004916 // Skip through any implicit casts we added while type-checking, and any
4917 // substitutions performed by template alias expansion.
4918 while (1) {
4919 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4920 E = ICE->getSubExpr();
4921 else if (const SubstNonTypeTemplateParmExpr *Subst =
4922 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4923 E = Subst->getReplacement();
4924 else
4925 break;
4926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927
4928 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004929 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004930 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004931 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004932 return;
4933
Mike Stump11289f42009-09-09 15:08:12 +00004934 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004935 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4936 if (!NTTP)
4937 return;
4938
Douglas Gregor21610382009-10-29 00:04:11 +00004939 if (NTTP->getDepth() == Depth)
4940 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004941
4942 // In C++1z mode, additional arguments may be deduced from the type of a
4943 // non-type argument.
4944 if (Ctx.getLangOpts().CPlusPlus1z)
4945 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004946}
4947
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004948/// \brief Mark the template parameters that are used by the given
4949/// nested name specifier.
4950static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004951MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004952 NestedNameSpecifier *NNS,
4953 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004954 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004955 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004956 if (!NNS)
4957 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004958
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004959 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004960 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004961 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004962 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004963}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004965/// \brief Mark the template parameters that are used by the given
4966/// template name.
4967static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004968MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004969 TemplateName Name,
4970 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004971 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004972 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004973 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4974 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004975 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4976 if (TTP->getDepth() == Depth)
4977 Used[TTP->getIndex()] = true;
4978 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004979 return;
4980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004982 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004983 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004984 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004985 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004986 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004987 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004988}
4989
4990/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004991/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004992static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004993MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004994 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004995 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004996 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004997 if (T.isNull())
4998 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
Douglas Gregor91772d12009-06-13 00:26:55 +00005000 // Non-dependent types have nothing deducible
5001 if (!T->isDependentType())
5002 return;
5003
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005004 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005005 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005006 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005007 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005008 cast<PointerType>(T)->getPointeeType(),
5009 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005010 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005011 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005012 break;
5013
5014 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005015 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005016 cast<BlockPointerType>(T)->getPointeeType(),
5017 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005018 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005019 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005020 break;
5021
5022 case Type::LValueReference:
5023 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005024 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005025 cast<ReferenceType>(T)->getPointeeType(),
5026 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005027 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005028 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005029 break;
5030
5031 case Type::MemberPointer: {
5032 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005034 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005035 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005036 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005037 break;
5038 }
5039
5040 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005041 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005042 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005043 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005044 // Fall through to check the element type
5045
5046 case Type::ConstantArray:
5047 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005048 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005049 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005050 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005051 break;
5052
5053 case Type::Vector:
5054 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005055 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005056 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005057 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005058 break;
5059
Douglas Gregor758a8692009-06-17 21:51:59 +00005060 case Type::DependentSizedExtVector: {
5061 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005062 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005063 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005064 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005065 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005066 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005067 break;
5068 }
5069
Douglas Gregor91772d12009-06-13 00:26:55 +00005070 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005071 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005072 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5073 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005074 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5075 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005076 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005077 break;
5078 }
5079
Douglas Gregor21610382009-10-29 00:04:11 +00005080 case Type::TemplateTypeParm: {
5081 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5082 if (TTP->getDepth() == Depth)
5083 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005084 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005085 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005086
Douglas Gregorfb322d82011-01-14 05:11:40 +00005087 case Type::SubstTemplateTypeParmPack: {
5088 const SubstTemplateTypeParmPackType *Subst
5089 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005090 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005091 QualType(Subst->getReplacedParameter(), 0),
5092 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005093 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005094 OnlyDeduced, Depth, Used);
5095 break;
5096 }
5097
John McCall2408e322010-04-27 00:57:59 +00005098 case Type::InjectedClassName:
5099 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5100 // fall through
5101
Douglas Gregor91772d12009-06-13 00:26:55 +00005102 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005103 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005104 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005105 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005106 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107
Douglas Gregord0ad2942010-12-23 01:24:45 +00005108 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005109 // If the template argument list of P contains a pack expansion that is
5110 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005111 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005112 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005113 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005114 break;
5115
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005116 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005117 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005118 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005119 break;
5120 }
5121
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005122 case Type::Complex:
5123 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005124 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005125 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005126 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005127 break;
5128
Eli Friedman0dfb8892011-10-06 23:00:33 +00005129 case Type::Atomic:
5130 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005131 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005132 cast<AtomicType>(T)->getValueType(),
5133 OnlyDeduced, Depth, Used);
5134 break;
5135
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005136 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005137 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005138 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005139 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005140 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005141 break;
5142
John McCallc392f372010-06-11 00:33:02 +00005143 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005144 // C++14 [temp.deduct.type]p5:
5145 // The non-deduced contexts are:
5146 // -- The nested-name-specifier of a type that was specified using a
5147 // qualified-id
5148 //
5149 // C++14 [temp.deduct.type]p6:
5150 // When a type name is specified in a way that includes a non-deduced
5151 // context, all of the types that comprise that type name are also
5152 // non-deduced.
5153 if (OnlyDeduced)
5154 break;
5155
John McCallc392f372010-06-11 00:33:02 +00005156 const DependentTemplateSpecializationType *Spec
5157 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Richard Smith50d5b972015-12-30 20:56:05 +00005159 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5160 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005161
John McCallc392f372010-06-11 00:33:02 +00005162 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005163 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005164 Used);
5165 break;
5166 }
5167
John McCallbd8d9bd2010-03-01 23:49:17 +00005168 case Type::TypeOf:
5169 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005170 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005171 cast<TypeOfType>(T)->getUnderlyingType(),
5172 OnlyDeduced, Depth, Used);
5173 break;
5174
5175 case Type::TypeOfExpr:
5176 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005177 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005178 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5179 OnlyDeduced, Depth, Used);
5180 break;
5181
5182 case Type::Decltype:
5183 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005184 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005185 cast<DecltypeType>(T)->getUnderlyingExpr(),
5186 OnlyDeduced, Depth, Used);
5187 break;
5188
Alexis Hunte852b102011-05-24 22:41:36 +00005189 case Type::UnaryTransform:
5190 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005191 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005192 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005193 OnlyDeduced, Depth, Used);
5194 break;
5195
Douglas Gregord2fa7662010-12-20 02:24:11 +00005196 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005197 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005198 cast<PackExpansionType>(T)->getPattern(),
5199 OnlyDeduced, Depth, Used);
5200 break;
5201
Richard Smith30482bc2011-02-20 03:19:35 +00005202 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005203 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005204 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005205 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005206 OnlyDeduced, Depth, Used);
5207
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005208 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005209 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005210 case Type::VariableArray:
5211 case Type::FunctionNoProto:
5212 case Type::Record:
5213 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005214 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005215 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005216 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005217 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005218 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005219#define TYPE(Class, Base)
5220#define ABSTRACT_TYPE(Class, Base)
5221#define DEPENDENT_TYPE(Class, Base)
5222#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5223#include "clang/AST/TypeNodes.def"
5224 break;
5225 }
5226}
5227
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005228/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005229/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005230static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005231MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005232 const TemplateArgument &TemplateArg,
5233 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005234 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005235 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005236 switch (TemplateArg.getKind()) {
5237 case TemplateArgument::Null:
5238 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005239 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005240 break;
Mike Stump11289f42009-09-09 15:08:12 +00005241
Eli Friedmanb826a002012-09-26 02:36:12 +00005242 case TemplateArgument::NullPtr:
5243 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5244 Depth, Used);
5245 break;
5246
Douglas Gregor91772d12009-06-13 00:26:55 +00005247 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005248 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005249 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005250 break;
5251
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005252 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005253 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005254 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005256 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005257 break;
5258
5259 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005260 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005261 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005262 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263
Anders Carlssonbc343912009-06-15 17:04:53 +00005264 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005265 for (const auto &P : TemplateArg.pack_elements())
5266 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005267 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005268 }
5269}
5270
James Dennett41725122012-06-22 10:16:05 +00005271/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005272/// template argument list.
5273///
5274/// \param TemplateArgs the template argument list from which template
5275/// parameters will be deduced.
5276///
James Dennett41725122012-06-22 10:16:05 +00005277/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005278/// to indicate when the corresponding template parameter will be
5279/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005280void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005281Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005282 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005283 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005284 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285 // If the template argument list of P contains a pack expansion that is not
5286 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005287 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005288 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005289 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005290 return;
5291
Douglas Gregor91772d12009-06-13 00:26:55 +00005292 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005293 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005294 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005295}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005296
5297/// \brief Marks all of the template parameters that will be deduced by a
5298/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005299void Sema::MarkDeducedTemplateParameters(
5300 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5301 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005302 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005303 = FunctionTemplate->getTemplateParameters();
5304 Deduced.clear();
5305 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
Douglas Gregorce23bae2009-09-18 23:21:38 +00005307 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5308 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005309 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005310 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005311}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005312
Richard Smithf0393bf2017-02-16 04:22:56 +00005313bool hasDeducibleTemplateParameters(Sema &S,
5314 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005315 QualType T) {
5316 if (!T->isDependentType())
5317 return false;
5318
Richard Smithf0393bf2017-02-16 04:22:56 +00005319 TemplateParameterList *TemplateParams
5320 = FunctionTemplate->getTemplateParameters();
5321 llvm::SmallBitVector Deduced(TemplateParams->size());
5322 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5323 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005324
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005325 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005326}