blob: 3515918be7ad153da79d46bbf43dbdeeccd764cb [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000025#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000026#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000027
28namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000029 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000055 TDF_TopLevelParameterTypeList = 0x10,
56 /// \brief Within template argument deduction from overload resolution per
57 /// C++ [over.over] allow matching function types that are compatible in
58 /// terms of noreturn and default calling convention adjustments.
59 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000060 };
61}
62
Douglas Gregor55ca8f62009-06-04 00:03:07 +000063using namespace clang;
64
Douglas Gregor0a29a052010-03-26 05:50:28 +000065/// \brief Compare two APSInts, extending and switching the sign as
66/// necessary to compare their values regardless of underlying type.
67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000069 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000070 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000071 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000072
73 // If there is a signedness mismatch, correct it.
74 if (X.isSigned() != Y.isSigned()) {
75 // If the signed value is negative, then the values cannot be the same.
76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77 return false;
78
79 Y.setIsSigned(true);
80 X.setIsSigned(true);
81 }
82
83 return X == Y;
84}
85
Douglas Gregor181aa4a2009-06-12 18:26:56 +000086static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000087DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000088 TemplateParameterList *TemplateParams,
89 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000090 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000091 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000092 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000093
Douglas Gregor7baabef2010-12-22 18:17:10 +000094static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000095DeduceTemplateArgumentsByTypeMatch(Sema &S,
96 TemplateParameterList *TemplateParams,
97 QualType Param,
98 QualType Arg,
99 TemplateDeductionInfo &Info,
100 SmallVectorImpl<DeducedTemplateArgument> &
101 Deduced,
102 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000103 bool PartialOrdering = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000104
105static Sema::TemplateDeductionResult
106DeduceTemplateArguments(Sema &S,
107 TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000108 const TemplateArgument *Params, unsigned NumParams,
109 const TemplateArgument *Args, unsigned NumArgs,
110 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000112
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000113/// \brief If the given expression is of a form that permits the deduction
114/// of a non-type template parameter, return the declaration of that
115/// non-type template parameter.
116static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000117 // If we are within an alias template, the expression may have undergone
118 // any number of parameter substitutions already.
119 while (1) {
120 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
121 E = IC->getSubExpr();
122 else if (SubstNonTypeTemplateParmExpr *Subst =
123 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
124 E = Subst->getReplacement();
125 else
126 break;
127 }
Mike Stump11289f42009-09-09 15:08:12 +0000128
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000129 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
130 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000131
Craig Topperc3ec1492014-05-26 06:22:03 +0000132 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000133}
134
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000135/// \brief Determine whether two declaration pointers refer to the same
136/// declaration.
137static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000138 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
139 X = NX->getUnderlyingDecl();
140 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
141 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000142
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000143 return X->getCanonicalDecl() == Y->getCanonicalDecl();
144}
145
146/// \brief Verify that the given, deduced template arguments are compatible.
147///
148/// \returns The deduced template argument, or a NULL template argument if
149/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000151checkDeducedTemplateArguments(ASTContext &Context,
152 const DeducedTemplateArgument &X,
153 const DeducedTemplateArgument &Y) {
154 // We have no deduction for one or both of the arguments; they're compatible.
155 if (X.isNull())
156 return Y;
157 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000159
160 switch (X.getKind()) {
161 case TemplateArgument::Null:
162 llvm_unreachable("Non-deduced template arguments handled above");
163
164 case TemplateArgument::Type:
165 // If two template type arguments have the same type, they're compatible.
166 if (Y.getKind() == TemplateArgument::Type &&
167 Context.hasSameType(X.getAsType(), Y.getAsType()))
168 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000169
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000170 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000171
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000172 case TemplateArgument::Integral:
173 // If we deduced a constant in one case and either a dependent expression or
174 // declaration in another case, keep the integral constant.
175 // If both are integral constants with the same value, keep that value.
176 if (Y.getKind() == TemplateArgument::Expression ||
177 Y.getKind() == TemplateArgument::Declaration ||
178 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000179 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 return DeducedTemplateArgument(X,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000181 X.wasDeducedFromArrayBound() &&
182 Y.wasDeducedFromArrayBound());
183
184 // All other combinations are incompatible.
185 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000186
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000187 case TemplateArgument::Template:
188 if (Y.getKind() == TemplateArgument::Template &&
189 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
190 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000192 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000194
195 case TemplateArgument::TemplateExpansion:
196 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000198 Y.getAsTemplateOrTemplatePattern()))
199 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000200
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000201 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000202 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000203
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000204 case TemplateArgument::Expression:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205 // If we deduced a dependent expression in one case and either an integral
206 // constant or a declaration in another case, keep the integral constant
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000207 // or declaration.
208 if (Y.getKind() == TemplateArgument::Integral ||
209 Y.getKind() == TemplateArgument::Declaration)
210 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
211 Y.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000213 if (Y.getKind() == TemplateArgument::Expression) {
214 // Compare the expressions for equality
215 llvm::FoldingSetNodeID ID1, ID2;
216 X.getAsExpr()->Profile(ID1, Context, true);
217 Y.getAsExpr()->Profile(ID2, Context, true);
218 if (ID1 == ID2)
219 return X;
220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000222 // All other combinations are incompatible.
223 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000225 case TemplateArgument::Declaration:
226 // If we deduced a declaration and a dependent expression, keep the
227 // declaration.
228 if (Y.getKind() == TemplateArgument::Expression)
229 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000231 // If we deduced a declaration and an integral constant, keep the
232 // integral constant.
233 if (Y.getKind() == TemplateArgument::Integral)
234 return Y;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000235
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000236 // If we deduced two declarations, make sure they they refer to the
237 // same declaration.
238 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000239 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000240 return X;
241
242 // All other combinations are incompatible.
243 return DeducedTemplateArgument();
244
245 case TemplateArgument::NullPtr:
246 // If we deduced a null pointer and a dependent expression, keep the
247 // null pointer.
248 if (Y.getKind() == TemplateArgument::Expression)
249 return X;
250
251 // If we deduced a null pointer and an integral constant, keep the
252 // integral constant.
253 if (Y.getKind() == TemplateArgument::Integral)
254 return Y;
255
256 // If we deduced two null pointers, make sure they have the same type.
257 if (Y.getKind() == TemplateArgument::NullPtr &&
258 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000260
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000261 // All other combinations are incompatible.
262 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000263
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000264 case TemplateArgument::Pack:
265 if (Y.getKind() != TemplateArgument::Pack ||
266 X.pack_size() != Y.pack_size())
267 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000268
269 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000270 XAEnd = X.pack_end(),
271 YA = Y.pack_begin();
272 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000273 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 if (checkDeducedTemplateArguments(Context,
275 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000276 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
277 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000278 return DeducedTemplateArgument();
279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283
David Blaikiee4d798f2012-01-20 21:50:17 +0000284 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000285}
286
Mike Stump11289f42009-09-09 15:08:12 +0000287/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000288/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000289static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000290DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000291 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000292 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000293 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000294 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000296 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000297 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000298
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000299 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
300 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000302 Deduced[NTTP->getIndex()],
303 NewDeduced);
304 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000305 Info.Param = NTTP;
306 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000312 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000313}
314
Mike Stump11289f42009-09-09 15:08:12 +0000315/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000316/// from the given type- or value-dependent expression.
317///
318/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000319static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000320DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000321 NonTypeTemplateParmDecl *NTTP,
322 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000323 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000325 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000326 "Cannot deduce non-type template argument with depth > 0");
327 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
328 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000329
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000330 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
332 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000335 if (Result.isNull()) {
336 Info.Param = NTTP;
337 Info.FirstArg = Deduced[NTTP->getIndex()];
338 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000341
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000342 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000343 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000344}
345
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000346/// \brief Deduce the value of the given non-type template parameter
347/// from the given declaration.
348///
349/// \returns true if deduction succeeded, false otherwise.
350static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000351DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000352 NonTypeTemplateParmDecl *NTTP,
353 ValueDecl *D,
354 TemplateDeductionInfo &Info,
355 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000356 assert(NTTP->getDepth() == 0 &&
357 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358
Craig Topperc3ec1492014-05-26 06:22:03 +0000359 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000360 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000361 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000363 Deduced[NTTP->getIndex()],
364 NewDeduced);
365 if (Result.isNull()) {
366 Info.Param = NTTP;
367 Info.FirstArg = Deduced[NTTP->getIndex()];
368 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000372 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000373 return Sema::TDK_Success;
374}
375
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000377DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000378 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000379 TemplateName Param,
380 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000381 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000383 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000384 if (!ParamDecl) {
385 // The parameter type is dependent and is not a template template parameter,
386 // so there is nothing that we can deduce.
387 return Sema::TDK_Success;
388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregoradee3e32009-11-11 23:06:43 +0000390 if (TemplateTemplateParmDecl *TempParam
391 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000392 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000394 Deduced[TempParam->getIndex()],
395 NewDeduced);
396 if (Result.isNull()) {
397 Info.Param = TempParam;
398 Info.FirstArg = Deduced[TempParam->getIndex()];
399 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000403 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406
Douglas Gregoradee3e32009-11-11 23:06:43 +0000407 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000408 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000409 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregoradee3e32009-11-11 23:06:43 +0000411 // Mismatch of non-dependent template parameter to argument.
412 Info.FirstArg = TemplateArgument(Param);
413 Info.SecondArg = TemplateArgument(Arg);
414 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000415}
416
Mike Stump11289f42009-09-09 15:08:12 +0000417/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000418/// type (which is a template-id) with the template argument type.
419///
Chandler Carruthc1263112010-02-07 21:33:28 +0000420/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000421///
422/// \param TemplateParams the template parameters that we are deducing
423///
424/// \param Param the parameter type
425///
426/// \param Arg the argument type
427///
428/// \param Info information about the template argument deduction itself
429///
430/// \param Deduced the deduced template arguments
431///
432/// \returns the result of template argument deduction so far. Note that a
433/// "success" result means that template argument deduction has not yet failed,
434/// but it may still fail, later, for other reasons.
435static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000436DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000437 TemplateParameterList *TemplateParams,
438 const TemplateSpecializationType *Param,
439 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000440 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000441 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000442 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregore81f3e72009-07-07 23:09:34 +0000444 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000445 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000446 = dyn_cast<TemplateSpecializationType>(Arg)) {
447 // Perform template argument deduction for the template name.
448 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000449 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000450 Param->getTemplateName(),
451 SpecArg->getTemplateName(),
452 Info, Deduced))
453 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000454
Mike Stump11289f42009-09-09 15:08:12 +0000455
Douglas Gregore81f3e72009-07-07 23:09:34 +0000456 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000457 // argument. Ignore any missing/extra arguments, since they could be
458 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459 return DeduceTemplateArguments(S, TemplateParams,
460 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000461 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000462 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Douglas Gregore81f3e72009-07-07 23:09:34 +0000465 // If the argument type is a class template specialization, we
466 // perform template argument deduction using its template
467 // arguments.
468 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000469 if (!RecordArg) {
470 Info.FirstArg = TemplateArgument(QualType(Param, 0));
471 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
475 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000476 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000477 if (!SpecArg) {
478 Info.FirstArg = TemplateArgument(QualType(Param, 0));
479 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000480 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregore81f3e72009-07-07 23:09:34 +0000483 // Perform template argument deduction for the template name.
484 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000485 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000486 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000487 Param->getTemplateName(),
488 TemplateName(SpecArg->getSpecializedTemplate()),
489 Info, Deduced))
490 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregor7baabef2010-12-22 18:17:10 +0000492 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000494 Param->getArgs(), Param->getNumArgs(),
495 SpecArg->getTemplateArgs().data(),
496 SpecArg->getTemplateArgs().size(),
497 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498}
499
John McCall08569062010-08-28 22:14:41 +0000500/// \brief Determines whether the given type is an opaque type that
501/// might be more qualified when instantiated.
502static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
503 switch (T->getTypeClass()) {
504 case Type::TypeOfExpr:
505 case Type::TypeOf:
506 case Type::DependentName:
507 case Type::Decltype:
508 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000509 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000510 return true;
511
512 case Type::ConstantArray:
513 case Type::IncompleteArray:
514 case Type::VariableArray:
515 case Type::DependentSizedArray:
516 return IsPossiblyOpaquelyQualifiedType(
517 cast<ArrayType>(T)->getElementType());
518
519 default:
520 return false;
521 }
522}
523
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000524/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000526getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000527 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
528 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Douglas Gregor5499af42011-01-05 23:12:31 +0000530 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
531 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000532
Douglas Gregor5499af42011-01-05 23:12:31 +0000533 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
534 return std::make_pair(TTP->getDepth(), TTP->getIndex());
535}
536
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000537/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000539getDepthAndIndex(UnexpandedParameterPack UPP) {
540 if (const TemplateTypeParmType *TTP
541 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
542 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000544 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
545}
546
Douglas Gregor5499af42011-01-05 23:12:31 +0000547/// \brief Helper function to build a TemplateParameter when we don't
548/// know its type statically.
549static TemplateParameter makeTemplateParameter(Decl *D) {
550 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
551 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000552 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000553 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor5499af42011-01-05 23:12:31 +0000555 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
556}
557
Richard Smith0a80d572014-05-29 01:12:14 +0000558/// A pack that we're currently deducing.
559struct clang::DeducedPack {
560 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000561
Richard Smith0a80d572014-05-29 01:12:14 +0000562 // The index of the pack.
563 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Richard Smith0a80d572014-05-29 01:12:14 +0000565 // The old value of the pack before we started deducing it.
566 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000567
Richard Smith0a80d572014-05-29 01:12:14 +0000568 // A deferred value of this pack from an inner deduction, that couldn't be
569 // deduced because this deduction hadn't happened yet.
570 DeducedTemplateArgument DeferredDeduction;
571
572 // The new value of the pack.
573 SmallVector<DeducedTemplateArgument, 4> New;
574
575 // The outer deduction for this pack, if any.
576 DeducedPack *Outer;
577};
578
579/// A scope in which we're performing pack deduction.
580class PackDeductionScope {
581public:
582 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
583 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
584 TemplateDeductionInfo &Info, TemplateArgument Pattern)
585 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
586 // Compute the set of template parameter indices that correspond to
587 // parameter packs expanded by the pack expansion.
588 {
589 llvm::SmallBitVector SawIndices(TemplateParams->size());
590 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
591 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
592 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
593 unsigned Depth, Index;
594 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
595 if (Depth == 0 && !SawIndices[Index]) {
596 SawIndices[Index] = true;
597
598 // Save the deduced template argument for the parameter pack expanded
599 // by this pack expansion, then clear out the deduction.
600 DeducedPack Pack(Index);
601 Pack.Saved = Deduced[Index];
602 Deduced[Index] = TemplateArgument();
603
604 Packs.push_back(Pack);
605 }
606 }
607 }
608 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
609
610 for (auto &Pack : Packs) {
611 if (Info.PendingDeducedPacks.size() > Pack.Index)
612 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
613 else
614 Info.PendingDeducedPacks.resize(Pack.Index + 1);
615 Info.PendingDeducedPacks[Pack.Index] = &Pack;
616
617 if (S.CurrentInstantiationScope) {
618 // If the template argument pack was explicitly specified, add that to
619 // the set of deduced arguments.
620 const TemplateArgument *ExplicitArgs;
621 unsigned NumExplicitArgs;
622 NamedDecl *PartiallySubstitutedPack =
623 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
624 &ExplicitArgs, &NumExplicitArgs);
625 if (PartiallySubstitutedPack &&
626 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
627 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
628 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000629 }
630 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000631
Richard Smith0a80d572014-05-29 01:12:14 +0000632 ~PackDeductionScope() {
633 for (auto &Pack : Packs)
634 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
Richard Smith0a80d572014-05-29 01:12:14 +0000637 /// Move to deducing the next element in each pack that is being deduced.
638 void nextPackElement() {
639 // Capture the deduced template arguments for each parameter pack expanded
640 // by this pack expansion, add them to the list of arguments we've deduced
641 // for that pack, then clear out the deduced argument.
642 for (auto &Pack : Packs) {
643 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
644 if (!DeducedArg.isNull()) {
645 Pack.New.push_back(DeducedArg);
646 DeducedArg = DeducedTemplateArgument();
647 }
648 }
649 }
650
651 /// \brief Finish template argument deduction for a set of argument packs,
652 /// producing the argument packs and checking for consistency with prior
653 /// deductions.
654 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
655 // Build argument packs for each of the parameter packs expanded by this
656 // pack expansion.
657 for (auto &Pack : Packs) {
658 // Put back the old value for this pack.
659 Deduced[Pack.Index] = Pack.Saved;
660
661 // Build or find a new value for this pack.
662 DeducedTemplateArgument NewPack;
663 if (HasAnyArguments && Pack.New.empty()) {
664 if (Pack.DeferredDeduction.isNull()) {
665 // We were not able to deduce anything for this parameter pack
666 // (because it only appeared in non-deduced contexts), so just
667 // restore the saved argument pack.
668 continue;
669 }
670
671 NewPack = Pack.DeferredDeduction;
672 Pack.DeferredDeduction = TemplateArgument();
673 } else if (Pack.New.empty()) {
674 // If we deduced an empty argument pack, create it now.
675 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
676 } else {
677 TemplateArgument *ArgumentPack =
678 new (S.Context) TemplateArgument[Pack.New.size()];
679 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
680 NewPack = DeducedTemplateArgument(
681 TemplateArgument(ArgumentPack, Pack.New.size()),
682 Pack.New[0].wasDeducedFromArrayBound());
683 }
684
685 // Pick where we're going to put the merged pack.
686 DeducedTemplateArgument *Loc;
687 if (Pack.Outer) {
688 if (Pack.Outer->DeferredDeduction.isNull()) {
689 // Defer checking this pack until we have a complete pack to compare
690 // it against.
691 Pack.Outer->DeferredDeduction = NewPack;
692 continue;
693 }
694 Loc = &Pack.Outer->DeferredDeduction;
695 } else {
696 Loc = &Deduced[Pack.Index];
697 }
698
699 // Check the new pack matches any previous value.
700 DeducedTemplateArgument OldPack = *Loc;
701 DeducedTemplateArgument Result =
702 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
703
704 // If we deferred a deduction of this pack, check that one now too.
705 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
706 OldPack = Result;
707 NewPack = Pack.DeferredDeduction;
708 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
709 }
710
711 if (Result.isNull()) {
712 Info.Param =
713 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
714 Info.FirstArg = OldPack;
715 Info.SecondArg = NewPack;
716 return Sema::TDK_Inconsistent;
717 }
718
719 *Loc = Result;
720 }
721
722 return Sema::TDK_Success;
723 }
724
725private:
726 Sema &S;
727 TemplateParameterList *TemplateParams;
728 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
729 TemplateDeductionInfo &Info;
730
731 SmallVector<DeducedPack, 2> Packs;
732};
Douglas Gregorb94a6172011-01-10 17:53:52 +0000733
Douglas Gregor5499af42011-01-05 23:12:31 +0000734/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735/// types to the list of argument types, as in the parameter-type-lists of
736/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000737///
738/// \param S The semantic analysis object within which we are deducing
739///
740/// \param TemplateParams The template parameters that we are deducing
741///
742/// \param Params The list of parameter types
743///
744/// \param NumParams The number of types in \c Params
745///
746/// \param Args The list of argument types
747///
748/// \param NumArgs The number of types in \c Args
749///
750/// \param Info information about the template argument deduction itself
751///
752/// \param Deduced the deduced template arguments
753///
754/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
755/// how template argument deduction is performed.
756///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000757/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000759/// (C++0x [temp.deduct.partial]).
760///
Douglas Gregor5499af42011-01-05 23:12:31 +0000761/// \returns the result of template argument deduction so far. Note that a
762/// "success" result means that template argument deduction has not yet failed,
763/// but it may still fail, later, for other reasons.
764static Sema::TemplateDeductionResult
765DeduceTemplateArguments(Sema &S,
766 TemplateParameterList *TemplateParams,
767 const QualType *Params, unsigned NumParams,
768 const QualType *Args, unsigned NumArgs,
769 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000770 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000771 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000772 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000773 // Fast-path check to see if we have too many/too few arguments.
774 if (NumParams != NumArgs &&
775 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
776 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000777 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778
Douglas Gregor5499af42011-01-05 23:12:31 +0000779 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 // Similarly, if P has a form that contains (T), then each parameter type
781 // Pi of the respective parameter-type- list of P is compared with the
782 // corresponding parameter type Ai of the corresponding parameter-type-list
783 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000784 unsigned ArgIdx = 0, ParamIdx = 0;
785 for (; ParamIdx != NumParams; ++ParamIdx) {
786 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000788 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
789 if (!Expansion) {
790 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000791
Douglas Gregor5499af42011-01-05 23:12:31 +0000792 // Make sure we have an argument.
793 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000794 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000796 if (isa<PackExpansionType>(Args[ArgIdx])) {
797 // C++0x [temp.deduct.type]p22:
798 // If the original function parameter associated with A is a function
799 // parameter pack and the function parameter associated with P is not
800 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000801 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000803
Douglas Gregor5499af42011-01-05 23:12:31 +0000804 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000805 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
806 Params[ParamIdx], Args[ArgIdx],
807 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000808 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000809 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 ++ArgIdx;
812 continue;
813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000815 // C++0x [temp.deduct.type]p5:
816 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000818 // parameter-declaration-clause.
819 if (ParamIdx + 1 < NumParams)
820 return Sema::TDK_Success;
821
Douglas Gregor5499af42011-01-05 23:12:31 +0000822 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000826 // comparison deduces template arguments for subsequent positions in the
827 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000828
Douglas Gregor5499af42011-01-05 23:12:31 +0000829 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000830 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
Douglas Gregor5499af42011-01-05 23:12:31 +0000832 bool HasAnyArguments = false;
833 for (; ArgIdx < NumArgs; ++ArgIdx) {
834 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor5499af42011-01-05 23:12:31 +0000836 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000838 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
839 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000840 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000841 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Richard Smith0a80d572014-05-29 01:12:14 +0000843 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845
Douglas Gregor5499af42011-01-05 23:12:31 +0000846 // Build argument packs for each of the parameter packs expanded by this
847 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000848 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851
Douglas Gregor5499af42011-01-05 23:12:31 +0000852 // Make sure we don't have any extra arguments.
853 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000854 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 return Sema::TDK_Success;
857}
858
Douglas Gregor1d684c22011-04-28 00:56:09 +0000859/// \brief Determine whether the parameter has qualifiers that are either
860/// inconsistent with or a superset of the argument's qualifiers.
861static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
862 QualType ArgType) {
863 Qualifiers ParamQs = ParamType.getQualifiers();
864 Qualifiers ArgQs = ArgType.getQualifiers();
865
866 if (ParamQs == ArgQs)
867 return false;
868
869 // Mismatched (but not missing) Objective-C GC attributes.
870 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
871 ParamQs.hasObjCGCAttr())
872 return true;
873
874 // Mismatched (but not missing) address spaces.
875 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
876 ParamQs.hasAddressSpace())
877 return true;
878
John McCall31168b02011-06-15 23:02:42 +0000879 // Mismatched (but not missing) Objective-C lifetime qualifiers.
880 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
881 ParamQs.hasObjCLifetime())
882 return true;
883
Douglas Gregor1d684c22011-04-28 00:56:09 +0000884 // CVR qualifier superset.
885 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
886 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
887 == ParamQs.getCVRQualifiers());
888}
889
Douglas Gregor19a41f12013-04-17 08:45:07 +0000890/// \brief Compare types for equality with respect to possibly compatible
891/// function types (noreturn adjustment, implicit calling conventions). If any
892/// of parameter and argument is not a function, just perform type comparison.
893///
894/// \param Param the template parameter type.
895///
896/// \param Arg the argument type.
897bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
898 CanQualType Arg) {
899 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
900 *ArgFunction = Arg->getAs<FunctionType>();
901
902 // Just compare if not functions.
903 if (!ParamFunction || !ArgFunction)
904 return Param == Arg;
905
906 // Noreturn adjustment.
907 QualType AdjustedParam;
908 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
909 return Arg == Context.getCanonicalType(AdjustedParam);
910
911 // FIXME: Compatible calling conventions.
912
913 return Param == Arg;
914}
915
Douglas Gregorcceb9752009-06-26 18:27:22 +0000916/// \brief Deduce the template arguments by comparing the parameter type and
917/// the argument type (C++ [temp.deduct.type]).
918///
Chandler Carruthc1263112010-02-07 21:33:28 +0000919/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000920///
921/// \param TemplateParams the template parameters that we are deducing
922///
923/// \param ParamIn the parameter type
924///
925/// \param ArgIn the argument type
926///
927/// \param Info information about the template argument deduction itself
928///
929/// \param Deduced the deduced template arguments
930///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000931/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000932/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000933///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000934/// \param PartialOrdering Whether we're performing template argument deduction
935/// in the context of partial ordering (C++0x [temp.deduct.partial]).
936///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000937/// \returns the result of template argument deduction so far. Note that a
938/// "success" result means that template argument deduction has not yet failed,
939/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000940static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000941DeduceTemplateArgumentsByTypeMatch(Sema &S,
942 TemplateParameterList *TemplateParams,
943 QualType ParamIn, QualType ArgIn,
944 TemplateDeductionInfo &Info,
945 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
946 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000947 bool PartialOrdering) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000948 // We only want to look at the canonical types, since typedefs and
949 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000950 QualType Param = S.Context.getCanonicalType(ParamIn);
951 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000952
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000953 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000955 if (const PackExpansionType *ArgExpansion
956 = dyn_cast<PackExpansionType>(Arg))
957 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000958
Douglas Gregorb837ea42011-01-11 17:34:58 +0000959 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000960 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961 // Before the partial ordering is done, certain transformations are
962 // performed on the types used for partial ordering:
963 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000964 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
965 if (ParamRef)
966 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
Douglas Gregorb837ea42011-01-11 17:34:58 +0000968 // - If A is a reference type, A is replaced by the type referred to.
969 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
970 if (ArgRef)
971 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
Richard Smithed563c22015-02-20 04:45:22 +0000973 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
974 // C++11 [temp.deduct.partial]p9:
975 // If, for a given type, deduction succeeds in both directions (i.e.,
976 // the types are identical after the transformations above) and both
977 // P and A were reference types [...]:
978 // - if [one type] was an lvalue reference and [the other type] was
979 // not, [the other type] is not considered to be at least as
980 // specialized as [the first type]
981 // - if [one type] is more cv-qualified than [the other type],
982 // [the other type] is not considered to be at least as specialized
983 // as [the first type]
984 // Objective-C ARC adds:
985 // - [one type] has non-trivial lifetime, [the other type] has
986 // __unsafe_unretained lifetime, and the types are otherwise
987 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +0000988 //
Richard Smithed563c22015-02-20 04:45:22 +0000989 // A is "considered to be at least as specialized" as P iff deduction
990 // succeeds, so we model this as a deduction failure. Note that
991 // [the first type] is P and [the other type] is A here; the standard
992 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +0000993 Qualifiers ParamQuals = Param.getQualifiers();
994 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +0000995 if ((ParamRef->isLValueReferenceType() &&
996 !ArgRef->isLValueReferenceType()) ||
997 ParamQuals.isStrictSupersetOf(ArgQuals) ||
998 (ParamQuals.hasNonTrivialObjCLifetime() &&
999 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1000 ParamQuals.withoutObjCLifetime() ==
1001 ArgQuals.withoutObjCLifetime())) {
1002 Info.FirstArg = TemplateArgument(ParamIn);
1003 Info.SecondArg = TemplateArgument(ArgIn);
1004 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001005 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Richard Smithed563c22015-02-20 04:45:22 +00001008 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001009 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001011 // version of P.
1012 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001014 // version of A.
1015 Arg = Arg.getUnqualifiedType();
1016 } else {
1017 // C++0x [temp.deduct.call]p4 bullet 1:
1018 // - If the original P is a reference type, the deduced A (i.e., the type
1019 // referred to by the reference) can be more cv-qualified than the
1020 // transformed A.
1021 if (TDF & TDF_ParamWithReferenceType) {
1022 Qualifiers Quals;
1023 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1024 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001025 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001026 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001028
Douglas Gregor85f240c2011-01-25 17:19:08 +00001029 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1030 // C++0x [temp.deduct.type]p10:
1031 // If P and A are function types that originated from deduction when
1032 // taking the address of a function template (14.8.2.2) or when deducing
1033 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034 // Ai are parameters of the top-level parameter-type-list of P and A,
1035 // respectively, Pi is adjusted if it is an rvalue reference to a
1036 // cv-unqualified template parameter and Ai is an lvalue reference, in
1037 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001038 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1039 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001040 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001041 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001042
Douglas Gregor85f240c2011-01-25 17:19:08 +00001043 if (const RValueReferenceType *ParamRef
1044 = Param->getAs<RValueReferenceType>()) {
1045 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1046 !ParamRef->getPointeeType().getQualifiers())
1047 if (Arg->isLValueReferenceType())
1048 Param = ParamRef->getPointeeType();
1049 }
1050 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001053 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001054 // A template type argument T, a template template argument TT or a
1055 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001056 // the following forms:
1057 //
1058 // T
1059 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001060 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001061 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001062 // Just skip any attempts to deduce from a placeholder type.
1063 if (Arg->isPlaceholderType())
1064 return Sema::TDK_Success;
1065
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001066 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001067 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregor60454822009-07-22 20:02:25 +00001069 // If the argument type is an array type, move the qualifiers up to the
1070 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001071 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001072 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001073 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001074 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001075 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001076 RecanonicalizeArg = true;
1077 }
1078 }
Mike Stump11289f42009-09-09 15:08:12 +00001079
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001080 // The argument type can not be less qualified than the parameter
1081 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001082 if (!(TDF & TDF_IgnoreQualifiers) &&
1083 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001084 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001085 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001086 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001087 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001088 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001089
1090 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001091 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001092 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001093
Douglas Gregor1d684c22011-04-28 00:56:09 +00001094 // Remove any qualifiers on the parameter from the deduced type.
1095 // We checked the qualifiers for consistency above.
1096 Qualifiers DeducedQs = DeducedType.getQualifiers();
1097 Qualifiers ParamQs = Param.getQualifiers();
1098 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1099 if (ParamQs.hasObjCGCAttr())
1100 DeducedQs.removeObjCGCAttr();
1101 if (ParamQs.hasAddressSpace())
1102 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001103 if (ParamQs.hasObjCLifetime())
1104 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001105
1106 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001107 // If template deduction would produce a lifetime qualifier on a type
1108 // that is not a lifetime type, template argument deduction fails.
1109 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1110 !DeducedType->isDependentType()) {
1111 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1112 Info.FirstArg = TemplateArgument(Param);
1113 Info.SecondArg = TemplateArgument(Arg);
1114 return Sema::TDK_Underqualified;
1115 }
1116
1117 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001118 // If template deduction would produce an argument type with lifetime type
1119 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001120 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001121 DeducedType->isObjCLifetimeType() &&
1122 !DeducedQs.hasObjCLifetime())
1123 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1124
Douglas Gregor1d684c22011-04-28 00:56:09 +00001125 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1126 DeducedQs);
1127
Douglas Gregord6605db2009-07-22 21:30:48 +00001128 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001129 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001130
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001131 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001133 Deduced[Index],
1134 NewDeduced);
1135 if (Result.isNull()) {
1136 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1137 Info.FirstArg = Deduced[Index];
1138 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001142 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001144 }
1145
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001146 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001147 Info.FirstArg = TemplateArgument(ParamIn);
1148 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001149
Douglas Gregorfb322d82011-01-14 05:11:40 +00001150 // If the parameter is an already-substituted template parameter
1151 // pack, do nothing: we don't know which of its arguments to look
1152 // at, so we have to wait until all of the parameter packs in this
1153 // expansion have arguments.
1154 if (isa<SubstTemplateTypeParmPackType>(Param))
1155 return Sema::TDK_Success;
1156
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001157 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001158 CanQualType CanParam = S.Context.getCanonicalType(Param);
1159 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001160 if (!(TDF & TDF_IgnoreQualifiers)) {
1161 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001162 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001163 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001164 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001165 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001166 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001167 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001168
1169 // If the parameter type is not dependent, there is nothing to deduce.
1170 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001171 if (!(TDF & TDF_SkipNonDependent)) {
1172 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1173 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1174 Param != Arg;
1175 if (NonDeduced) {
1176 return Sema::TDK_NonDeducedMismatch;
1177 }
1178 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001179 return Sema::TDK_Success;
1180 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001181 } else if (!Param->isDependentType()) {
1182 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1183 ArgUnqualType = CanArg.getUnqualifiedType();
1184 bool Success = (TDF & TDF_InOverloadResolution)?
1185 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1186 ArgUnqualType) :
1187 ParamUnqualType == ArgUnqualType;
1188 if (Success)
1189 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001190 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001191
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001192 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001193 // Non-canonical types cannot appear here.
1194#define NON_CANONICAL_TYPE(Class, Base) \
1195 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1196#define TYPE(Class, Base)
1197#include "clang/AST/TypeNodes.def"
1198
1199 case Type::TemplateTypeParm:
1200 case Type::SubstTemplateTypeParmPack:
1201 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001202
1203 // These types cannot be dependent, so simply check whether the types are
1204 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001205 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001206 case Type::VariableArray:
1207 case Type::Vector:
1208 case Type::FunctionNoProto:
1209 case Type::Record:
1210 case Type::Enum:
1211 case Type::ObjCObject:
1212 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001213 case Type::ObjCObjectPointer: {
1214 if (TDF & TDF_SkipNonDependent)
1215 return Sema::TDK_Success;
1216
1217 if (TDF & TDF_IgnoreQualifiers) {
1218 Param = Param.getUnqualifiedType();
1219 Arg = Arg.getUnqualifiedType();
1220 }
1221
1222 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1223 }
1224
Douglas Gregor39c02722011-06-15 16:02:29 +00001225 // _Complex T [placeholder extension]
1226 case Type::Complex:
1227 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001228 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001229 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001230 ComplexArg->getElementType(),
1231 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001232
1233 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001234
1235 // _Atomic T [extension]
1236 case Type::Atomic:
1237 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001238 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001239 cast<AtomicType>(Param)->getValueType(),
1240 AtomicArg->getValueType(),
1241 Info, Deduced, TDF);
1242
1243 return Sema::TDK_NonDeducedMismatch;
1244
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001245 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001246 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001247 QualType PointeeType;
1248 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1249 PointeeType = PointerArg->getPointeeType();
1250 } else if (const ObjCObjectPointerType *PointerArg
1251 = Arg->getAs<ObjCObjectPointerType>()) {
1252 PointeeType = PointerArg->getPointeeType();
1253 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001254 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001255 }
Mike Stump11289f42009-09-09 15:08:12 +00001256
Douglas Gregorfc516c92009-06-26 23:27:24 +00001257 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001258 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1259 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001260 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001261 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001264 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001265 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001266 const LValueReferenceType *ReferenceArg =
1267 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001268 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001269 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001271 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001272 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001273 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001274 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001275
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001276 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001277 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001278 const RValueReferenceType *ReferenceArg =
1279 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001280 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001281 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001282
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001283 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1284 cast<RValueReferenceType>(Param)->getPointeeType(),
1285 ReferenceArg->getPointeeType(),
1286 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001289 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001290 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001291 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001292 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001293 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001294 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001295
John McCallf7332682010-08-19 00:20:19 +00001296 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001297 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1298 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1299 IncompleteArrayArg->getElementType(),
1300 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001301 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001302
1303 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001304 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001305 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001306 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001307 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001308 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001309
1310 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001311 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001312 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001313 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001314
John McCallf7332682010-08-19 00:20:19 +00001315 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001316 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1317 ConstantArrayParm->getElementType(),
1318 ConstantArrayArg->getElementType(),
1319 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001320 }
1321
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001322 // type [i]
1323 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001324 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001325 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001326 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001327
John McCallf7332682010-08-19 00:20:19 +00001328 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1329
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001330 // Check the element type of the arrays
1331 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001332 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001333 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001334 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1335 DependentArrayParm->getElementType(),
1336 ArrayArg->getElementType(),
1337 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001338 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001339
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001340 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001341 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1343 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001344 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001345
1346 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001347 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001348 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001349 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001350 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001351 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1352 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001354 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001355 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001356 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001357 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001358 if (const DependentSizedArrayType *DependentArrayArg
1359 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001360 if (DependentArrayArg->getSizeExpr())
1361 return DeduceNonTypeTemplateArgument(S, NTTP,
1362 DependentArrayArg->getSizeExpr(),
1363 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001365 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001366 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
1369 // type(*)(T)
1370 // T(*)()
1371 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001372 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001373 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001374 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001375 dyn_cast<FunctionProtoType>(Arg);
1376 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001377 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001378
1379 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001380 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001381
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001383 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001385 != FunctionProtoArg->getRefQualifier() ||
1386 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001387 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001388
Anders Carlsson2128ec72009-06-08 15:19:08 +00001389 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001390 if (Sema::TemplateDeductionResult Result =
1391 DeduceTemplateArgumentsByTypeMatch(
1392 S, TemplateParams, FunctionProtoParam->getReturnType(),
1393 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001394 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001395
Alp Toker9cacbab2014-01-20 20:26:09 +00001396 return DeduceTemplateArguments(
1397 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1398 FunctionProtoParam->getNumParams(),
1399 FunctionProtoArg->param_type_begin(),
1400 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
John McCalle78aac42010-03-10 03:28:59 +00001403 case Type::InjectedClassName: {
1404 // Treat a template's injected-class-name as if the template
1405 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001406 Param = cast<InjectedClassNameType>(Param)
1407 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001408 assert(isa<TemplateSpecializationType>(Param) &&
1409 "injected class name is not a template specialization type");
1410 // fall through
1411 }
1412
Douglas Gregor705c9002009-06-26 20:57:09 +00001413 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001414 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001415 // TT<T>
1416 // TT<i>
1417 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001418 case Type::TemplateSpecialization: {
1419 const TemplateSpecializationType *SpecParam
1420 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001421
Douglas Gregore81f3e72009-07-07 23:09:34 +00001422 // Try to deduce template arguments from the template-id.
1423 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001424 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001425 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001426
Douglas Gregor42909752009-09-30 22:13:51 +00001427 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001428 // C++ [temp.deduct.call]p3b3:
1429 // If P is a class, and P has the form template-id, then A can be a
1430 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001431 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001432 // class pointed to by the deduced A.
1433 //
1434 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001435 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001436 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001437 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1438 // We cannot inspect base classes as part of deduction when the type
1439 // is incomplete, so either instantiate any templates necessary to
1440 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001441 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001442 return Result;
1443
Douglas Gregore81f3e72009-07-07 23:09:34 +00001444 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001445 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001446 // ToVisit is our stack of records that we still need to visit.
1447 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001448 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001449 ToVisit.push_back(RecordT);
1450 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001451 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1452 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001453 while (!ToVisit.empty()) {
1454 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001455 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001456
Douglas Gregore81f3e72009-07-07 23:09:34 +00001457 // If we have already seen this type, skip it.
David Blaikie82e95a32014-11-19 07:49:47 +00001458 if (!Visited.insert(NextT).second)
Douglas Gregore81f3e72009-07-07 23:09:34 +00001459 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregore81f3e72009-07-07 23:09:34 +00001461 // If this is a base class, try to perform template argument
1462 // deduction from it.
1463 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001464 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001465 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001466 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001467 QualType(NextT, 0), BaseInfo,
1468 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Douglas Gregore81f3e72009-07-07 23:09:34 +00001470 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001471 // note that we had some success. Otherwise, ignore any deductions
1472 // from this base class.
1473 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001474 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001475 DeducedOrig.clear();
1476 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001477 Info.Param = BaseInfo.Param;
1478 Info.FirstArg = BaseInfo.FirstArg;
1479 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001480 }
1481 else
1482 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001483 }
Mike Stump11289f42009-09-09 15:08:12 +00001484
Douglas Gregore81f3e72009-07-07 23:09:34 +00001485 // Visit base classes
1486 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001487 for (const auto &Base : Next->bases()) {
1488 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001489 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001490 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001491 }
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Douglas Gregore81f3e72009-07-07 23:09:34 +00001494 if (Successful)
1495 return Sema::TDK_Success;
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregore81f3e72009-07-07 23:09:34 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregore81f3e72009-07-07 23:09:34 +00001500 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001501 }
1502
Douglas Gregor637d9982009-06-10 23:47:09 +00001503 // T type::*
1504 // T T::*
1505 // T (type::*)()
1506 // type (T::*)()
1507 // type (type::*)(T)
1508 // type (T::*)(T)
1509 // T (type::*)(T)
1510 // T (T::*)()
1511 // T (T::*)(T)
1512 case Type::MemberPointer: {
1513 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1514 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1515 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001516 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001517
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001518 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001519 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1520 MemPtrParam->getPointeeType(),
1521 MemPtrArg->getPointeeType(),
1522 Info, Deduced,
1523 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001524 return Result;
1525
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001526 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1527 QualType(MemPtrParam->getClass(), 0),
1528 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001529 Info, Deduced,
1530 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001531 }
1532
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001533 // (clang extension)
1534 //
Mike Stump11289f42009-09-09 15:08:12 +00001535 // type(^)(T)
1536 // T(^)()
1537 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001538 case Type::BlockPointer: {
1539 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1540 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001541
Anders Carlssona767eee2009-06-12 16:23:10 +00001542 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001543 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001544
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001545 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1546 BlockPtrParam->getPointeeType(),
1547 BlockPtrArg->getPointeeType(),
1548 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001549 }
1550
Douglas Gregor39c02722011-06-15 16:02:29 +00001551 // (clang extension)
1552 //
1553 // T __attribute__(((ext_vector_type(<integral constant>))))
1554 case Type::ExtVector: {
1555 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1556 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1557 // Make sure that the vectors have the same number of elements.
1558 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1559 return Sema::TDK_NonDeducedMismatch;
1560
1561 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001562 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1563 VectorParam->getElementType(),
1564 VectorArg->getElementType(),
1565 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001566 }
1567
1568 if (const DependentSizedExtVectorType *VectorArg
1569 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1570 // We can't check the number of elements, since the argument has a
1571 // dependent number of elements. This can only occur during partial
1572 // ordering.
1573
1574 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001575 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1576 VectorParam->getElementType(),
1577 VectorArg->getElementType(),
1578 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001579 }
1580
1581 return Sema::TDK_NonDeducedMismatch;
1582 }
1583
1584 // (clang extension)
1585 //
1586 // T __attribute__(((ext_vector_type(N))))
1587 case Type::DependentSizedExtVector: {
1588 const DependentSizedExtVectorType *VectorParam
1589 = cast<DependentSizedExtVectorType>(Param);
1590
1591 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1592 // Perform deduction on the element types.
1593 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001594 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1595 VectorParam->getElementType(),
1596 VectorArg->getElementType(),
1597 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001598 return Result;
1599
1600 // Perform deduction on the vector size, if we can.
1601 NonTypeTemplateParmDecl *NTTP
1602 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1603 if (!NTTP)
1604 return Sema::TDK_Success;
1605
1606 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1607 ArgSize = VectorArg->getNumElements();
1608 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1609 false, Info, Deduced);
1610 }
1611
1612 if (const DependentSizedExtVectorType *VectorArg
1613 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1614 // Perform deduction on the element types.
1615 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001616 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1617 VectorParam->getElementType(),
1618 VectorArg->getElementType(),
1619 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001620 return Result;
1621
1622 // Perform deduction on the vector size, if we can.
1623 NonTypeTemplateParmDecl *NTTP
1624 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1625 if (!NTTP)
1626 return Sema::TDK_Success;
1627
1628 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1629 Info, Deduced);
1630 }
1631
1632 return Sema::TDK_NonDeducedMismatch;
1633 }
1634
Douglas Gregor637d9982009-06-10 23:47:09 +00001635 case Type::TypeOfExpr:
1636 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001637 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001638 case Type::UnresolvedUsing:
1639 case Type::Decltype:
1640 case Type::UnaryTransform:
1641 case Type::Auto:
1642 case Type::DependentTemplateSpecialization:
1643 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001644 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001645 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001646 }
1647
David Blaikiee4d798f2012-01-20 21:50:17 +00001648 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001649}
1650
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001651static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001652DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001653 TemplateParameterList *TemplateParams,
1654 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001655 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001656 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001657 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001658 // If the template argument is a pack expansion, perform template argument
1659 // deduction against the pattern of that expansion. This only occurs during
1660 // partial ordering.
1661 if (Arg.isPackExpansion())
1662 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001663
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001664 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001665 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001666 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001667
1668 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001669 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001670 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1671 Param.getAsType(),
1672 Arg.getAsType(),
1673 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001674 Info.FirstArg = Param;
1675 Info.SecondArg = Arg;
1676 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001677
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001678 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001679 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001681 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001682 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001683 Info.FirstArg = Param;
1684 Info.SecondArg = Arg;
1685 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001686
1687 case TemplateArgument::TemplateExpansion:
1688 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001690 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001691 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001692 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001693 return Sema::TDK_Success;
1694
1695 Info.FirstArg = Param;
1696 Info.SecondArg = Arg;
1697 return Sema::TDK_NonDeducedMismatch;
1698
1699 case TemplateArgument::NullPtr:
1700 if (Arg.getKind() == TemplateArgument::NullPtr &&
1701 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001702 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001704 Info.FirstArg = Param;
1705 Info.SecondArg = Arg;
1706 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001707
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001708 case TemplateArgument::Integral:
1709 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001710 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001711 return Sema::TDK_Success;
1712
1713 Info.FirstArg = Param;
1714 Info.SecondArg = Arg;
1715 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001716 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001717
1718 if (Arg.getKind() == TemplateArgument::Expression) {
1719 Info.FirstArg = Param;
1720 Info.SecondArg = Arg;
1721 return Sema::TDK_NonDeducedMismatch;
1722 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001723
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001724 Info.FirstArg = Param;
1725 Info.SecondArg = Arg;
1726 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001728 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001729 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001730 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1731 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001732 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001733 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001734 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001735 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001736 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001737 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001738 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001739 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001740 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001741 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001742 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001744 Info.FirstArg = Param;
1745 Info.SecondArg = Arg;
1746 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001747 }
Mike Stump11289f42009-09-09 15:08:12 +00001748
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001749 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001750 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001751 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001752 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001753 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001754 }
Mike Stump11289f42009-09-09 15:08:12 +00001755
David Blaikiee4d798f2012-01-20 21:50:17 +00001756 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001757}
1758
Douglas Gregor7baabef2010-12-22 18:17:10 +00001759/// \brief Determine whether there is a template argument to be used for
1760/// deduction.
1761///
1762/// This routine "expands" argument packs in-place, overriding its input
1763/// parameters so that \c Args[ArgIdx] will be the available template argument.
1764///
1765/// \returns true if there is another template argument (which will be at
1766/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001768 unsigned &ArgIdx,
1769 unsigned &NumArgs) {
1770 if (ArgIdx == NumArgs)
1771 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772
Douglas Gregor7baabef2010-12-22 18:17:10 +00001773 const TemplateArgument &Arg = Args[ArgIdx];
1774 if (Arg.getKind() != TemplateArgument::Pack)
1775 return true;
1776
1777 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1778 Args = Arg.pack_begin();
1779 NumArgs = Arg.pack_size();
1780 ArgIdx = 0;
1781 return ArgIdx < NumArgs;
1782}
1783
Douglas Gregord0ad2942010-12-23 01:24:45 +00001784/// \brief Determine whether the given set of template arguments has a pack
1785/// expansion that is not the last template argument.
1786static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1787 unsigned NumArgs) {
1788 unsigned ArgIdx = 0;
1789 while (ArgIdx < NumArgs) {
1790 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791
Douglas Gregord0ad2942010-12-23 01:24:45 +00001792 // Unwrap argument packs.
1793 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1794 Args = Arg.pack_begin();
1795 NumArgs = Arg.pack_size();
1796 ArgIdx = 0;
1797 continue;
1798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001799
Douglas Gregord0ad2942010-12-23 01:24:45 +00001800 ++ArgIdx;
1801 if (ArgIdx == NumArgs)
1802 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803
Douglas Gregord0ad2942010-12-23 01:24:45 +00001804 if (Arg.isPackExpansion())
1805 return true;
1806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807
Douglas Gregord0ad2942010-12-23 01:24:45 +00001808 return false;
1809}
1810
Douglas Gregor7baabef2010-12-22 18:17:10 +00001811static Sema::TemplateDeductionResult
1812DeduceTemplateArguments(Sema &S,
1813 TemplateParameterList *TemplateParams,
1814 const TemplateArgument *Params, unsigned NumParams,
1815 const TemplateArgument *Args, unsigned NumArgs,
1816 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001817 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001818 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001819 // If the template argument list of P contains a pack expansion that is not
1820 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001821 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001822 if (hasPackExpansionBeforeEnd(Params, NumParams))
1823 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001825 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826 // If P has a form that contains <T> or <i>, then each argument Pi of the
1827 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001828 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001829 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001831 ++ParamIdx) {
1832 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001833 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001834
Douglas Gregor7baabef2010-12-22 18:17:10 +00001835 // Check whether we have enough arguments.
1836 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001837 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001839 if (Args[ArgIdx].isPackExpansion()) {
1840 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1841 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001842 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001845 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001846 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001847 = DeduceTemplateArguments(S, TemplateParams,
1848 Params[ParamIdx], Args[ArgIdx],
1849 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001850 return Result;
1851
Douglas Gregor7baabef2010-12-22 18:17:10 +00001852 // Move to the next argument.
1853 ++ArgIdx;
1854 continue;
1855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001857 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001859 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860 // If Pi is a pack expansion, then the pattern of Pi is compared with
1861 // each remaining argument in the template argument list of A. Each
1862 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001863 // template parameter packs expanded by Pi.
1864 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001866 // FIXME: If there are no remaining arguments, we can bail out early
1867 // and set any deduced parameter packs to an empty argument pack.
1868 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869
Richard Smith0a80d572014-05-29 01:12:14 +00001870 // Prepare to deduce the packs within the pattern.
1871 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001872
1873 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001875 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001876 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001877 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001878 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001879
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001880 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001882 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1883 Info, Deduced))
1884 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885
Richard Smith0a80d572014-05-29 01:12:14 +00001886 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001889 // Build argument packs for each of the parameter packs expanded by this
1890 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001891 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 return Sema::TDK_Success;
1896}
1897
Mike Stump11289f42009-09-09 15:08:12 +00001898static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001899DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001900 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001901 const TemplateArgumentList &ParamList,
1902 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001903 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001904 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001906 ParamList.data(), ParamList.size(),
1907 ArgList.data(), ArgList.size(),
1908 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001909}
1910
Douglas Gregor705c9002009-06-26 20:57:09 +00001911/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001912static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001913 const TemplateArgument &X,
1914 const TemplateArgument &Y) {
1915 if (X.getKind() != Y.getKind())
1916 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001917
Douglas Gregor705c9002009-06-26 20:57:09 +00001918 switch (X.getKind()) {
1919 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001920 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001921
Douglas Gregor705c9002009-06-26 20:57:09 +00001922 case TemplateArgument::Type:
1923 return Context.getCanonicalType(X.getAsType()) ==
1924 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregor705c9002009-06-26 20:57:09 +00001926 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001927 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001928
1929 case TemplateArgument::NullPtr:
1930 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001931
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001932 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001933 case TemplateArgument::TemplateExpansion:
1934 return Context.getCanonicalTemplateName(
1935 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1936 Context.getCanonicalTemplateName(
1937 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
Douglas Gregor705c9002009-06-26 20:57:09 +00001939 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001940 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001941
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001942 case TemplateArgument::Expression: {
1943 llvm::FoldingSetNodeID XID, YID;
1944 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001946 return XID == YID;
1947 }
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor705c9002009-06-26 20:57:09 +00001949 case TemplateArgument::Pack:
1950 if (X.pack_size() != Y.pack_size())
1951 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001952
1953 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1954 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001955 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001956 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001957 if (!isSameTemplateArg(Context, *XP, *YP))
1958 return false;
1959
1960 return true;
1961 }
1962
David Blaikiee4d798f2012-01-20 21:50:17 +00001963 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00001964}
1965
Douglas Gregorca4686d2011-01-04 23:35:54 +00001966/// \brief Allocate a TemplateArgumentLoc where all locations have
1967/// been initialized to the given location.
1968///
1969/// \param S The semantic analysis object.
1970///
James Dennett634962f2012-06-14 21:40:34 +00001971/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00001972/// location information for.
1973///
1974/// \param NTTPType For a declaration template argument, the type of
1975/// the non-type template parameter that corresponds to this template
1976/// argument.
1977///
1978/// \param Loc The source location to use for the resulting template
1979/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00001981getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001983 QualType NTTPType,
1984 SourceLocation Loc) {
1985 switch (Arg.getKind()) {
1986 case TemplateArgument::Null:
1987 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Douglas Gregorca4686d2011-01-04 23:35:54 +00001989 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001991 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Douglas Gregorca4686d2011-01-04 23:35:54 +00001993 case TemplateArgument::Declaration: {
1994 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00001995 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001996 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00001997 return TemplateArgumentLoc(TemplateArgument(E), E);
1998 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999
Eli Friedmanb826a002012-09-26 02:36:12 +00002000 case TemplateArgument::NullPtr: {
2001 Expr *E
2002 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002003 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002004 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2005 E);
2006 }
2007
Douglas Gregorca4686d2011-01-04 23:35:54 +00002008 case TemplateArgument::Integral: {
2009 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002010 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002011 return TemplateArgumentLoc(TemplateArgument(E), E);
2012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002013
Douglas Gregor9d802122011-03-02 17:09:35 +00002014 case TemplateArgument::Template:
2015 case TemplateArgument::TemplateExpansion: {
2016 NestedNameSpecifierLocBuilder Builder;
2017 TemplateName Template = Arg.getAsTemplate();
2018 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2019 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002020 else if (QualifiedTemplateName *QTN =
2021 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002022 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2023
2024 if (Arg.getKind() == TemplateArgument::Template)
2025 return TemplateArgumentLoc(Arg,
2026 Builder.getWithLocInContext(S.Context),
2027 Loc);
2028
2029
2030 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2031 Loc, Loc);
2032 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002033
Douglas Gregorca4686d2011-01-04 23:35:54 +00002034 case TemplateArgument::Expression:
2035 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002036
Douglas Gregorca4686d2011-01-04 23:35:54 +00002037 case TemplateArgument::Pack:
2038 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040
David Blaikiee4d798f2012-01-20 21:50:17 +00002041 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002042}
2043
2044
2045/// \brief Convert the given deduced template argument and add it to the set of
2046/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002047static bool
2048ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2049 DeducedTemplateArgument Arg,
2050 NamedDecl *Template,
2051 QualType NTTPType,
2052 unsigned ArgumentPackIndex,
2053 TemplateDeductionInfo &Info,
2054 bool InFunctionTemplate,
2055 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002056 if (Arg.getKind() == TemplateArgument::Pack) {
2057 // This is a template argument pack, so check each of its arguments against
2058 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002059 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002060 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002061 // When converting the deduced template argument, append it to the
2062 // general output list. We need to do this so that the template argument
2063 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002064 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002065 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002067 NTTPType, PackedArgsBuilder.size(),
2068 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002069 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002070
Douglas Gregor51bc5712011-01-05 20:52:18 +00002071 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002072 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Douglas Gregorca4686d2011-01-04 23:35:54 +00002075 // Create the resulting argument pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002076 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor74c6d192011-01-11 23:09:57 +00002077 PackedArgsBuilder.data(),
2078 PackedArgsBuilder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002079 return false;
2080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081
Douglas Gregorca4686d2011-01-04 23:35:54 +00002082 // Convert the deduced template argument into a template
2083 // argument that we can check, almost as if the user had written
2084 // the template argument explicitly.
2085 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2086 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087
Douglas Gregorca4686d2011-01-04 23:35:54 +00002088 // Check the template argument, converting it as necessary.
2089 return S.CheckTemplateArgument(Param, ArgLoc,
2090 Template,
2091 Template->getLocation(),
2092 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002093 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002094 Output,
2095 InFunctionTemplate
2096 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002098 : Sema::CTAK_Deduced)
2099 : Sema::CTAK_Specified);
2100}
2101
Douglas Gregor684268d2010-04-29 06:21:43 +00002102/// Complete template argument deduction for a class template partial
2103/// specialization.
2104static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002106 ClassTemplatePartialSpecializationDecl *Partial,
2107 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002108 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002109 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002110 // Unevaluated SFINAE context.
2111 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002112 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002113
Douglas Gregor684268d2010-04-29 06:21:43 +00002114 Sema::ContextRAII SavedContext(S, Partial);
2115
2116 // C++ [temp.deduct.type]p2:
2117 // [...] or if any template argument remains neither deduced nor
2118 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002119 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002120 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2121 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002122 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002123 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002124 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002125 return Sema::TDK_Incomplete;
2126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127
Douglas Gregorca4686d2011-01-04 23:35:54 +00002128 // We have deduced this argument, so it still needs to be
2129 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregorca4686d2011-01-04 23:35:54 +00002131 // First, for a non-type template parameter type that is
2132 // initialized by a declaration, we need the type of the
2133 // corresponding non-type template parameter.
2134 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002136 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002137 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002138 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002140 Builder.data(), Builder.size());
2141 NTTPType = S.SubstType(NTTPType,
2142 MultiLevelTemplateArgumentList(TemplateArgs),
2143 NTTP->getLocation(),
2144 NTTP->getDeclName());
2145 if (NTTPType.isNull()) {
2146 Info.Param = makeTemplateParameter(Param);
2147 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2149 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002150 Builder.size()));
2151 return Sema::TDK_SubstitutionFailure;
2152 }
2153 }
2154 }
2155
Douglas Gregorca4686d2011-01-04 23:35:54 +00002156 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002157 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002158 Builder)) {
2159 Info.Param = makeTemplateParameter(Param);
2160 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002161 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2162 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002163 return Sema::TDK_SubstitutionFailure;
2164 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166
Douglas Gregor684268d2010-04-29 06:21:43 +00002167 // Form the template argument list from the deduced template arguments.
2168 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002170 Builder.size());
2171
Douglas Gregor684268d2010-04-29 06:21:43 +00002172 Info.reset(DeducedArgumentList);
2173
2174 // Substitute the deduced template arguments into the template
2175 // arguments of the class template partial specialization, and
2176 // verify that the instantiated template arguments are both valid
2177 // and are equivalent to the template arguments originally provided
2178 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002179 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002180 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002181 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002182 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002183 const TemplateArgumentLoc *PartialTemplateArgs
2184 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002185
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002186 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2187 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002188
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002189 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002190 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2191 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2192 if (ParamIdx >= Partial->getTemplateParameters()->size())
2193 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2194
2195 Decl *Param
2196 = const_cast<NamedDecl *>(
2197 Partial->getTemplateParameters()->getParam(ParamIdx));
2198 Info.Param = makeTemplateParameter(Param);
2199 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2200 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002201 }
2202
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002203 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002204 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002205 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002206 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207
Douglas Gregorca4686d2011-01-04 23:35:54 +00002208 TemplateParameterList *TemplateParams
2209 = ClassTemplate->getTemplateParameters();
2210 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002211 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002212 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002213 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002214 Info.FirstArg = TemplateArgs[I];
2215 Info.SecondArg = InstArg;
2216 return Sema::TDK_NonDeducedMismatch;
2217 }
2218 }
2219
2220 if (Trap.hasErrorOccurred())
2221 return Sema::TDK_SubstitutionFailure;
2222
2223 return Sema::TDK_Success;
2224}
2225
Douglas Gregor170bc422009-06-12 22:31:52 +00002226/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002227/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002228/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002229Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002230Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002231 const TemplateArgumentList &TemplateArgs,
2232 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002233 if (Partial->isInvalidDecl())
2234 return TDK_Invalid;
2235
Douglas Gregor170bc422009-06-12 22:31:52 +00002236 // C++ [temp.class.spec.match]p2:
2237 // A partial specialization matches a given actual template
2238 // argument list if the template arguments of the partial
2239 // specialization can be deduced from the actual template argument
2240 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002241
2242 // Unevaluated SFINAE context.
2243 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002244 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002245
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002247 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002248 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002249 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002250 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002251 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002252 TemplateArgs, Info, Deduced))
2253 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002254
Richard Smith80934652012-07-16 01:09:10 +00002255 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002256 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2257 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002258 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002259 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002260
Douglas Gregore1416332009-06-14 08:02:22 +00002261 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002262 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002263
2264 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002265 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002266}
Douglas Gregor91772d12009-06-13 00:26:55 +00002267
Larisse Voufo39a1e502013-08-06 01:03:05 +00002268/// Complete template argument deduction for a variable template partial
2269/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002270/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2271/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2272/// VarTemplate(Partial)SpecializationDecl with a new data
2273/// structure Template(Partial)SpecializationDecl, and
2274/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002275static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2276 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2277 const TemplateArgumentList &TemplateArgs,
2278 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2279 TemplateDeductionInfo &Info) {
2280 // Unevaluated SFINAE context.
2281 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2282 Sema::SFINAETrap Trap(S);
2283
2284 // C++ [temp.deduct.type]p2:
2285 // [...] or if any template argument remains neither deduced nor
2286 // explicitly specified, template argument deduction fails.
2287 SmallVector<TemplateArgument, 4> Builder;
2288 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2289 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2290 NamedDecl *Param = PartialParams->getParam(I);
2291 if (Deduced[I].isNull()) {
2292 Info.Param = makeTemplateParameter(Param);
2293 return Sema::TDK_Incomplete;
2294 }
2295
2296 // We have deduced this argument, so it still needs to be
2297 // checked and converted.
2298
2299 // First, for a non-type template parameter type that is
2300 // initialized by a declaration, we need the type of the
2301 // corresponding non-type template parameter.
2302 QualType NTTPType;
2303 if (NonTypeTemplateParmDecl *NTTP =
2304 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2305 NTTPType = NTTP->getType();
2306 if (NTTPType->isDependentType()) {
2307 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2308 Builder.data(), Builder.size());
2309 NTTPType =
2310 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2311 NTTP->getLocation(), NTTP->getDeclName());
2312 if (NTTPType.isNull()) {
2313 Info.Param = makeTemplateParameter(Param);
2314 // FIXME: These template arguments are temporary. Free them!
2315 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2316 Builder.size()));
2317 return Sema::TDK_SubstitutionFailure;
2318 }
2319 }
2320 }
2321
2322 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2323 0, Info, false, Builder)) {
2324 Info.Param = makeTemplateParameter(Param);
2325 // FIXME: These template arguments are temporary. Free them!
2326 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2327 Builder.size()));
2328 return Sema::TDK_SubstitutionFailure;
2329 }
2330 }
2331
2332 // Form the template argument list from the deduced template arguments.
2333 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2334 S.Context, Builder.data(), Builder.size());
2335
2336 Info.reset(DeducedArgumentList);
2337
2338 // Substitute the deduced template arguments into the template
2339 // arguments of the class template partial specialization, and
2340 // verify that the instantiated template arguments are both valid
2341 // and are equivalent to the template arguments originally provided
2342 // to the class template.
2343 LocalInstantiationScope InstScope(S);
2344 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002345 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2346 = Partial->getTemplateArgsAsWritten();
2347 const TemplateArgumentLoc *PartialTemplateArgs
2348 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002349
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002350 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2351 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002352
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002353 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002354 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2355 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2356 if (ParamIdx >= Partial->getTemplateParameters()->size())
2357 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2358
2359 Decl *Param = const_cast<NamedDecl *>(
2360 Partial->getTemplateParameters()->getParam(ParamIdx));
2361 Info.Param = makeTemplateParameter(Param);
2362 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2363 return Sema::TDK_SubstitutionFailure;
2364 }
2365 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2366 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2367 false, ConvertedInstArgs))
2368 return Sema::TDK_SubstitutionFailure;
2369
2370 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2371 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2372 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2373 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2374 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2375 Info.FirstArg = TemplateArgs[I];
2376 Info.SecondArg = InstArg;
2377 return Sema::TDK_NonDeducedMismatch;
2378 }
2379 }
2380
2381 if (Trap.hasErrorOccurred())
2382 return Sema::TDK_SubstitutionFailure;
2383
2384 return Sema::TDK_Success;
2385}
2386
2387/// \brief Perform template argument deduction to determine whether
2388/// the given template arguments match the given variable template
2389/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002390/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2391/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2392/// VarTemplate(Partial)SpecializationDecl with a new data
2393/// structure Template(Partial)SpecializationDecl, and
2394/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002395Sema::TemplateDeductionResult
2396Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2397 const TemplateArgumentList &TemplateArgs,
2398 TemplateDeductionInfo &Info) {
2399 if (Partial->isInvalidDecl())
2400 return TDK_Invalid;
2401
2402 // C++ [temp.class.spec.match]p2:
2403 // A partial specialization matches a given actual template
2404 // argument list if the template arguments of the partial
2405 // specialization can be deduced from the actual template argument
2406 // list (14.8.2).
2407
2408 // Unevaluated SFINAE context.
2409 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2410 SFINAETrap Trap(*this);
2411
2412 SmallVector<DeducedTemplateArgument, 4> Deduced;
2413 Deduced.resize(Partial->getTemplateParameters()->size());
2414 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2415 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2416 TemplateArgs, Info, Deduced))
2417 return Result;
2418
2419 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002420 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2421 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002422 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002423 return TDK_InstantiationDepth;
2424
2425 if (Trap.hasErrorOccurred())
2426 return Sema::TDK_SubstitutionFailure;
2427
2428 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2429 Deduced, Info);
2430}
2431
Douglas Gregorfc516c92009-06-26 23:27:24 +00002432/// \brief Determine whether the given type T is a simple-template-id type.
2433static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002434 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002435 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002436 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregorfc516c92009-06-26 23:27:24 +00002438 return false;
2439}
Douglas Gregor9b146582009-07-08 20:55:45 +00002440
2441/// \brief Substitute the explicitly-provided template arguments into the
2442/// given function template according to C++ [temp.arg.explicit].
2443///
2444/// \param FunctionTemplate the function template into which the explicit
2445/// template arguments will be substituted.
2446///
James Dennett634962f2012-06-14 21:40:34 +00002447/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002448/// arguments.
2449///
Mike Stump11289f42009-09-09 15:08:12 +00002450/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002451/// with the converted and checked explicit template arguments.
2452///
Mike Stump11289f42009-09-09 15:08:12 +00002453/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002454/// parameters.
2455///
2456/// \param FunctionType if non-NULL, the result type of the function template
2457/// will also be instantiated and the pointed-to value will be updated with
2458/// the instantiated function type.
2459///
2460/// \param Info if substitution fails for any reason, this object will be
2461/// populated with more information about the failure.
2462///
2463/// \returns TDK_Success if substitution was successful, or some failure
2464/// condition.
2465Sema::TemplateDeductionResult
2466Sema::SubstituteExplicitTemplateArguments(
2467 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002468 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002469 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2470 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002471 QualType *FunctionType,
2472 TemplateDeductionInfo &Info) {
2473 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2474 TemplateParameterList *TemplateParams
2475 = FunctionTemplate->getTemplateParameters();
2476
John McCall6b51f282009-11-23 01:53:49 +00002477 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002478 // No arguments to substitute; just copy over the parameter types and
2479 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002480 for (auto P : Function->params())
2481 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002482
Douglas Gregor9b146582009-07-08 20:55:45 +00002483 if (FunctionType)
2484 *FunctionType = Function->getType();
2485 return TDK_Success;
2486 }
Mike Stump11289f42009-09-09 15:08:12 +00002487
Eli Friedman77dcc722012-02-08 03:07:05 +00002488 // Unevaluated SFINAE context.
2489 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002490 SFINAETrap Trap(*this);
2491
Douglas Gregor9b146582009-07-08 20:55:45 +00002492 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002493 // Template arguments that are present shall be specified in the
2494 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002495 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002496 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002497 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002498
2499 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002500 // explicitly-specified template arguments against this function template,
2501 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002502 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002503 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2504 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002505 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2506 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002507 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002508 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002509
Douglas Gregor9b146582009-07-08 20:55:45 +00002510 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002511 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002512 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002513 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002514 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002515 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002516 if (Index >= TemplateParams->size())
2517 Index = TemplateParams->size() - 1;
2518 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002519 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002520 }
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregor9b146582009-07-08 20:55:45 +00002522 // Form the template argument list from the explicitly-specified
2523 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002524 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002525 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002526 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002527
John McCall036855a2010-10-12 19:40:14 +00002528 // Template argument deduction and the final substitution should be
2529 // done in the context of the templated declaration. Explicit
2530 // argument substitution, on the other hand, needs to happen in the
2531 // calling context.
2532 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2533
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002534 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002535 // note that the template argument pack is partially substituted and record
2536 // the explicit template arguments. They'll be used as part of deduction
2537 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002538 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2539 const TemplateArgument &Arg = Builder[I];
2540 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002541 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002543 Arg.pack_begin(),
2544 Arg.pack_size());
2545 break;
2546 }
2547 }
2548
Richard Smith5e580292012-02-10 09:58:53 +00002549 const FunctionProtoType *Proto
2550 = Function->getType()->getAs<FunctionProtoType>();
2551 assert(Proto && "Function template does not have a prototype?");
2552
Richard Smith70b13042015-01-09 01:19:56 +00002553 // Isolate our substituted parameters from our caller.
2554 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2555
Douglas Gregor9b146582009-07-08 20:55:45 +00002556 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002557 // explicitly-specified template arguments. If the function has a trailing
2558 // return type, substitute it after the arguments to ensure we substitute
2559 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002560 if (Proto->hasTrailingReturn()) {
2561 if (SubstParmTypes(Function->getLocation(),
2562 Function->param_begin(), Function->getNumParams(),
2563 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2564 ParamTypes))
2565 return TDK_SubstitutionFailure;
2566 }
2567
Richard Smith5e580292012-02-10 09:58:53 +00002568 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002569 QualType ResultType;
2570 {
2571 // C++11 [expr.prim.general]p3:
2572 // If a declaration declares a member function or member function
2573 // template of a class X, the expression this is a prvalue of type
2574 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2575 // and the end of the function-definition, member-declarator, or
2576 // declarator.
2577 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002578 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2580 ThisContext = Method->getParent();
2581 ThisTypeQuals = Method->getTypeQualifiers();
2582 }
2583
2584 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002585 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002586
2587 ResultType =
2588 SubstType(Proto->getReturnType(),
2589 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2590 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002591 if (ResultType.isNull() || Trap.hasErrorOccurred())
2592 return TDK_SubstitutionFailure;
2593 }
2594
Richard Smith5e580292012-02-10 09:58:53 +00002595 // Instantiate the types of each of the function parameters given the
2596 // explicitly-specified template arguments if we didn't do so earlier.
2597 if (!Proto->hasTrailingReturn() &&
2598 SubstParmTypes(Function->getLocation(),
2599 Function->param_begin(), Function->getNumParams(),
2600 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2601 ParamTypes))
2602 return TDK_SubstitutionFailure;
2603
Douglas Gregor9b146582009-07-08 20:55:45 +00002604 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002605 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002606 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002607 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002608 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002609 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2610 return TDK_SubstitutionFailure;
2611 }
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregor9b146582009-07-08 20:55:45 +00002613 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002614 // Trailing template arguments that can be deduced (14.8.2) may be
2615 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002616 // template arguments can be deduced, they may all be omitted; in this
2617 // case, the empty template argument list <> itself may also be omitted.
2618 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002619 // Take all of the explicitly-specified arguments and put them into
2620 // the set of deduced template arguments. Explicitly-specified
2621 // parameter packs, however, will be set to NULL since the deduction
2622 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002623 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002624 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2625 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2626 if (Arg.getKind() == TemplateArgument::Pack)
2627 Deduced.push_back(DeducedTemplateArgument());
2628 else
2629 Deduced.push_back(Arg);
2630 }
Mike Stump11289f42009-09-09 15:08:12 +00002631
Douglas Gregor9b146582009-07-08 20:55:45 +00002632 return TDK_Success;
2633}
2634
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002635/// \brief Check whether the deduced argument type for a call to a function
2636/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2637static bool
2638CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2639 QualType DeducedA) {
2640 ASTContext &Context = S.Context;
2641
2642 QualType A = OriginalArg.OriginalArgType;
2643 QualType OriginalParamType = OriginalArg.OriginalParamType;
2644
2645 // Check for type equality (top-level cv-qualifiers are ignored).
2646 if (Context.hasSameUnqualifiedType(A, DeducedA))
2647 return false;
2648
2649 // Strip off references on the argument types; they aren't needed for
2650 // the following checks.
2651 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2652 DeducedA = DeducedARef->getPointeeType();
2653 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2654 A = ARef->getPointeeType();
2655
2656 // C++ [temp.deduct.call]p4:
2657 // [...] However, there are three cases that allow a difference:
2658 // - If the original P is a reference type, the deduced A (i.e., the
2659 // type referred to by the reference) can be more cv-qualified than
2660 // the transformed A.
2661 if (const ReferenceType *OriginalParamRef
2662 = OriginalParamType->getAs<ReferenceType>()) {
2663 // We don't want to keep the reference around any more.
2664 OriginalParamType = OriginalParamRef->getPointeeType();
2665
2666 Qualifiers AQuals = A.getQualifiers();
2667 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002668
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002669 // Under Objective-C++ ARC, the deduced type may have implicitly
2670 // been given strong or (when dealing with a const reference)
2671 // unsafe_unretained lifetime. If so, update the original
2672 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002673 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002674 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2675 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2676 (DeducedAQuals.hasConst() &&
2677 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2678 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002679 }
2680
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002681 if (AQuals == DeducedAQuals) {
2682 // Qualifiers match; there's nothing to do.
2683 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002684 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002685 } else {
2686 // Qualifiers are compatible, so have the argument type adopt the
2687 // deduced argument type's qualifiers as if we had performed the
2688 // qualification conversion.
2689 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2690 }
2691 }
2692
2693 // - The transformed A can be another pointer or pointer to member
2694 // type that can be converted to the deduced A via a qualification
2695 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002696 //
2697 // Also allow conversions which merely strip [[noreturn]] from function types
2698 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002699 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002700 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002701 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002702 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002703 (S.IsQualificationConversion(A, DeducedA, false,
2704 ObjCLifetimeConversion) ||
2705 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002706 return false;
2707
2708
2709 // - If P is a class and P has the form simple-template-id, then the
2710 // transformed A can be a derived class of the deduced A. [...]
2711 // [...] Likewise, if P is a pointer to a class of the form
2712 // simple-template-id, the transformed A can be a pointer to a
2713 // derived class pointed to by the deduced A.
2714 if (const PointerType *OriginalParamPtr
2715 = OriginalParamType->getAs<PointerType>()) {
2716 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2717 if (const PointerType *APtr = A->getAs<PointerType>()) {
2718 if (A->getPointeeType()->isRecordType()) {
2719 OriginalParamType = OriginalParamPtr->getPointeeType();
2720 DeducedA = DeducedAPtr->getPointeeType();
2721 A = APtr->getPointeeType();
2722 }
2723 }
2724 }
2725 }
2726
2727 if (Context.hasSameUnqualifiedType(A, DeducedA))
2728 return false;
2729
2730 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2731 S.IsDerivedFrom(A, DeducedA))
2732 return false;
2733
2734 return true;
2735}
2736
Mike Stump11289f42009-09-09 15:08:12 +00002737/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002738/// checking the deduced template arguments for completeness and forming
2739/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002740///
2741/// \param OriginalCallArgs If non-NULL, the original call arguments against
2742/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002743Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002744Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002745 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002746 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002747 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002748 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002749 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2750 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002751 TemplateParameterList *TemplateParams
2752 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002753
Eli Friedman77dcc722012-02-08 03:07:05 +00002754 // Unevaluated SFINAE context.
2755 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002756 SFINAETrap Trap(*this);
2757
Douglas Gregor9b146582009-07-08 20:55:45 +00002758 // Enter a new template instantiation context while we instantiate the
2759 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002760 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002761 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2762 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002763 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2764 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002765 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002766 return TDK_InstantiationDepth;
2767
John McCalle23b8712010-04-29 01:18:58 +00002768 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002769
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002770 // C++ [temp.deduct.type]p2:
2771 // [...] or if any template argument remains neither deduced nor
2772 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002773 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002774 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2775 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002776
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002777 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002778 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002779 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002781 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002782 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002783 // We may have had explicitly-specified template arguments for a
2784 // template parameter pack (that may or may not have been extended
2785 // via additional deduced arguments).
2786 if (Param->isParameterPack() && CurrentInstantiationScope) {
2787 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2788 Param) {
2789 // Forget the partially-substituted pack; its substitution is now
2790 // complete.
2791 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2792 }
2793 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002794 continue;
2795 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002796 // We have deduced this argument, so it still needs to be
2797 // checked and converted.
2798
2799 // First, for a non-type template parameter type that is
2800 // initialized by a declaration, we need the type of the
2801 // corresponding non-type template parameter.
2802 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803 if (NonTypeTemplateParmDecl *NTTP
2804 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002805 NTTPType = NTTP->getType();
2806 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002807 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002808 Builder.data(), Builder.size());
2809 NTTPType = SubstType(NTTPType,
2810 MultiLevelTemplateArgumentList(TemplateArgs),
2811 NTTP->getLocation(),
2812 NTTP->getDeclName());
2813 if (NTTPType.isNull()) {
2814 Info.Param = makeTemplateParameter(Param);
2815 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816 Info.reset(TemplateArgumentList::CreateCopy(Context,
2817 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002818 Builder.size()));
2819 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002820 }
2821 }
2822 }
2823
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002824 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002825 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002826 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002827 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002828 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2830 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002831 return TDK_SubstitutionFailure;
2832 }
2833
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002834 continue;
2835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002837 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002839 // be deduced to an empty sequence of template arguments.
2840 // FIXME: Where did the word "trailing" come from?
2841 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002842 // We may have had explicitly-specified template arguments for this
2843 // template parameter pack. If so, our empty deduction extends the
2844 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2845 const TemplateArgument *ExplicitArgs;
2846 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002847 if (CurrentInstantiationScope &&
2848 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002849 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002850 == Param) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002851 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002852
Douglas Gregorcaddba92013-01-18 22:27:09 +00002853 // Forget the partially-substituted pack; it's substitution is now
2854 // complete.
2855 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2856 } else {
2857 Builder.push_back(TemplateArgument::getEmptyPack());
2858 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002859 continue;
2860 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002861
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002862 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002863 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002864 TemplateArgumentLoc DefArg
2865 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2866 FunctionTemplate->getLocation(),
2867 FunctionTemplate->getSourceRange().getEnd(),
2868 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002869 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002870
2871 // If there was no default argument, deduction is incomplete.
2872 if (DefArg.getArgument().isNull()) {
2873 Info.Param = makeTemplateParameter(
2874 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002875 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2876 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002877 if (PartialOverloading) break;
2878
Richard Smithc87b9382013-07-04 01:01:24 +00002879 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002881
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002882 // Check whether we can actually use the default argument.
2883 if (CheckTemplateArgument(Param, DefArg,
2884 FunctionTemplate,
2885 FunctionTemplate->getLocation(),
2886 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002887 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002888 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002889 Info.Param = makeTemplateParameter(
2890 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002891 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002892 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002893 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002894 return TDK_SubstitutionFailure;
2895 }
2896
2897 // If we get here, we successfully used the default template argument.
2898 }
2899
2900 // Form the template argument list from the deduced template arguments.
2901 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002902 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002903 Info.reset(DeducedArgumentList);
2904
Mike Stump11289f42009-09-09 15:08:12 +00002905 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002906 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002907 DeclContext *Owner = FunctionTemplate->getDeclContext();
2908 if (FunctionTemplate->getFriendObjectKind())
2909 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002910 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002911 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002912 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002913 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002914 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002917 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918
Mike Stump11289f42009-09-09 15:08:12 +00002919 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002920 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002921 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2922 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002923 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002924
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002925 // There may have been an error that did not prevent us from constructing a
2926 // declaration. Mark the declaration invalid and return with a substitution
2927 // failure.
2928 if (Trap.hasErrorOccurred()) {
2929 Specialization->setInvalidDecl(true);
2930 return TDK_SubstitutionFailure;
2931 }
2932
Douglas Gregore65aacb2011-06-16 16:50:48 +00002933 if (OriginalCallArgs) {
2934 // C++ [temp.deduct.call]p4:
2935 // In general, the deduction process attempts to find template argument
2936 // values that will make the deduced A identical to A (after the type A
2937 // is transformed as described above). [...]
2938 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2939 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002940 unsigned ParamIdx = OriginalArg.ArgIdx;
2941
2942 if (ParamIdx >= Specialization->getNumParams())
2943 continue;
2944
2945 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002946 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2947 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002948 }
2949 }
2950
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002951 // If we suppressed any diagnostics while performing template argument
2952 // deduction, and if we haven't already instantiated this declaration,
2953 // keep track of these diagnostics. They'll be emitted if this specialization
2954 // is actually used.
2955 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002956 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002957 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2958 if (Pos == SuppressedDiagnostics.end())
2959 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2960 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002962
Mike Stump11289f42009-09-09 15:08:12 +00002963 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002964}
2965
John McCall8d08b9b2010-08-27 09:08:28 +00002966/// Gets the type of a function for template-argument-deducton
2967/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002968static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002969 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002970 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002971 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002972 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002973 return QualType();
2974
John McCallc1f69982010-02-02 02:21:27 +00002975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002976 if (Method->isInstance()) {
2977 // An instance method that's referenced in a form that doesn't
2978 // look like a member pointer is just invalid.
2979 if (!R.HasFormOfMemberPointer) return QualType();
2980
Richard Smith2a7d4812013-05-04 07:00:32 +00002981 return S.Context.getMemberPointerType(Fn->getType(),
2982 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002983 }
2984
2985 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002986 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002987}
2988
2989/// Apply the deduction rules for overload sets.
2990///
2991/// \return the null type if this argument should be treated as an
2992/// undeduced context
2993static QualType
2994ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002995 Expr *Arg, QualType ParamType,
2996 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997
John McCall8d08b9b2010-08-27 09:08:28 +00002998 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002999
John McCall8d08b9b2010-08-27 09:08:28 +00003000 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003001
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003002 // C++0x [temp.deduct.call]p4
3003 unsigned TDF = 0;
3004 if (ParamWasReference)
3005 TDF |= TDF_ParamWithReferenceType;
3006 if (R.IsAddressOfOperand)
3007 TDF |= TDF_IgnoreQualifiers;
3008
John McCallc1f69982010-02-02 02:21:27 +00003009 // C++0x [temp.deduct.call]p6:
3010 // When P is a function type, pointer to function type, or pointer
3011 // to member function type:
3012
3013 if (!ParamType->isFunctionType() &&
3014 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003015 !ParamType->isMemberFunctionPointerType()) {
3016 if (Ovl->hasExplicitTemplateArgs()) {
3017 // But we can still look for an explicit specialization.
3018 if (FunctionDecl *ExplicitSpec
3019 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003020 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003021 }
John McCallc1f69982010-02-02 02:21:27 +00003022
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003023 return QualType();
3024 }
3025
3026 // Gather the explicit template arguments, if any.
3027 TemplateArgumentListInfo ExplicitTemplateArgs;
3028 if (Ovl->hasExplicitTemplateArgs())
3029 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003030 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003031 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3032 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003033 NamedDecl *D = (*I)->getUnderlyingDecl();
3034
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003035 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3036 // - If the argument is an overload set containing one or more
3037 // function templates, the parameter is treated as a
3038 // non-deduced context.
3039 if (!Ovl->hasExplicitTemplateArgs())
3040 return QualType();
3041
3042 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003043 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003044 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003045 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3046 Specialization, Info))
3047 continue;
3048
3049 D = Specialization;
3050 }
John McCallc1f69982010-02-02 02:21:27 +00003051
3052 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003053 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003054 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003055
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003056 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003057 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003058 ArgType->isFunctionType())
3059 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060
John McCallc1f69982010-02-02 02:21:27 +00003061 // - If the argument is an overload set (not containing function
3062 // templates), trial argument deduction is attempted using each
3063 // of the members of the set. If deduction succeeds for only one
3064 // of the overload set members, that member is used as the
3065 // argument value for the deduction. If deduction succeeds for
3066 // more than one member of the overload set the parameter is
3067 // treated as a non-deduced context.
3068
3069 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3070 // Type deduction is done independently for each P/A pair, and
3071 // the deduced template argument values are then combined.
3072 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003073 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003074 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003075 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003076 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003077 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3078 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003079 if (Result) continue;
3080 if (!Match.isNull()) return QualType();
3081 Match = ArgType;
3082 }
3083
3084 return Match;
3085}
3086
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003087/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003088/// described in C++ [temp.deduct.call].
3089///
3090/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003091/// argument deduction based on this P/A pair because the argument is an
3092/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003093static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3094 TemplateParameterList *TemplateParams,
3095 QualType &ParamType,
3096 QualType &ArgType,
3097 Expr *Arg,
3098 unsigned &TDF) {
3099 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003100 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003101 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003102 if (ParamType.hasQualifiers())
3103 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003104
3105 // [...] If P is a reference type, the type referred to by P is
3106 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003107 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003108 if (ParamRefType)
3109 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003110
Nathan Sidwell96090022015-01-16 15:20:14 +00003111 // Overload sets usually make this parameter an undeduced context,
3112 // but there are sometimes special circumstances. Typically
3113 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003114 if (ArgType == S.Context.OverloadTy) {
3115 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3116 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003117 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003118 if (ArgType.isNull())
3119 return true;
3120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121
Douglas Gregor7825bf32011-01-06 22:09:01 +00003122 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003123 // If the argument has incomplete array type, try to complete its type.
3124 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
3125 ArgType = Arg->getType();
3126
Douglas Gregor7825bf32011-01-06 22:09:01 +00003127 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003128 // If P is an rvalue reference to a cv-unqualified template
3129 // parameter and the argument is an lvalue, the type "lvalue
3130 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003131 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003132 !ParamType.getQualifiers() &&
3133 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003134 Arg->isLValue())
3135 ArgType = S.Context.getLValueReferenceType(ArgType);
3136 } else {
3137 // C++ [temp.deduct.call]p2:
3138 // If P is not a reference type:
3139 // - If A is an array type, the pointer type produced by the
3140 // array-to-pointer standard conversion (4.2) is used in place of
3141 // A for type deduction; otherwise,
3142 if (ArgType->isArrayType())
3143 ArgType = S.Context.getArrayDecayedType(ArgType);
3144 // - If A is a function type, the pointer type produced by the
3145 // function-to-pointer standard conversion (4.3) is used in place
3146 // of A for type deduction; otherwise,
3147 else if (ArgType->isFunctionType())
3148 ArgType = S.Context.getPointerType(ArgType);
3149 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003150 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003151 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003152 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003153 }
3154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155
Douglas Gregor7825bf32011-01-06 22:09:01 +00003156 // C++0x [temp.deduct.call]p4:
3157 // In general, the deduction process attempts to find template argument
3158 // values that will make the deduced A identical to A (after the type A
3159 // is transformed as described above). [...]
3160 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Douglas Gregor7825bf32011-01-06 22:09:01 +00003162 // - If the original P is a reference type, the deduced A (i.e., the
3163 // type referred to by the reference) can be more cv-qualified than
3164 // the transformed A.
3165 if (ParamRefType)
3166 TDF |= TDF_ParamWithReferenceType;
3167 // - The transformed A can be another pointer or pointer to member
3168 // type that can be converted to the deduced A via a qualification
3169 // conversion (4.4).
3170 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3171 ArgType->isObjCObjectPointerType())
3172 TDF |= TDF_IgnoreQualifiers;
3173 // - If P is a class and P has the form simple-template-id, then the
3174 // transformed A can be a derived class of the deduced A. Likewise,
3175 // if P is a pointer to a class of the form simple-template-id, the
3176 // transformed A can be a pointer to a derived class pointed to by
3177 // the deduced A.
3178 if (isSimpleTemplateIdType(ParamType) ||
3179 (isa<PointerType>(ParamType) &&
3180 isSimpleTemplateIdType(
3181 ParamType->getAs<PointerType>()->getPointeeType())))
3182 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Douglas Gregor7825bf32011-01-06 22:09:01 +00003184 return false;
3185}
3186
Nico Weberc153d242014-07-28 00:02:09 +00003187static bool
3188hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3189 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003190
Sebastian Redl19181662012-03-15 21:40:51 +00003191/// \brief Perform template argument deduction by matching a parameter type
3192/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003193/// an initializer list that was originally matched against a parameter
3194/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003195static Sema::TemplateDeductionResult
3196DeduceTemplateArgumentByListElement(Sema &S,
3197 TemplateParameterList *TemplateParams,
3198 QualType ParamType, Expr *Arg,
3199 TemplateDeductionInfo &Info,
3200 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3201 unsigned TDF) {
3202 // Handle the case where an init list contains another init list as the
3203 // element.
3204 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3205 QualType X;
3206 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3207 return Sema::TDK_Success; // Just ignore this expression.
3208
3209 // Recurse down into the init list.
3210 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3211 if (Sema::TemplateDeductionResult Result =
3212 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3213 ILE->getInit(i),
3214 Info, Deduced, TDF))
3215 return Result;
3216 }
3217 return Sema::TDK_Success;
3218 }
3219
3220 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003221 QualType ArgType = Arg->getType();
3222 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003223 ArgType, Arg, TDF)) {
3224 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003225 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003226 }
Sebastian Redl19181662012-03-15 21:40:51 +00003227 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003228 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003229}
3230
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003231/// \brief Perform template argument deduction from a function call
3232/// (C++ [temp.deduct.call]).
3233///
3234/// \param FunctionTemplate the function template for which we are performing
3235/// template argument deduction.
3236///
James Dennett18348b62012-06-22 08:52:37 +00003237/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003238/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003239///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003240/// \param Args the function call arguments
3241///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003242/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003243/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003244/// template argument deduction.
3245///
3246/// \param Info the argument will be updated to provide additional information
3247/// about template argument deduction.
3248///
3249/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003250Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3251 FunctionTemplateDecl *FunctionTemplate,
3252 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003253 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3254 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003255 if (FunctionTemplate->isInvalidDecl())
3256 return TDK_Invalid;
3257
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003258 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003259 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003260
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003261 // C++ [temp.deduct.call]p1:
3262 // Template argument deduction is done by comparing each function template
3263 // parameter type (call it P) with the type of the corresponding argument
3264 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003265 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003266 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003267 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003268 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003269 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003270 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003271 if (Proto->isTemplateVariadic())
3272 /* Do nothing */;
3273 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003274 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003276 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Douglas Gregor89026b52009-06-30 23:57:56 +00003279 // The types of the parameters from which we will perform template argument
3280 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003281 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003282 TemplateParameterList *TemplateParams
3283 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003284 SmallVector<DeducedTemplateArgument, 4> Deduced;
3285 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003286 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003287 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003288 TemplateDeductionResult Result =
3289 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003290 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003291 Deduced,
3292 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003293 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003294 Info);
3295 if (Result)
3296 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003297
3298 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003299 } else {
3300 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003301 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003302 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3303 }
Mike Stump11289f42009-09-09 15:08:12 +00003304
Douglas Gregor89026b52009-06-30 23:57:56 +00003305 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003306 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003307 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003308 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003309 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3310 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003311 QualType OrigParamType = ParamTypes[ParamIdx];
3312 QualType ParamType = OrigParamType;
3313
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003315 = dyn_cast<PackExpansionType>(ParamType);
3316 if (!ParamExpansion) {
3317 // Simple case: matching a function parameter to a function argument.
3318 if (ArgIdx >= CheckArgs)
3319 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003320
Douglas Gregor7825bf32011-01-06 22:09:01 +00003321 Expr *Arg = Args[ArgIdx++];
3322 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003323
Douglas Gregor7825bf32011-01-06 22:09:01 +00003324 unsigned TDF = 0;
3325 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3326 ParamType, ArgType, Arg,
3327 TDF))
3328 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329
Douglas Gregor0c83c812011-10-09 22:06:46 +00003330 // If we have nothing to deduce, we're done.
3331 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3332 continue;
3333
Sebastian Redl43144e72012-01-17 22:49:58 +00003334 // If the argument is an initializer list ...
3335 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3336 // ... then the parameter is an undeduced context, unless the parameter
3337 // type is (reference to cv) std::initializer_list<P'>, in which case
3338 // deduction is done for each element of the initializer list, and the
3339 // result is the deduced type if it's the same for all elements.
3340 QualType X;
3341 // Removing references was already done.
3342 if (!isStdInitializerList(ParamType, &X))
3343 continue;
3344
3345 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3346 if (TemplateDeductionResult Result =
Sebastian Redl19181662012-03-15 21:40:51 +00003347 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3348 ILE->getInit(i),
3349 Info, Deduced, TDF))
Sebastian Redl43144e72012-01-17 22:49:58 +00003350 return Result;
3351 }
3352 // Don't track the argument type, since an initializer list has none.
3353 continue;
3354 }
3355
Douglas Gregore65aacb2011-06-16 16:50:48 +00003356 // Keep track of the argument type and corresponding parameter index,
3357 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003358 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3359 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003360
Douglas Gregor7825bf32011-01-06 22:09:01 +00003361 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003362 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3363 ParamType, ArgType,
3364 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003365 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003366
Douglas Gregor7825bf32011-01-06 22:09:01 +00003367 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369
Douglas Gregor7825bf32011-01-06 22:09:01 +00003370 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371 // For a function parameter pack that occurs at the end of the
3372 // parameter-declaration-list, the type A of each remaining argument of
3373 // the call is compared with the type P of the declarator-id of the
3374 // function parameter pack. Each comparison deduces template arguments
3375 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003376 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003378 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003379 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003380 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
Douglas Gregor7825bf32011-01-06 22:09:01 +00003382 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003383 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3384 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385
Douglas Gregor7825bf32011-01-06 22:09:01 +00003386 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003387 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003388 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389
Douglas Gregore65aacb2011-06-16 16:50:48 +00003390 QualType OrigParamType = ParamPattern;
3391 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003392 Expr *Arg = Args[ArgIdx];
3393 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003394
Douglas Gregor7825bf32011-01-06 22:09:01 +00003395 unsigned TDF = 0;
3396 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3397 ParamType, ArgType, Arg,
3398 TDF)) {
3399 // We can't actually perform any deduction for this argument, so stop
3400 // deduction at this point.
3401 ++ArgIdx;
3402 break;
3403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404
Sebastian Redl43144e72012-01-17 22:49:58 +00003405 // As above, initializer lists need special handling.
3406 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3407 QualType X;
3408 if (!isStdInitializerList(ParamType, &X)) {
3409 ++ArgIdx;
3410 break;
3411 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003412
Sebastian Redl43144e72012-01-17 22:49:58 +00003413 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3414 if (TemplateDeductionResult Result =
3415 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3416 ILE->getInit(i)->getType(),
3417 Info, Deduced, TDF))
3418 return Result;
3419 }
3420 } else {
3421
3422 // Keep track of the argument type and corresponding argument index,
3423 // so we can check for compatibility between the deduced A and A.
3424 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3425 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3426 ArgType));
3427
3428 if (TemplateDeductionResult Result
3429 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3430 ParamType, ArgType, Info,
3431 Deduced, TDF))
3432 return Result;
3433 }
Mike Stump11289f42009-09-09 15:08:12 +00003434
Richard Smith0a80d572014-05-29 01:12:14 +00003435 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
Douglas Gregor7825bf32011-01-06 22:09:01 +00003438 // Build argument packs for each of the parameter packs expanded by this
3439 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003440 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003442
Douglas Gregor7825bf32011-01-06 22:09:01 +00003443 // After we've matching against a parameter pack, we're done.
3444 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003445 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003446
Mike Stump11289f42009-09-09 15:08:12 +00003447 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003448 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003449 Info, &OriginalCallArgs,
3450 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003451}
3452
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003453QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3454 QualType FunctionType) {
3455 if (ArgFunctionType.isNull())
3456 return ArgFunctionType;
3457
3458 const FunctionProtoType *FunctionTypeP =
3459 FunctionType->castAs<FunctionProtoType>();
3460 CallingConv CC = FunctionTypeP->getCallConv();
3461 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3462 const FunctionProtoType *ArgFunctionTypeP =
3463 ArgFunctionType->getAs<FunctionProtoType>();
3464 if (ArgFunctionTypeP->getCallConv() == CC &&
3465 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3466 return ArgFunctionType;
3467
3468 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3469 EI = EI.withNoReturn(NoReturn);
3470 ArgFunctionTypeP =
3471 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3472 return QualType(ArgFunctionTypeP, 0);
3473}
3474
Douglas Gregor9b146582009-07-08 20:55:45 +00003475/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003476/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3477/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003478///
3479/// \param FunctionTemplate the function template for which we are performing
3480/// template argument deduction.
3481///
James Dennett18348b62012-06-22 08:52:37 +00003482/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003483/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003484///
3485/// \param ArgFunctionType the function type that will be used as the
3486/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003487/// function template's function type. This type may be NULL, if there is no
3488/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003489///
3490/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003491/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003492/// template argument deduction.
3493///
3494/// \param Info the argument will be updated to provide additional information
3495/// about template argument deduction.
3496///
3497/// \returns the result of template argument deduction.
3498Sema::TemplateDeductionResult
3499Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003500 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003501 QualType ArgFunctionType,
3502 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003503 TemplateDeductionInfo &Info,
3504 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003505 if (FunctionTemplate->isInvalidDecl())
3506 return TDK_Invalid;
3507
Douglas Gregor9b146582009-07-08 20:55:45 +00003508 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3509 TemplateParameterList *TemplateParams
3510 = FunctionTemplate->getTemplateParameters();
3511 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003512 if (!InOverloadResolution)
3513 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003514
Douglas Gregor9b146582009-07-08 20:55:45 +00003515 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003516 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003517 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003518 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003519 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003520 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003521 if (TemplateDeductionResult Result
3522 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003523 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003524 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003525 &FunctionType, Info))
3526 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003527
3528 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003529 }
3530
Eli Friedman77dcc722012-02-08 03:07:05 +00003531 // Unevaluated SFINAE context.
3532 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003533 SFINAETrap Trap(*this);
3534
John McCallc1f69982010-02-02 02:21:27 +00003535 Deduced.resize(TemplateParams->size());
3536
Richard Smith2a7d4812013-05-04 07:00:32 +00003537 // If the function has a deduced return type, substitute it for a dependent
3538 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003539 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003540 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003541 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003542 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003543 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003544 }
3545
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003546 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003547 unsigned TDF = TDF_TopLevelParameterTypeList;
3548 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003549 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003550 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003551 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003552 FunctionType, ArgFunctionType,
3553 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003554 return Result;
3555 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003556
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003558 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3559 NumExplicitlySpecified,
3560 Specialization, Info))
3561 return Result;
3562
Richard Smith2a7d4812013-05-04 07:00:32 +00003563 // If the function has a deduced return type, deduce it now, so we can check
3564 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003565 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003566 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003567 DeduceReturnType(Specialization, Info.getLocation(), false))
3568 return TDK_MiscellaneousDeductionFailure;
3569
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003570 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003571 // specialization with respect to arguments of compatible pointer to function
3572 // types, template argument deduction fails.
3573 if (!ArgFunctionType.isNull()) {
3574 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3575 Context.getCanonicalType(Specialization->getType()),
3576 Context.getCanonicalType(ArgFunctionType)))
3577 return TDK_MiscellaneousDeductionFailure;
3578 else if(!InOverloadResolution &&
3579 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3580 return TDK_MiscellaneousDeductionFailure;
3581 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003582
3583 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003584}
3585
Faisal Vali850da1a2013-09-29 17:08:32 +00003586/// \brief Given a function declaration (e.g. a generic lambda conversion
3587/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003588/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3589/// to replace 'auto' with and not the actual result type you want
3590/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003591static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003592SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003593 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003594 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003595 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003596 assert(AutoResultType->getContainedAutoType());
3597 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003598 TypeToReplaceAutoWith);
3599 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3600}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003601
3602/// \brief Given a specialized conversion operator of a generic lambda
3603/// create the corresponding specializations of the call operator and
3604/// the static-invoker. If the return type of the call operator is auto,
3605/// deduce its return type and check if that matches the
3606/// return type of the destination function ptr.
3607
3608static inline Sema::TemplateDeductionResult
3609SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3610 CXXConversionDecl *ConversionSpecialized,
3611 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3612 QualType ReturnTypeOfDestFunctionPtr,
3613 TemplateDeductionInfo &TDInfo,
3614 Sema &S) {
3615
3616 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3617 assert(LambdaClass && LambdaClass->isGenericLambda());
3618
3619 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003620 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003621 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3622 CallOpResultType->getContainedAutoType();
3623
3624 FunctionTemplateDecl *CallOpTemplate =
3625 CallOpGeneric->getDescribedFunctionTemplate();
3626
Craig Topperc3ec1492014-05-26 06:22:03 +00003627 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003628 // Use the deduced arguments of the conversion function, to specialize our
3629 // generic lambda's call operator.
3630 if (Sema::TemplateDeductionResult Result
3631 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3632 DeducedArguments,
3633 0, CallOpSpecialized, TDInfo))
3634 return Result;
3635
3636 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003637 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3638 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003639 S.DeduceReturnType(CallOpSpecialized,
3640 CallOpSpecialized->getPointOfInstantiation(),
3641 /*Diagnose*/ true);
3642
3643 // Check to see if the return type of the destination ptr-to-function
3644 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003645 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003646 ReturnTypeOfDestFunctionPtr))
3647 return Sema::TDK_NonDeducedMismatch;
3648 // Since we have succeeded in matching the source and destination
3649 // ptr-to-functions (now including return type), and have successfully
3650 // specialized our corresponding call operator, we are ready to
3651 // specialize the static invoker with the deduced arguments of our
3652 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003653 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003654 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3655 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3656
3657 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result
3658 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3659 InvokerSpecialized, TDInfo);
3660 assert(Result == Sema::TDK_Success &&
3661 "If the call operator succeeded so should the invoker!");
3662 // Set the result type to match the corresponding call operator
3663 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003664 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3665 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003666 // Be sure to get the type to replace 'auto' with and not
3667 // the full result type of the call op specialization
3668 // to substitute into the 'auto' of the invoker and conversion
3669 // function.
3670 // For e.g.
3671 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3672 // We don't want to subst 'int*' into 'auto' to get int**.
3673
Alp Toker314cc812014-01-25 16:55:45 +00003674 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3675 ->getContainedAutoType()
3676 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003677 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3678 TypeToReplaceAutoWith, S);
3679 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3680 TypeToReplaceAutoWith, S);
3681 }
3682
3683 // Ensure that static invoker doesn't have a const qualifier.
3684 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3685 // do not use the CallOperator's TypeSourceInfo which allows
3686 // the const qualifier to leak through.
3687 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3688 getType().getTypePtr()->castAs<FunctionProtoType>();
3689 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3690 EPI.TypeQuals = 0;
3691 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003692 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003693 return Sema::TDK_Success;
3694}
Douglas Gregor05155d82009-08-21 23:19:43 +00003695/// \brief Deduce template arguments for a templated conversion
3696/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3697/// conversion function template specialization.
3698Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003699Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003700 QualType ToType,
3701 CXXConversionDecl *&Specialization,
3702 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003703 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003704 return TDK_Invalid;
3705
Faisal Vali2b3a3012013-10-24 23:40:02 +00003706 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003707 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3708
Faisal Vali2b3a3012013-10-24 23:40:02 +00003709 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003710
3711 // Canonicalize the types for deduction.
3712 QualType P = Context.getCanonicalType(FromType);
3713 QualType A = Context.getCanonicalType(ToType);
3714
Douglas Gregord99609a2011-03-06 09:03:20 +00003715 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003716 // If P is a reference type, the type referred to by P is used for
3717 // type deduction.
3718 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3719 P = PRef->getPointeeType();
3720
Douglas Gregord99609a2011-03-06 09:03:20 +00003721 // C++0x [temp.deduct.conv]p4:
3722 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003723 // for type deduction.
3724 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003725 A = ARef->getPointeeType().getUnqualifiedType();
3726 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003727 //
Mike Stump11289f42009-09-09 15:08:12 +00003728 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003729 else {
3730 assert(!A->isReferenceType() && "Reference types were handled above");
3731
3732 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003733 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003734 // of P for type deduction; otherwise,
3735 if (P->isArrayType())
3736 P = Context.getArrayDecayedType(P);
3737 // - If P is a function type, the pointer type produced by the
3738 // function-to-pointer standard conversion (4.3) is used in
3739 // place of P for type deduction; otherwise,
3740 else if (P->isFunctionType())
3741 P = Context.getPointerType(P);
3742 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003743 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003744 else
3745 P = P.getUnqualifiedType();
3746
Douglas Gregord99609a2011-03-06 09:03:20 +00003747 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003748 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003749 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003750 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003751 A = A.getUnqualifiedType();
3752 }
3753
Eli Friedman77dcc722012-02-08 03:07:05 +00003754 // Unevaluated SFINAE context.
3755 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003756 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003757
3758 // C++ [temp.deduct.conv]p1:
3759 // Template argument deduction is done by comparing the return
3760 // type of the template conversion function (call it P) with the
3761 // type that is required as the result of the conversion (call it
3762 // A) as described in 14.8.2.4.
3763 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003764 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003765 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003766 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003767
3768 // C++0x [temp.deduct.conv]p4:
3769 // In general, the deduction process attempts to find template
3770 // argument values that will make the deduced A identical to
3771 // A. However, there are two cases that allow a difference:
3772 unsigned TDF = 0;
3773 // - If the original A is a reference type, A can be more
3774 // cv-qualified than the deduced A (i.e., the type referred to
3775 // by the reference)
3776 if (ToType->isReferenceType())
3777 TDF |= TDF_ParamWithReferenceType;
3778 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003779 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003780 // conversion.
3781 //
3782 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3783 // both P and A are pointers or member pointers. In this case, we
3784 // just ignore cv-qualifiers completely).
3785 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003786 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003787 TDF |= TDF_IgnoreQualifiers;
3788 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003789 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3790 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003791 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003792
3793 // Create an Instantiation Scope for finalizing the operator.
3794 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003795 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003796 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003797 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003798 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3799 ConversionSpecialized, Info);
3800 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3801
3802 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003803 // to a ptr-to-function, use the deduced arguments from the conversion
3804 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003805 // e.g., int (*fp)(int) = [](auto a) { return a; };
3806 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3807
3808 // Get the return type of the destination ptr-to-function we are converting
3809 // to. This is necessary for matching the lambda call operator's return
3810 // type to that of the destination ptr-to-function's return type.
3811 assert(A->isPointerType() &&
3812 "Can only convert from lambda to ptr-to-function");
3813 const FunctionType *ToFunType =
3814 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003815 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3816
Faisal Vali2b3a3012013-10-24 23:40:02 +00003817 // Create the corresponding specializations of the call operator and
3818 // the static-invoker; and if the return type is auto,
3819 // deduce the return type and check if it matches the
3820 // DestFunctionPtrReturnType.
3821 // For instance:
3822 // auto L = [](auto a) { return f(a); };
3823 // int (*fp)(int) = L;
3824 // char (*fp2)(int) = L; <-- Not OK.
3825
3826 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3827 Specialization, Deduced, DestFunctionPtrReturnType,
3828 Info, *this);
3829 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003830 return Result;
3831}
3832
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003833/// \brief Deduce template arguments for a function template when there is
3834/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3835///
3836/// \param FunctionTemplate the function template for which we are performing
3837/// template argument deduction.
3838///
James Dennett18348b62012-06-22 08:52:37 +00003839/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003840/// arguments.
3841///
3842/// \param Specialization if template argument deduction was successful,
3843/// this will be set to the function template specialization produced by
3844/// template argument deduction.
3845///
3846/// \param Info the argument will be updated to provide additional information
3847/// about template argument deduction.
3848///
3849/// \returns the result of template argument deduction.
3850Sema::TemplateDeductionResult
3851Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003852 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003853 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003854 TemplateDeductionInfo &Info,
3855 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003856 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003857 QualType(), Specialization, Info,
3858 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003859}
3860
Richard Smith30482bc2011-02-20 03:19:35 +00003861namespace {
3862 /// Substitute the 'auto' type specifier within a type for a given replacement
3863 /// type.
3864 class SubstituteAutoTransform :
3865 public TreeTransform<SubstituteAutoTransform> {
3866 QualType Replacement;
3867 public:
Nico Weberc153d242014-07-28 00:02:09 +00003868 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3869 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3870 Replacement(Replacement) {}
3871
Richard Smith30482bc2011-02-20 03:19:35 +00003872 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3873 // If we're building the type pattern to deduce against, don't wrap the
3874 // substituted type in an AutoType. Certain template deduction rules
3875 // apply only when a template type parameter appears directly (and not if
3876 // the parameter is found through desugaring). For instance:
3877 // auto &&lref = lvalue;
3878 // must transform into "rvalue reference to T" not "rvalue reference to
3879 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003880 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003881 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003882 TemplateTypeParmTypeLoc NewTL =
3883 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003884 NewTL.setNameLoc(TL.getNameLoc());
3885 return Result;
3886 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003887 bool Dependent =
3888 !Replacement.isNull() && Replacement->isDependentType();
3889 QualType Result =
3890 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3891 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003892 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003893 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3894 NewTL.setNameLoc(TL.getNameLoc());
3895 return Result;
3896 }
3897 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003898
3899 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3900 // Lambdas never need to be transformed.
3901 return E;
3902 }
Richard Smith061f1e22013-04-30 21:23:01 +00003903
Richard Smith2a7d4812013-05-04 07:00:32 +00003904 QualType Apply(TypeLoc TL) {
3905 // Create some scratch storage for the transformed type locations.
3906 // FIXME: We're just going to throw this information away. Don't build it.
3907 TypeLocBuilder TLB;
3908 TLB.reserve(TL.getFullDataSize());
3909 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003910 }
Richard Smith30482bc2011-02-20 03:19:35 +00003911 };
3912}
3913
Richard Smith2a7d4812013-05-04 07:00:32 +00003914Sema::DeduceAutoResult
3915Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3916 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3917}
3918
Richard Smith061f1e22013-04-30 21:23:01 +00003919/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003920///
3921/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003922/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003923/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003924/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003925Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003926Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003927 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003928 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3929 if (NonPlaceholder.isInvalid())
3930 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003931 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003932 }
3933
Richard Smith2a7d4812013-05-04 07:00:32 +00003934 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003935 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003936 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003937 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003938 }
3939
Richard Smith74aeef52013-04-26 16:15:35 +00003940 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3941 // Since 'decltype(auto)' can only occur at the top of the type, we
3942 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003943 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003944 if (AT->isDecltypeAuto()) {
3945 if (isa<InitListExpr>(Init)) {
3946 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3947 return DAR_FailedAlreadyDiagnosed;
3948 }
3949
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003950 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
Richard Smith74aeef52013-04-26 16:15:35 +00003951 // FIXME: Support a non-canonical deduced type for 'auto'.
3952 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003953 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003954 if (Result.isNull())
3955 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003956 return DAR_Succeeded;
3957 }
3958 }
3959
Richard Smith30482bc2011-02-20 03:19:35 +00003960 SourceLocation Loc = Init->getExprLoc();
3961
3962 LocalInstantiationScope InstScope(*this);
3963
3964 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00003965 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00003966 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
3967 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00003968 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
3969 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00003970 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
3971 Loc);
3972
Richard Smith061f1e22013-04-30 21:23:01 +00003973 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
3974 assert(!FuncParam.isNull() &&
3975 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00003976
3977 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003978 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00003979 Deduced.resize(1);
3980 QualType InitType = Init->getType();
3981 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00003982
Craig Toppere6706e42012-09-19 02:26:47 +00003983 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00003984
Richard Smith74801c82012-07-08 04:13:07 +00003985 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00003986 if (InitList) {
3987 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00003988 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003989 TemplArg,
3990 InitList->getInit(i),
3991 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00003992 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00003993 }
3994 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003995 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
3996 FuncParam, InitType, Init,
3997 TDF))
3998 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00003999
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004000 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4001 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004002 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004003 }
Richard Smith30482bc2011-02-20 03:19:35 +00004004
Eli Friedmane4310952012-11-06 23:56:42 +00004005 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004006 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004007
Eli Friedmane4310952012-11-06 23:56:42 +00004008 QualType DeducedType = Deduced[0].getAsType();
4009
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004010 if (InitList) {
4011 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4012 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004013 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004014 }
4015
Richard Smith061f1e22013-04-30 21:23:01 +00004016 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004017 if (Result.isNull())
4018 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004019
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004020 // Check that the deduced argument type is compatible with the original
4021 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004022 if (!InitList && !Result.isNull() &&
4023 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004024 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004025 Result)) {
4026 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004027 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004028 }
4029
Sebastian Redl09edce02012-01-23 22:09:39 +00004030 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004031}
4032
Faisal Vali2b391ab2013-09-26 19:54:12 +00004033QualType Sema::SubstAutoType(QualType TypeWithAuto,
4034 QualType TypeToReplaceAuto) {
4035 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4036 TransformType(TypeWithAuto);
4037}
4038
4039TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4040 QualType TypeToReplaceAuto) {
4041 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4042 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004043}
4044
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004045void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4046 if (isa<InitListExpr>(Init))
4047 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004048 VDecl->isInitCapture()
4049 ? diag::err_init_capture_deduction_failure_from_init_list
4050 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004051 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4052 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004053 Diag(VDecl->getLocation(),
4054 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4055 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004056 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4057 << Init->getSourceRange();
4058}
4059
Richard Smith2a7d4812013-05-04 07:00:32 +00004060bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4061 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004062 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004063
4064 if (FD->getTemplateInstantiationPattern())
4065 InstantiateFunctionDefinition(Loc, FD);
4066
Alp Toker314cc812014-01-25 16:55:45 +00004067 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004068 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4069 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4070 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4071 }
4072
4073 return StillUndeduced;
4074}
4075
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004076static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004077MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004078 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004079 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004080 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
4082/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004083static void
4084AddImplicitObjectParameterType(ASTContext &Context,
4085 CXXMethodDecl *Method,
4086 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004087 // C++11 [temp.func.order]p3:
4088 // [...] The new parameter is of type "reference to cv A," where cv are
4089 // the cv-qualifiers of the function template (if any) and A is
4090 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004091 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004092 // The standard doesn't say explicitly, but we pick the appropriate kind of
4093 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004094 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4095 ArgTy = Context.getQualifiedType(ArgTy,
4096 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004097 if (Method->getRefQualifier() == RQ_RValue)
4098 ArgTy = Context.getRValueReferenceType(ArgTy);
4099 else
4100 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004101 ArgTypes.push_back(ArgTy);
4102}
4103
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004104/// \brief Determine whether the function template \p FT1 is at least as
4105/// specialized as \p FT2.
4106static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004107 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004108 FunctionTemplateDecl *FT1,
4109 FunctionTemplateDecl *FT2,
4110 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004111 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004112 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004114 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4115 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004117 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4118 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004119 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004120 Deduced.resize(TemplateParams->size());
4121
4122 // C++0x [temp.deduct.partial]p3:
4123 // The types used to determine the ordering depend on the context in which
4124 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004125 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004126 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004127 switch (TPOC) {
4128 case TPOC_Call: {
4129 // - In the context of a function call, the function parameter types are
4130 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004131 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4132 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004133
Eli Friedman3b5774a2012-09-19 23:27:04 +00004134 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004135 // [...] If only one of the function templates is a non-static
4136 // member, that function template is considered to have a new
4137 // first parameter inserted in its function parameter list. The
4138 // new parameter is of type "reference to cv A," where cv are
4139 // the cv-qualifiers of the function template (if any) and A is
4140 // the class of which the function template is a member.
4141 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004142 // Note that we interpret this to mean "if one of the function
4143 // templates is a non-static member and the other is a non-member";
4144 // otherwise, the ordering rules for static functions against non-static
4145 // functions don't make any sense.
4146 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004147 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4148 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004149 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004150
Richard Smithe5b52202013-09-11 00:52:39 +00004151 unsigned NumComparedArguments = NumCallArguments1;
4152
4153 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004154 // Compare 'this' from Method1 against first parameter from Method2.
4155 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4156 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004157 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004158 // Compare 'this' from Method2 against first parameter from Method1.
4159 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004160 }
4161
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004162 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004163 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004164 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004165 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166
Douglas Gregorb837ea42011-01-11 17:34:58 +00004167 // C++ [temp.func.order]p5:
4168 // The presence of unused ellipsis and default arguments has no effect on
4169 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004170 if (Args1.size() > NumComparedArguments)
4171 Args1.resize(NumComparedArguments);
4172 if (Args2.size() > NumComparedArguments)
4173 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004174 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4175 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004176 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004177 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004179 break;
4180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004182 case TPOC_Conversion:
4183 // - In the context of a call to a conversion operator, the return types
4184 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004185 if (DeduceTemplateArgumentsByTypeMatch(
4186 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4187 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004188 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004189 return false;
4190 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004192 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004193 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004194 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004195 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4196 FD2->getType(), FD1->getType(),
4197 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004198 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004199 return false;
4200 break;
4201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004203 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204 // In most cases, all template parameters must have values in order for
4205 // deduction to succeed, but for partial ordering purposes a template
4206 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004207 // types being used for partial ordering. [ Note: a template parameter used
4208 // in a non-deduced context is considered used. -end note]
4209 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4210 for (; ArgIdx != NumArgs; ++ArgIdx)
4211 if (Deduced[ArgIdx].isNull())
4212 break;
4213
4214 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004216 // as FT2.
4217 return true;
4218 }
4219
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004220 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004221 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004222 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004223 case TPOC_Call:
4224 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4225 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004226 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004227 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004228 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004230 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004231 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4232 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004233 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004235 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004236 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004237 TemplateParams->getDepth(),
4238 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004239 break;
4240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004242 for (; ArgIdx != NumArgs; ++ArgIdx)
4243 // If this argument had no value deduced but was used in one of the types
4244 // used for partial ordering, then deduction fails.
4245 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4246 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004248 return true;
4249}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250
Douglas Gregorcef1a032011-01-16 16:03:23 +00004251/// \brief Determine whether this a function template whose parameter-type-list
4252/// ends with a function parameter pack.
4253static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4254 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4255 unsigned NumParams = Function->getNumParams();
4256 if (NumParams == 0)
4257 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregorcef1a032011-01-16 16:03:23 +00004259 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4260 if (!Last->isParameterPack())
4261 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Douglas Gregorcef1a032011-01-16 16:03:23 +00004263 // Make sure that no previous parameter is a parameter pack.
4264 while (--NumParams > 0) {
4265 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4266 return false;
4267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregorcef1a032011-01-16 16:03:23 +00004269 return true;
4270}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
Douglas Gregorbe999392009-09-15 16:23:51 +00004272/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004273/// to the rules of function template partial ordering (C++ [temp.func.order]).
4274///
4275/// \param FT1 the first function template
4276///
4277/// \param FT2 the second function template
4278///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004279/// \param TPOC the context in which we are performing partial ordering of
4280/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004281///
Richard Smithe5b52202013-09-11 00:52:39 +00004282/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4283/// only when \c TPOC is \c TPOC_Call.
4284///
4285/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4286/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004287///
Douglas Gregorbe999392009-09-15 16:23:51 +00004288/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004289/// template is more specialized, returns NULL.
4290FunctionTemplateDecl *
4291Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4292 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004293 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004294 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004295 unsigned NumCallArguments1,
4296 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004298 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004300 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004302 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004303 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004305 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004306 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004307
Douglas Gregorcef1a032011-01-16 16:03:23 +00004308 // FIXME: This mimics what GCC implements, but doesn't match up with the
4309 // proposed resolution for core issue 692. This area needs to be sorted out,
4310 // but for now we attempt to maintain compatibility.
4311 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4312 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4313 if (Variadic1 != Variadic2)
4314 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
Craig Topperc3ec1492014-05-26 06:22:03 +00004316 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004317}
Douglas Gregor9b146582009-07-08 20:55:45 +00004318
Douglas Gregor450f00842009-09-25 18:43:00 +00004319/// \brief Determine if the two templates are equivalent.
4320static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4321 if (T1 == T2)
4322 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregor450f00842009-09-25 18:43:00 +00004324 if (!T1 || !T2)
4325 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor450f00842009-09-25 18:43:00 +00004327 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4328}
4329
4330/// \brief Retrieve the most specialized of the given function template
4331/// specializations.
4332///
John McCall58cc69d2010-01-27 01:50:18 +00004333/// \param SpecBegin the start iterator of the function template
4334/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004335///
John McCall58cc69d2010-01-27 01:50:18 +00004336/// \param SpecEnd the end iterator of the function template
4337/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004338///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004340/// diagnostic should occur.
4341///
4342/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4343/// no matching candidates.
4344///
4345/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4346/// occurs.
4347///
4348/// \param CandidateDiag partial diagnostic used for each function template
4349/// specialization that is a candidate in the ambiguous ordering. One parameter
4350/// in this diagnostic should be unbound, which will correspond to the string
4351/// describing the template arguments for the function template specialization.
4352///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004354/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004355UnresolvedSetIterator Sema::getMostSpecialized(
4356 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4357 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004358 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4359 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4360 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004361 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004362 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004363 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004364 FailedCandidates.NoteCandidates(*this, Loc);
4365 }
John McCall58cc69d2010-01-27 01:50:18 +00004366 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
4369 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004370 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Douglas Gregor450f00842009-09-25 18:43:00 +00004372 // Find the function template that is better than all of the templates it
4373 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004374 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004376 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004377 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004378 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4379 FunctionTemplateDecl *Challenger
4380 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004381 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004382 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004383 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004384 Challenger)) {
4385 Best = I;
4386 BestTemplate = Challenger;
4387 }
4388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
Douglas Gregor450f00842009-09-25 18:43:00 +00004390 // Make sure that the "best" function template is more specialized than all
4391 // of the others.
4392 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004393 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4394 FunctionTemplateDecl *Challenger
4395 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004396 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004398 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004399 BestTemplate)) {
4400 Ambiguous = true;
4401 break;
4402 }
4403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregor450f00842009-09-25 18:43:00 +00004405 if (!Ambiguous) {
4406 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004407 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Douglas Gregor450f00842009-09-25 18:43:00 +00004410 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004411 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004412 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Richard Smithb875c432013-05-04 01:51:08 +00004414 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004415 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4416 PartialDiagnostic PD = CandidateDiag;
4417 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004418 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004419 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004420 if (!TargetType.isNull())
4421 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4422 TargetType);
4423 Diag((*I)->getLocation(), PD);
4424 }
Richard Smithb875c432013-05-04 01:51:08 +00004425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
John McCall58cc69d2010-01-27 01:50:18 +00004427 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004428}
4429
Douglas Gregorbe999392009-09-15 16:23:51 +00004430/// \brief Returns the more specialized class template partial specialization
4431/// according to the rules of partial ordering of class template partial
4432/// specializations (C++ [temp.class.order]).
4433///
4434/// \param PS1 the first class template partial specialization
4435///
4436/// \param PS2 the second class template partial specialization
4437///
4438/// \returns the more specialized class template partial specialization. If
4439/// neither partial specialization is more specialized, returns NULL.
4440ClassTemplatePartialSpecializationDecl *
4441Sema::getMoreSpecializedPartialSpecialization(
4442 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004443 ClassTemplatePartialSpecializationDecl *PS2,
4444 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004445 // C++ [temp.class.order]p1:
4446 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447 // specialized as the second if, given the following rewrite to two
4448 // function templates, the first function template is at least as
4449 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004450 // templates (14.6.6.2):
4451 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452 // first partial specialization and has a single function parameter
4453 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004454 // arguments of the first partial specialization, and
4455 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456 // second partial specialization and has a single function parameter
4457 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004458 // arguments of the second partial specialization.
4459 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004460 // Rather than synthesize function templates, we merely perform the
4461 // equivalent partial ordering by performing deduction directly on
4462 // the template arguments of the class template partial
4463 // specializations. This computation is slightly simpler than the
4464 // general problem of function template partial ordering, because
4465 // class template partial specializations are more constrained. We
4466 // know that every template parameter is deducible from the class
4467 // template partial specialization's template arguments, for
4468 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004469 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004470 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004471
4472 QualType PT1 = PS1->getInjectedSpecializationType();
4473 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474
Douglas Gregorbe999392009-09-15 16:23:51 +00004475 // Determine whether PS1 is at least as specialized as PS2
4476 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004477 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4478 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004479 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004480 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004481 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004482 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004483 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004484 Better1 = !::FinishTemplateArgumentDeduction(
4485 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4486 }
4487
4488 // Determine whether PS2 is at least as specialized as PS1
4489 Deduced.clear();
4490 Deduced.resize(PS1->getTemplateParameters()->size());
4491 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4492 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004493 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004494 if (Better2) {
4495 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4496 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004497 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004498 Better2 = !::FinishTemplateArgumentDeduction(
4499 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4500 }
4501
4502 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004503 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004504
4505 return Better1 ? PS1 : PS2;
4506}
4507
Larisse Voufo30616382013-08-23 22:21:36 +00004508/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4509/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4510/// VarTemplate(Partial)SpecializationDecl with a new data
4511/// structure Template(Partial)SpecializationDecl, and
4512/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004513VarTemplatePartialSpecializationDecl *
4514Sema::getMoreSpecializedPartialSpecialization(
4515 VarTemplatePartialSpecializationDecl *PS1,
4516 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4517 SmallVector<DeducedTemplateArgument, 4> Deduced;
4518 TemplateDeductionInfo Info(Loc);
4519
Richard Smithf04fd0b2013-12-12 23:14:16 +00004520 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004521 "the partial specializations being compared should specialize"
4522 " the same template.");
4523 TemplateName Name(PS1->getSpecializedTemplate());
4524 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4525 QualType PT1 = Context.getTemplateSpecializationType(
4526 CanonTemplate, PS1->getTemplateArgs().data(),
4527 PS1->getTemplateArgs().size());
4528 QualType PT2 = Context.getTemplateSpecializationType(
4529 CanonTemplate, PS2->getTemplateArgs().data(),
4530 PS2->getTemplateArgs().size());
4531
4532 // Determine whether PS1 is at least as specialized as PS2
4533 Deduced.resize(PS2->getTemplateParameters()->size());
4534 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4535 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004536 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004537 if (Better1) {
4538 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4539 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004540 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4542 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004543 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004544 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Douglas Gregorbe999392009-09-15 16:23:51 +00004546 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004547 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004548 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004549 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4550 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004551 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004552 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004553 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004554 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004555 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4557 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004558 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004560
Douglas Gregorbe999392009-09-15 16:23:51 +00004561 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004562 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563
Douglas Gregorbe999392009-09-15 16:23:51 +00004564 return Better1? PS1 : PS2;
4565}
4566
Mike Stump11289f42009-09-09 15:08:12 +00004567static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004568MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004569 const TemplateArgument &TemplateArg,
4570 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004571 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004572 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004573
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004574/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004575/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004576static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004577MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004578 const Expr *E,
4579 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004580 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004581 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004582 // We can deduce from a pack expansion.
4583 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4584 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Richard Smith34349002012-07-09 03:07:20 +00004586 // Skip through any implicit casts we added while type-checking, and any
4587 // substitutions performed by template alias expansion.
4588 while (1) {
4589 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4590 E = ICE->getSubExpr();
4591 else if (const SubstNonTypeTemplateParmExpr *Subst =
4592 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4593 E = Subst->getReplacement();
4594 else
4595 break;
4596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
4598 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004599 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004600 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004601 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004602 return;
4603
Mike Stump11289f42009-09-09 15:08:12 +00004604 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004605 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4606 if (!NTTP)
4607 return;
4608
Douglas Gregor21610382009-10-29 00:04:11 +00004609 if (NTTP->getDepth() == Depth)
4610 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004611}
4612
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004613/// \brief Mark the template parameters that are used by the given
4614/// nested name specifier.
4615static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004616MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004617 NestedNameSpecifier *NNS,
4618 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004619 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004620 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004621 if (!NNS)
4622 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004624 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004625 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004626 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004627 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004628}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004630/// \brief Mark the template parameters that are used by the given
4631/// template name.
4632static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004633MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004634 TemplateName Name,
4635 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004636 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004637 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004638 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4639 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004640 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4641 if (TTP->getDepth() == Depth)
4642 Used[TTP->getIndex()] = true;
4643 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004644 return;
4645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004647 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004648 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004649 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004650 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004651 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004652 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004653}
4654
4655/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004656/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004657static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004658MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004659 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004660 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004661 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004662 if (T.isNull())
4663 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664
Douglas Gregor91772d12009-06-13 00:26:55 +00004665 // Non-dependent types have nothing deducible
4666 if (!T->isDependentType())
4667 return;
4668
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004669 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004670 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004671 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004672 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004673 cast<PointerType>(T)->getPointeeType(),
4674 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004675 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004676 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004677 break;
4678
4679 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004680 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004681 cast<BlockPointerType>(T)->getPointeeType(),
4682 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004683 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004684 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004685 break;
4686
4687 case Type::LValueReference:
4688 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004689 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004690 cast<ReferenceType>(T)->getPointeeType(),
4691 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004692 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004693 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004694 break;
4695
4696 case Type::MemberPointer: {
4697 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004698 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004699 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004700 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004701 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004702 break;
4703 }
4704
4705 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004706 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004707 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004708 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004709 // Fall through to check the element type
4710
4711 case Type::ConstantArray:
4712 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004713 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004714 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004715 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004716 break;
4717
4718 case Type::Vector:
4719 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004720 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004721 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004722 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004723 break;
4724
Douglas Gregor758a8692009-06-17 21:51:59 +00004725 case Type::DependentSizedExtVector: {
4726 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004727 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004728 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004729 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004730 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004731 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004732 break;
4733 }
4734
Douglas Gregor91772d12009-06-13 00:26:55 +00004735 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004736 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004737 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4738 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004739 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4740 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004741 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004742 break;
4743 }
4744
Douglas Gregor21610382009-10-29 00:04:11 +00004745 case Type::TemplateTypeParm: {
4746 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4747 if (TTP->getDepth() == Depth)
4748 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004749 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004750 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004751
Douglas Gregorfb322d82011-01-14 05:11:40 +00004752 case Type::SubstTemplateTypeParmPack: {
4753 const SubstTemplateTypeParmPackType *Subst
4754 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004755 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004756 QualType(Subst->getReplacedParameter(), 0),
4757 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004758 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004759 OnlyDeduced, Depth, Used);
4760 break;
4761 }
4762
John McCall2408e322010-04-27 00:57:59 +00004763 case Type::InjectedClassName:
4764 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4765 // fall through
4766
Douglas Gregor91772d12009-06-13 00:26:55 +00004767 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004768 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004769 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004770 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004771 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
Douglas Gregord0ad2942010-12-23 01:24:45 +00004773 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004774 // If the template argument list of P contains a pack expansion that is
4775 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004776 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004778 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4779 break;
4780
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004781 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004782 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004783 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004784 break;
4785 }
4786
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004787 case Type::Complex:
4788 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004789 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004790 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004791 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004792 break;
4793
Eli Friedman0dfb8892011-10-06 23:00:33 +00004794 case Type::Atomic:
4795 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004796 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004797 cast<AtomicType>(T)->getValueType(),
4798 OnlyDeduced, Depth, Used);
4799 break;
4800
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004801 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004802 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004803 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004804 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004805 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806 break;
4807
John McCallc392f372010-06-11 00:33:02 +00004808 case Type::DependentTemplateSpecialization: {
4809 const DependentTemplateSpecializationType *Spec
4810 = cast<DependentTemplateSpecializationType>(T);
4811 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004812 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004813 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814
Douglas Gregord0ad2942010-12-23 01:24:45 +00004815 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816 // If the template argument list of P contains a pack expansion that is not
4817 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004818 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004819 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004820 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4821 break;
4822
John McCallc392f372010-06-11 00:33:02 +00004823 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004824 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004825 Used);
4826 break;
4827 }
4828
John McCallbd8d9bd2010-03-01 23:49:17 +00004829 case Type::TypeOf:
4830 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004832 cast<TypeOfType>(T)->getUnderlyingType(),
4833 OnlyDeduced, Depth, Used);
4834 break;
4835
4836 case Type::TypeOfExpr:
4837 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004838 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004839 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4840 OnlyDeduced, Depth, Used);
4841 break;
4842
4843 case Type::Decltype:
4844 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004845 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004846 cast<DecltypeType>(T)->getUnderlyingExpr(),
4847 OnlyDeduced, Depth, Used);
4848 break;
4849
Alexis Hunte852b102011-05-24 22:41:36 +00004850 case Type::UnaryTransform:
4851 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004852 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004853 cast<UnaryTransformType>(T)->getUnderlyingType(),
4854 OnlyDeduced, Depth, Used);
4855 break;
4856
Douglas Gregord2fa7662010-12-20 02:24:11 +00004857 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004858 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004859 cast<PackExpansionType>(T)->getPattern(),
4860 OnlyDeduced, Depth, Used);
4861 break;
4862
Richard Smith30482bc2011-02-20 03:19:35 +00004863 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004864 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004865 cast<AutoType>(T)->getDeducedType(),
4866 OnlyDeduced, Depth, Used);
4867
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004868 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004869 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004870 case Type::VariableArray:
4871 case Type::FunctionNoProto:
4872 case Type::Record:
4873 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004874 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004875 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004876 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004877 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004878#define TYPE(Class, Base)
4879#define ABSTRACT_TYPE(Class, Base)
4880#define DEPENDENT_TYPE(Class, Base)
4881#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4882#include "clang/AST/TypeNodes.def"
4883 break;
4884 }
4885}
4886
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004887/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004888/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004889static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004890MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004891 const TemplateArgument &TemplateArg,
4892 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004893 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004894 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004895 switch (TemplateArg.getKind()) {
4896 case TemplateArgument::Null:
4897 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004898 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004899 break;
Mike Stump11289f42009-09-09 15:08:12 +00004900
Eli Friedmanb826a002012-09-26 02:36:12 +00004901 case TemplateArgument::NullPtr:
4902 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4903 Depth, Used);
4904 break;
4905
Douglas Gregor91772d12009-06-13 00:26:55 +00004906 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004907 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004908 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004909 break;
4910
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004911 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004912 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004913 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004915 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004916 break;
4917
4918 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004919 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004920 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004921 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Anders Carlssonbc343912009-06-15 17:04:53 +00004923 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00004924 for (const auto &P : TemplateArg.pack_elements())
4925 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00004926 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00004927 }
4928}
4929
James Dennett41725122012-06-22 10:16:05 +00004930/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00004931/// template argument list.
4932///
4933/// \param TemplateArgs the template argument list from which template
4934/// parameters will be deduced.
4935///
James Dennett41725122012-06-22 10:16:05 +00004936/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00004937/// to indicate when the corresponding template parameter will be
4938/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00004939void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004940Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00004941 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004942 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00004943 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944 // If the template argument list of P contains a pack expansion that is not
4945 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004946 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004947 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004948 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
4949 return;
4950
Douglas Gregor91772d12009-06-13 00:26:55 +00004951 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004952 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004953 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004954}
Douglas Gregorce23bae2009-09-18 23:21:38 +00004955
4956/// \brief Marks all of the template parameters that will be deduced by a
4957/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00004958void Sema::MarkDeducedTemplateParameters(
4959 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
4960 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00004962 = FunctionTemplate->getTemplateParameters();
4963 Deduced.clear();
4964 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Douglas Gregorce23bae2009-09-18 23:21:38 +00004966 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4967 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004968 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004969 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00004970}
Douglas Gregore65aacb2011-06-16 16:50:48 +00004971
4972bool hasDeducibleTemplateParameters(Sema &S,
4973 FunctionTemplateDecl *FunctionTemplate,
4974 QualType T) {
4975 if (!T->isDependentType())
4976 return false;
4977
4978 TemplateParameterList *TemplateParams
4979 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004980 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004981 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00004982 Deduced);
4983
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004984 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00004985}