blob: ae8157e70a603b38fc3d2de100cab0794d3c837d [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 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000061}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062
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
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000579namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000580/// A scope in which we're performing pack deduction.
581class PackDeductionScope {
582public:
583 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
584 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
585 TemplateDeductionInfo &Info, TemplateArgument Pattern)
586 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
587 // Compute the set of template parameter indices that correspond to
588 // parameter packs expanded by the pack expansion.
589 {
590 llvm::SmallBitVector SawIndices(TemplateParams->size());
591 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
592 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
593 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
594 unsigned Depth, Index;
595 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
596 if (Depth == 0 && !SawIndices[Index]) {
597 SawIndices[Index] = true;
598
599 // Save the deduced template argument for the parameter pack expanded
600 // by this pack expansion, then clear out the deduction.
601 DeducedPack Pack(Index);
602 Pack.Saved = Deduced[Index];
603 Deduced[Index] = TemplateArgument();
604
605 Packs.push_back(Pack);
606 }
607 }
608 }
609 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
610
611 for (auto &Pack : Packs) {
612 if (Info.PendingDeducedPacks.size() > Pack.Index)
613 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
614 else
615 Info.PendingDeducedPacks.resize(Pack.Index + 1);
616 Info.PendingDeducedPacks[Pack.Index] = &Pack;
617
618 if (S.CurrentInstantiationScope) {
619 // If the template argument pack was explicitly specified, add that to
620 // the set of deduced arguments.
621 const TemplateArgument *ExplicitArgs;
622 unsigned NumExplicitArgs;
623 NamedDecl *PartiallySubstitutedPack =
624 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
625 &ExplicitArgs, &NumExplicitArgs);
626 if (PartiallySubstitutedPack &&
627 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
628 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
629 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000630 }
631 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000632
Richard Smith0a80d572014-05-29 01:12:14 +0000633 ~PackDeductionScope() {
634 for (auto &Pack : Packs)
635 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Richard Smith0a80d572014-05-29 01:12:14 +0000638 /// Move to deducing the next element in each pack that is being deduced.
639 void nextPackElement() {
640 // Capture the deduced template arguments for each parameter pack expanded
641 // by this pack expansion, add them to the list of arguments we've deduced
642 // for that pack, then clear out the deduced argument.
643 for (auto &Pack : Packs) {
644 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
645 if (!DeducedArg.isNull()) {
646 Pack.New.push_back(DeducedArg);
647 DeducedArg = DeducedTemplateArgument();
648 }
649 }
650 }
651
652 /// \brief Finish template argument deduction for a set of argument packs,
653 /// producing the argument packs and checking for consistency with prior
654 /// deductions.
655 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
656 // Build argument packs for each of the parameter packs expanded by this
657 // pack expansion.
658 for (auto &Pack : Packs) {
659 // Put back the old value for this pack.
660 Deduced[Pack.Index] = Pack.Saved;
661
662 // Build or find a new value for this pack.
663 DeducedTemplateArgument NewPack;
664 if (HasAnyArguments && Pack.New.empty()) {
665 if (Pack.DeferredDeduction.isNull()) {
666 // We were not able to deduce anything for this parameter pack
667 // (because it only appeared in non-deduced contexts), so just
668 // restore the saved argument pack.
669 continue;
670 }
671
672 NewPack = Pack.DeferredDeduction;
673 Pack.DeferredDeduction = TemplateArgument();
674 } else if (Pack.New.empty()) {
675 // If we deduced an empty argument pack, create it now.
676 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
677 } else {
678 TemplateArgument *ArgumentPack =
679 new (S.Context) TemplateArgument[Pack.New.size()];
680 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
681 NewPack = DeducedTemplateArgument(
682 TemplateArgument(ArgumentPack, Pack.New.size()),
683 Pack.New[0].wasDeducedFromArrayBound());
684 }
685
686 // Pick where we're going to put the merged pack.
687 DeducedTemplateArgument *Loc;
688 if (Pack.Outer) {
689 if (Pack.Outer->DeferredDeduction.isNull()) {
690 // Defer checking this pack until we have a complete pack to compare
691 // it against.
692 Pack.Outer->DeferredDeduction = NewPack;
693 continue;
694 }
695 Loc = &Pack.Outer->DeferredDeduction;
696 } else {
697 Loc = &Deduced[Pack.Index];
698 }
699
700 // Check the new pack matches any previous value.
701 DeducedTemplateArgument OldPack = *Loc;
702 DeducedTemplateArgument Result =
703 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
704
705 // If we deferred a deduction of this pack, check that one now too.
706 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
707 OldPack = Result;
708 NewPack = Pack.DeferredDeduction;
709 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
710 }
711
712 if (Result.isNull()) {
713 Info.Param =
714 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
715 Info.FirstArg = OldPack;
716 Info.SecondArg = NewPack;
717 return Sema::TDK_Inconsistent;
718 }
719
720 *Loc = Result;
721 }
722
723 return Sema::TDK_Success;
724 }
725
726private:
727 Sema &S;
728 TemplateParameterList *TemplateParams;
729 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
730 TemplateDeductionInfo &Info;
731
732 SmallVector<DeducedPack, 2> Packs;
733};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000734} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000735
Douglas Gregor5499af42011-01-05 23:12:31 +0000736/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737/// types to the list of argument types, as in the parameter-type-lists of
738/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000739///
740/// \param S The semantic analysis object within which we are deducing
741///
742/// \param TemplateParams The template parameters that we are deducing
743///
744/// \param Params The list of parameter types
745///
746/// \param NumParams The number of types in \c Params
747///
748/// \param Args The list of argument types
749///
750/// \param NumArgs The number of types in \c Args
751///
752/// \param Info information about the template argument deduction itself
753///
754/// \param Deduced the deduced template arguments
755///
756/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
757/// how template argument deduction is performed.
758///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000759/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000761/// (C++0x [temp.deduct.partial]).
762///
Douglas Gregor5499af42011-01-05 23:12:31 +0000763/// \returns the result of template argument deduction so far. Note that a
764/// "success" result means that template argument deduction has not yet failed,
765/// but it may still fail, later, for other reasons.
766static Sema::TemplateDeductionResult
767DeduceTemplateArguments(Sema &S,
768 TemplateParameterList *TemplateParams,
769 const QualType *Params, unsigned NumParams,
770 const QualType *Args, unsigned NumArgs,
771 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000772 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000773 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000774 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000775 // Fast-path check to see if we have too many/too few arguments.
776 if (NumParams != NumArgs &&
777 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
778 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000779 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
Douglas Gregor5499af42011-01-05 23:12:31 +0000781 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782 // Similarly, if P has a form that contains (T), then each parameter type
783 // Pi of the respective parameter-type- list of P is compared with the
784 // corresponding parameter type Ai of the corresponding parameter-type-list
785 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000786 unsigned ArgIdx = 0, ParamIdx = 0;
787 for (; ParamIdx != NumParams; ++ParamIdx) {
788 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000790 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
791 if (!Expansion) {
792 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793
Douglas Gregor5499af42011-01-05 23:12:31 +0000794 // Make sure we have an argument.
795 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000796 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000798 if (isa<PackExpansionType>(Args[ArgIdx])) {
799 // C++0x [temp.deduct.type]p22:
800 // If the original function parameter associated with A is a function
801 // parameter pack and the function parameter associated with P is not
802 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000803 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor5499af42011-01-05 23:12:31 +0000806 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000807 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
808 Params[ParamIdx], Args[ArgIdx],
809 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000810 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
Douglas Gregor5499af42011-01-05 23:12:31 +0000813 ++ArgIdx;
814 continue;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000817 // C++0x [temp.deduct.type]p5:
818 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000820 // parameter-declaration-clause.
821 if (ParamIdx + 1 < NumParams)
822 return Sema::TDK_Success;
823
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000826 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000828 // comparison deduces template arguments for subsequent positions in the
829 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
Douglas Gregor5499af42011-01-05 23:12:31 +0000831 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000832 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833
Douglas Gregor5499af42011-01-05 23:12:31 +0000834 bool HasAnyArguments = false;
835 for (; ArgIdx < NumArgs; ++ArgIdx) {
836 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor5499af42011-01-05 23:12:31 +0000838 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000840 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
841 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000842 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Richard Smith0a80d572014-05-29 01:12:14 +0000845 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 // Build argument packs for each of the parameter packs expanded by this
849 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000850 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854 // Make sure we don't have any extra arguments.
855 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000856 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 return Sema::TDK_Success;
859}
860
Douglas Gregor1d684c22011-04-28 00:56:09 +0000861/// \brief Determine whether the parameter has qualifiers that are either
862/// inconsistent with or a superset of the argument's qualifiers.
863static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
864 QualType ArgType) {
865 Qualifiers ParamQs = ParamType.getQualifiers();
866 Qualifiers ArgQs = ArgType.getQualifiers();
867
868 if (ParamQs == ArgQs)
869 return false;
870
871 // Mismatched (but not missing) Objective-C GC attributes.
872 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
873 ParamQs.hasObjCGCAttr())
874 return true;
875
876 // Mismatched (but not missing) address spaces.
877 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
878 ParamQs.hasAddressSpace())
879 return true;
880
John McCall31168b02011-06-15 23:02:42 +0000881 // Mismatched (but not missing) Objective-C lifetime qualifiers.
882 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
883 ParamQs.hasObjCLifetime())
884 return true;
885
Douglas Gregor1d684c22011-04-28 00:56:09 +0000886 // CVR qualifier superset.
887 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
888 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
889 == ParamQs.getCVRQualifiers());
890}
891
Douglas Gregor19a41f12013-04-17 08:45:07 +0000892/// \brief Compare types for equality with respect to possibly compatible
893/// function types (noreturn adjustment, implicit calling conventions). If any
894/// of parameter and argument is not a function, just perform type comparison.
895///
896/// \param Param the template parameter type.
897///
898/// \param Arg the argument type.
899bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
900 CanQualType Arg) {
901 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
902 *ArgFunction = Arg->getAs<FunctionType>();
903
904 // Just compare if not functions.
905 if (!ParamFunction || !ArgFunction)
906 return Param == Arg;
907
908 // Noreturn adjustment.
909 QualType AdjustedParam;
910 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
911 return Arg == Context.getCanonicalType(AdjustedParam);
912
913 // FIXME: Compatible calling conventions.
914
915 return Param == Arg;
916}
917
Douglas Gregorcceb9752009-06-26 18:27:22 +0000918/// \brief Deduce the template arguments by comparing the parameter type and
919/// the argument type (C++ [temp.deduct.type]).
920///
Chandler Carruthc1263112010-02-07 21:33:28 +0000921/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000922///
923/// \param TemplateParams the template parameters that we are deducing
924///
925/// \param ParamIn the parameter type
926///
927/// \param ArgIn the argument type
928///
929/// \param Info information about the template argument deduction itself
930///
931/// \param Deduced the deduced template arguments
932///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000933/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000934/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000935///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000936/// \param PartialOrdering Whether we're performing template argument deduction
937/// in the context of partial ordering (C++0x [temp.deduct.partial]).
938///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000939/// \returns the result of template argument deduction so far. Note that a
940/// "success" result means that template argument deduction has not yet failed,
941/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000942static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000943DeduceTemplateArgumentsByTypeMatch(Sema &S,
944 TemplateParameterList *TemplateParams,
945 QualType ParamIn, QualType ArgIn,
946 TemplateDeductionInfo &Info,
947 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
948 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000949 bool PartialOrdering) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000950 // We only want to look at the canonical types, since typedefs and
951 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000952 QualType Param = S.Context.getCanonicalType(ParamIn);
953 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000954
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000955 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000957 if (const PackExpansionType *ArgExpansion
958 = dyn_cast<PackExpansionType>(Arg))
959 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
Douglas Gregorb837ea42011-01-11 17:34:58 +0000961 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000962 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963 // Before the partial ordering is done, certain transformations are
964 // performed on the types used for partial ordering:
965 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000966 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
967 if (ParamRef)
968 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregorb837ea42011-01-11 17:34:58 +0000970 // - If A is a reference type, A is replaced by the type referred to.
971 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
972 if (ArgRef)
973 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
Richard Smithed563c22015-02-20 04:45:22 +0000975 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
976 // C++11 [temp.deduct.partial]p9:
977 // If, for a given type, deduction succeeds in both directions (i.e.,
978 // the types are identical after the transformations above) and both
979 // P and A were reference types [...]:
980 // - if [one type] was an lvalue reference and [the other type] was
981 // not, [the other type] is not considered to be at least as
982 // specialized as [the first type]
983 // - if [one type] is more cv-qualified than [the other type],
984 // [the other type] is not considered to be at least as specialized
985 // as [the first type]
986 // Objective-C ARC adds:
987 // - [one type] has non-trivial lifetime, [the other type] has
988 // __unsafe_unretained lifetime, and the types are otherwise
989 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +0000990 //
Richard Smithed563c22015-02-20 04:45:22 +0000991 // A is "considered to be at least as specialized" as P iff deduction
992 // succeeds, so we model this as a deduction failure. Note that
993 // [the first type] is P and [the other type] is A here; the standard
994 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +0000995 Qualifiers ParamQuals = Param.getQualifiers();
996 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +0000997 if ((ParamRef->isLValueReferenceType() &&
998 !ArgRef->isLValueReferenceType()) ||
999 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1000 (ParamQuals.hasNonTrivialObjCLifetime() &&
1001 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1002 ParamQuals.withoutObjCLifetime() ==
1003 ArgQuals.withoutObjCLifetime())) {
1004 Info.FirstArg = TemplateArgument(ParamIn);
1005 Info.SecondArg = TemplateArgument(ArgIn);
1006 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001007 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
Richard Smithed563c22015-02-20 04:45:22 +00001010 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001011 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 // version of P.
1014 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001016 // version of A.
1017 Arg = Arg.getUnqualifiedType();
1018 } else {
1019 // C++0x [temp.deduct.call]p4 bullet 1:
1020 // - If the original P is a reference type, the deduced A (i.e., the type
1021 // referred to by the reference) can be more cv-qualified than the
1022 // transformed A.
1023 if (TDF & TDF_ParamWithReferenceType) {
1024 Qualifiers Quals;
1025 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1026 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001027 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001028 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Douglas Gregor85f240c2011-01-25 17:19:08 +00001031 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1032 // C++0x [temp.deduct.type]p10:
1033 // If P and A are function types that originated from deduction when
1034 // taking the address of a function template (14.8.2.2) or when deducing
1035 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036 // Ai are parameters of the top-level parameter-type-list of P and A,
1037 // respectively, Pi is adjusted if it is an rvalue reference to a
1038 // cv-unqualified template parameter and Ai is an lvalue reference, in
1039 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001040 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1041 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001042 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001043 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregor85f240c2011-01-25 17:19:08 +00001045 if (const RValueReferenceType *ParamRef
1046 = Param->getAs<RValueReferenceType>()) {
1047 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1048 !ParamRef->getPointeeType().getQualifiers())
1049 if (Arg->isLValueReferenceType())
1050 Param = ParamRef->getPointeeType();
1051 }
1052 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001055 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001056 // A template type argument T, a template template argument TT or a
1057 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001058 // the following forms:
1059 //
1060 // T
1061 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001062 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001063 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001064 // Just skip any attempts to deduce from a placeholder type.
1065 if (Arg->isPlaceholderType())
1066 return Sema::TDK_Success;
1067
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001068 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001069 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregor60454822009-07-22 20:02:25 +00001071 // If the argument type is an array type, move the qualifiers up to the
1072 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001073 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001074 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001075 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001076 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001077 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001078 RecanonicalizeArg = true;
1079 }
1080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001082 // The argument type can not be less qualified than the parameter
1083 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001084 if (!(TDF & TDF_IgnoreQualifiers) &&
1085 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001086 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001087 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001088 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001089 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001090 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001091
1092 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001093 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001094 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001095
Douglas Gregor1d684c22011-04-28 00:56:09 +00001096 // Remove any qualifiers on the parameter from the deduced type.
1097 // We checked the qualifiers for consistency above.
1098 Qualifiers DeducedQs = DeducedType.getQualifiers();
1099 Qualifiers ParamQs = Param.getQualifiers();
1100 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1101 if (ParamQs.hasObjCGCAttr())
1102 DeducedQs.removeObjCGCAttr();
1103 if (ParamQs.hasAddressSpace())
1104 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001105 if (ParamQs.hasObjCLifetime())
1106 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001107
1108 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001109 // If template deduction would produce a lifetime qualifier on a type
1110 // that is not a lifetime type, template argument deduction fails.
1111 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1112 !DeducedType->isDependentType()) {
1113 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1114 Info.FirstArg = TemplateArgument(Param);
1115 Info.SecondArg = TemplateArgument(Arg);
1116 return Sema::TDK_Underqualified;
1117 }
1118
1119 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001120 // If template deduction would produce an argument type with lifetime type
1121 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001122 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001123 DeducedType->isObjCLifetimeType() &&
1124 !DeducedQs.hasObjCLifetime())
1125 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1126
Douglas Gregor1d684c22011-04-28 00:56:09 +00001127 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1128 DeducedQs);
1129
Douglas Gregord6605db2009-07-22 21:30:48 +00001130 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001131 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001133 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001135 Deduced[Index],
1136 NewDeduced);
1137 if (Result.isNull()) {
1138 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1139 Info.FirstArg = Deduced[Index];
1140 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001144 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001146 }
1147
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001148 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001149 Info.FirstArg = TemplateArgument(ParamIn);
1150 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001151
Douglas Gregorfb322d82011-01-14 05:11:40 +00001152 // If the parameter is an already-substituted template parameter
1153 // pack, do nothing: we don't know which of its arguments to look
1154 // at, so we have to wait until all of the parameter packs in this
1155 // expansion have arguments.
1156 if (isa<SubstTemplateTypeParmPackType>(Param))
1157 return Sema::TDK_Success;
1158
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001159 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001160 CanQualType CanParam = S.Context.getCanonicalType(Param);
1161 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001162 if (!(TDF & TDF_IgnoreQualifiers)) {
1163 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001164 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001165 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001166 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001167 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001168 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001169 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001170
1171 // If the parameter type is not dependent, there is nothing to deduce.
1172 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001173 if (!(TDF & TDF_SkipNonDependent)) {
1174 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1175 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1176 Param != Arg;
1177 if (NonDeduced) {
1178 return Sema::TDK_NonDeducedMismatch;
1179 }
1180 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001181 return Sema::TDK_Success;
1182 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001183 } else if (!Param->isDependentType()) {
1184 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1185 ArgUnqualType = CanArg.getUnqualifiedType();
1186 bool Success = (TDF & TDF_InOverloadResolution)?
1187 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1188 ArgUnqualType) :
1189 ParamUnqualType == ArgUnqualType;
1190 if (Success)
1191 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001192 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001193
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001194 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001195 // Non-canonical types cannot appear here.
1196#define NON_CANONICAL_TYPE(Class, Base) \
1197 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1198#define TYPE(Class, Base)
1199#include "clang/AST/TypeNodes.def"
1200
1201 case Type::TemplateTypeParm:
1202 case Type::SubstTemplateTypeParmPack:
1203 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001204
1205 // These types cannot be dependent, so simply check whether the types are
1206 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001207 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001208 case Type::VariableArray:
1209 case Type::Vector:
1210 case Type::FunctionNoProto:
1211 case Type::Record:
1212 case Type::Enum:
1213 case Type::ObjCObject:
1214 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001215 case Type::ObjCObjectPointer: {
1216 if (TDF & TDF_SkipNonDependent)
1217 return Sema::TDK_Success;
1218
1219 if (TDF & TDF_IgnoreQualifiers) {
1220 Param = Param.getUnqualifiedType();
1221 Arg = Arg.getUnqualifiedType();
1222 }
1223
1224 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1225 }
1226
Douglas Gregor39c02722011-06-15 16:02:29 +00001227 // _Complex T [placeholder extension]
1228 case Type::Complex:
1229 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001230 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001231 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001232 ComplexArg->getElementType(),
1233 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001234
1235 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001236
1237 // _Atomic T [extension]
1238 case Type::Atomic:
1239 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001240 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001241 cast<AtomicType>(Param)->getValueType(),
1242 AtomicArg->getValueType(),
1243 Info, Deduced, TDF);
1244
1245 return Sema::TDK_NonDeducedMismatch;
1246
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001247 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001248 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001249 QualType PointeeType;
1250 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1251 PointeeType = PointerArg->getPointeeType();
1252 } else if (const ObjCObjectPointerType *PointerArg
1253 = Arg->getAs<ObjCObjectPointerType>()) {
1254 PointeeType = PointerArg->getPointeeType();
1255 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001256 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregorfc516c92009-06-26 23:27:24 +00001259 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001260 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1261 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001262 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001263 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001266 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001267 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001268 const LValueReferenceType *ReferenceArg =
1269 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001270 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001271 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001273 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001274 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001275 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001276 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001277
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001278 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001279 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001280 const RValueReferenceType *ReferenceArg =
1281 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001282 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001283 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001284
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001285 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1286 cast<RValueReferenceType>(Param)->getPointeeType(),
1287 ReferenceArg->getPointeeType(),
1288 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001291 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001292 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001293 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001294 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001295 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001296 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001297
John McCallf7332682010-08-19 00:20:19 +00001298 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1300 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1301 IncompleteArrayArg->getElementType(),
1302 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001303 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001304
1305 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001306 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001307 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001308 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001309 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001310 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001311
1312 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001313 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001314 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001315 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001316
John McCallf7332682010-08-19 00:20:19 +00001317 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001318 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1319 ConstantArrayParm->getElementType(),
1320 ConstantArrayArg->getElementType(),
1321 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001322 }
1323
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001324 // type [i]
1325 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001326 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001328 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCallf7332682010-08-19 00:20:19 +00001330 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1331
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001332 // Check the element type of the arrays
1333 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001334 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001336 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1337 DependentArrayParm->getElementType(),
1338 ArrayArg->getElementType(),
1339 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001340 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001343 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001344 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1345 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001347
1348 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001349 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001350 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001351 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001352 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001353 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1354 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001356 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001357 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001358 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001359 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001360 if (const DependentSizedArrayType *DependentArrayArg
1361 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001362 if (DependentArrayArg->getSizeExpr())
1363 return DeduceNonTypeTemplateArgument(S, NTTP,
1364 DependentArrayArg->getSizeExpr(),
1365 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001368 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
1371 // type(*)(T)
1372 // T(*)()
1373 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001374 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001375 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001376 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001377 dyn_cast<FunctionProtoType>(Arg);
1378 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001379 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001380
1381 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001382 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001385 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001387 != FunctionProtoArg->getRefQualifier() ||
1388 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001389 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001390
Anders Carlsson2128ec72009-06-08 15:19:08 +00001391 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001392 if (Sema::TemplateDeductionResult Result =
1393 DeduceTemplateArgumentsByTypeMatch(
1394 S, TemplateParams, FunctionProtoParam->getReturnType(),
1395 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001396 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Alp Toker9cacbab2014-01-20 20:26:09 +00001398 return DeduceTemplateArguments(
1399 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1400 FunctionProtoParam->getNumParams(),
1401 FunctionProtoArg->param_type_begin(),
1402 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCalle78aac42010-03-10 03:28:59 +00001405 case Type::InjectedClassName: {
1406 // Treat a template's injected-class-name as if the template
1407 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001408 Param = cast<InjectedClassNameType>(Param)
1409 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001410 assert(isa<TemplateSpecializationType>(Param) &&
1411 "injected class name is not a template specialization type");
1412 // fall through
1413 }
1414
Douglas Gregor705c9002009-06-26 20:57:09 +00001415 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001416 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001417 // TT<T>
1418 // TT<i>
1419 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001420 case Type::TemplateSpecialization: {
1421 const TemplateSpecializationType *SpecParam
1422 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Douglas Gregore81f3e72009-07-07 23:09:34 +00001424 // Try to deduce template arguments from the template-id.
1425 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001426 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001427 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001428
Douglas Gregor42909752009-09-30 22:13:51 +00001429 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001430 // C++ [temp.deduct.call]p3b3:
1431 // If P is a class, and P has the form template-id, then A can be a
1432 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001433 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001434 // class pointed to by the deduced A.
1435 //
1436 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001437 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001438 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001439 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1440 // We cannot inspect base classes as part of deduction when the type
1441 // is incomplete, so either instantiate any templates necessary to
1442 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001443 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001444 return Result;
1445
Douglas Gregore81f3e72009-07-07 23:09:34 +00001446 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001447 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001448 // ToVisit is our stack of records that we still need to visit.
1449 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001450 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001451 ToVisit.push_back(RecordT);
1452 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001453 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1454 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001455 while (!ToVisit.empty()) {
1456 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001457 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001458
Douglas Gregore81f3e72009-07-07 23:09:34 +00001459 // If we have already seen this type, skip it.
David Blaikie82e95a32014-11-19 07:49:47 +00001460 if (!Visited.insert(NextT).second)
Douglas Gregore81f3e72009-07-07 23:09:34 +00001461 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001462
Douglas Gregore81f3e72009-07-07 23:09:34 +00001463 // If this is a base class, try to perform template argument
1464 // deduction from it.
1465 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001466 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001467 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001468 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001469 QualType(NextT, 0), BaseInfo,
1470 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001471
Douglas Gregore81f3e72009-07-07 23:09:34 +00001472 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001473 // note that we had some success. Otherwise, ignore any deductions
1474 // from this base class.
1475 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001476 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001477 DeducedOrig.clear();
1478 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001479 Info.Param = BaseInfo.Param;
1480 Info.FirstArg = BaseInfo.FirstArg;
1481 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001482 }
1483 else
1484 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Douglas Gregore81f3e72009-07-07 23:09:34 +00001487 // Visit base classes
1488 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001489 for (const auto &Base : Next->bases()) {
1490 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001491 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001492 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001493 }
1494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Douglas Gregore81f3e72009-07-07 23:09:34 +00001496 if (Successful)
1497 return Sema::TDK_Success;
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregore81f3e72009-07-07 23:09:34 +00001500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregore81f3e72009-07-07 23:09:34 +00001502 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001503 }
1504
Douglas Gregor637d9982009-06-10 23:47:09 +00001505 // T type::*
1506 // T T::*
1507 // T (type::*)()
1508 // type (T::*)()
1509 // type (type::*)(T)
1510 // type (T::*)(T)
1511 // T (type::*)(T)
1512 // T (T::*)()
1513 // T (T::*)(T)
1514 case Type::MemberPointer: {
1515 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1516 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1517 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001518 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001519
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001520 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001521 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1522 MemPtrParam->getPointeeType(),
1523 MemPtrArg->getPointeeType(),
1524 Info, Deduced,
1525 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001526 return Result;
1527
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001528 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1529 QualType(MemPtrParam->getClass(), 0),
1530 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001531 Info, Deduced,
1532 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001533 }
1534
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001535 // (clang extension)
1536 //
Mike Stump11289f42009-09-09 15:08:12 +00001537 // type(^)(T)
1538 // T(^)()
1539 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001540 case Type::BlockPointer: {
1541 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1542 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Anders Carlssona767eee2009-06-12 16:23:10 +00001544 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001545 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001546
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001547 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1548 BlockPtrParam->getPointeeType(),
1549 BlockPtrArg->getPointeeType(),
1550 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001551 }
1552
Douglas Gregor39c02722011-06-15 16:02:29 +00001553 // (clang extension)
1554 //
1555 // T __attribute__(((ext_vector_type(<integral constant>))))
1556 case Type::ExtVector: {
1557 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1558 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1559 // Make sure that the vectors have the same number of elements.
1560 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1561 return Sema::TDK_NonDeducedMismatch;
1562
1563 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001564 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1565 VectorParam->getElementType(),
1566 VectorArg->getElementType(),
1567 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001568 }
1569
1570 if (const DependentSizedExtVectorType *VectorArg
1571 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1572 // We can't check the number of elements, since the argument has a
1573 // dependent number of elements. This can only occur during partial
1574 // ordering.
1575
1576 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001577 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1578 VectorParam->getElementType(),
1579 VectorArg->getElementType(),
1580 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001581 }
1582
1583 return Sema::TDK_NonDeducedMismatch;
1584 }
1585
1586 // (clang extension)
1587 //
1588 // T __attribute__(((ext_vector_type(N))))
1589 case Type::DependentSizedExtVector: {
1590 const DependentSizedExtVectorType *VectorParam
1591 = cast<DependentSizedExtVectorType>(Param);
1592
1593 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1594 // Perform deduction on the element types.
1595 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001596 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1597 VectorParam->getElementType(),
1598 VectorArg->getElementType(),
1599 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001600 return Result;
1601
1602 // Perform deduction on the vector size, if we can.
1603 NonTypeTemplateParmDecl *NTTP
1604 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1605 if (!NTTP)
1606 return Sema::TDK_Success;
1607
1608 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1609 ArgSize = VectorArg->getNumElements();
1610 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1611 false, Info, Deduced);
1612 }
1613
1614 if (const DependentSizedExtVectorType *VectorArg
1615 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1616 // Perform deduction on the element types.
1617 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001618 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1619 VectorParam->getElementType(),
1620 VectorArg->getElementType(),
1621 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001622 return Result;
1623
1624 // Perform deduction on the vector size, if we can.
1625 NonTypeTemplateParmDecl *NTTP
1626 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1627 if (!NTTP)
1628 return Sema::TDK_Success;
1629
1630 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1631 Info, Deduced);
1632 }
1633
1634 return Sema::TDK_NonDeducedMismatch;
1635 }
1636
Douglas Gregor637d9982009-06-10 23:47:09 +00001637 case Type::TypeOfExpr:
1638 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001639 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001640 case Type::UnresolvedUsing:
1641 case Type::Decltype:
1642 case Type::UnaryTransform:
1643 case Type::Auto:
1644 case Type::DependentTemplateSpecialization:
1645 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001646 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001647 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001648 }
1649
David Blaikiee4d798f2012-01-20 21:50:17 +00001650 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001651}
1652
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001653static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001654DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001655 TemplateParameterList *TemplateParams,
1656 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001657 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001658 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001659 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001660 // If the template argument is a pack expansion, perform template argument
1661 // deduction against the pattern of that expansion. This only occurs during
1662 // partial ordering.
1663 if (Arg.isPackExpansion())
1664 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001666 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001667 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001668 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001669
1670 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001671 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001672 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1673 Param.getAsType(),
1674 Arg.getAsType(),
1675 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001676 Info.FirstArg = Param;
1677 Info.SecondArg = Arg;
1678 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001679
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001680 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001681 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001683 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001684 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001685 Info.FirstArg = Param;
1686 Info.SecondArg = Arg;
1687 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001688
1689 case TemplateArgument::TemplateExpansion:
1690 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001692 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001693 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001694 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001695 return Sema::TDK_Success;
1696
1697 Info.FirstArg = Param;
1698 Info.SecondArg = Arg;
1699 return Sema::TDK_NonDeducedMismatch;
1700
1701 case TemplateArgument::NullPtr:
1702 if (Arg.getKind() == TemplateArgument::NullPtr &&
1703 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001704 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001705
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001706 Info.FirstArg = Param;
1707 Info.SecondArg = Arg;
1708 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001709
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001710 case TemplateArgument::Integral:
1711 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001712 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001713 return Sema::TDK_Success;
1714
1715 Info.FirstArg = Param;
1716 Info.SecondArg = Arg;
1717 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001718 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001719
1720 if (Arg.getKind() == TemplateArgument::Expression) {
1721 Info.FirstArg = Param;
1722 Info.SecondArg = Arg;
1723 return Sema::TDK_NonDeducedMismatch;
1724 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001725
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001726 Info.FirstArg = Param;
1727 Info.SecondArg = Arg;
1728 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001729
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001730 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001731 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001732 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1733 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001734 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001735 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001736 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001737 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001738 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001739 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001740 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001741 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001742 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001743 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001744 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001745
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001746 Info.FirstArg = Param;
1747 Info.SecondArg = Arg;
1748 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001751 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001752 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001753 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001754 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001755 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001756 }
Mike Stump11289f42009-09-09 15:08:12 +00001757
David Blaikiee4d798f2012-01-20 21:50:17 +00001758 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001759}
1760
Douglas Gregor7baabef2010-12-22 18:17:10 +00001761/// \brief Determine whether there is a template argument to be used for
1762/// deduction.
1763///
1764/// This routine "expands" argument packs in-place, overriding its input
1765/// parameters so that \c Args[ArgIdx] will be the available template argument.
1766///
1767/// \returns true if there is another template argument (which will be at
1768/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001769static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001770 unsigned &ArgIdx,
1771 unsigned &NumArgs) {
1772 if (ArgIdx == NumArgs)
1773 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774
Douglas Gregor7baabef2010-12-22 18:17:10 +00001775 const TemplateArgument &Arg = Args[ArgIdx];
1776 if (Arg.getKind() != TemplateArgument::Pack)
1777 return true;
1778
1779 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1780 Args = Arg.pack_begin();
1781 NumArgs = Arg.pack_size();
1782 ArgIdx = 0;
1783 return ArgIdx < NumArgs;
1784}
1785
Douglas Gregord0ad2942010-12-23 01:24:45 +00001786/// \brief Determine whether the given set of template arguments has a pack
1787/// expansion that is not the last template argument.
1788static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1789 unsigned NumArgs) {
1790 unsigned ArgIdx = 0;
1791 while (ArgIdx < NumArgs) {
1792 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793
Douglas Gregord0ad2942010-12-23 01:24:45 +00001794 // Unwrap argument packs.
1795 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1796 Args = Arg.pack_begin();
1797 NumArgs = Arg.pack_size();
1798 ArgIdx = 0;
1799 continue;
1800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001801
Douglas Gregord0ad2942010-12-23 01:24:45 +00001802 ++ArgIdx;
1803 if (ArgIdx == NumArgs)
1804 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805
Douglas Gregord0ad2942010-12-23 01:24:45 +00001806 if (Arg.isPackExpansion())
1807 return true;
1808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809
Douglas Gregord0ad2942010-12-23 01:24:45 +00001810 return false;
1811}
1812
Douglas Gregor7baabef2010-12-22 18:17:10 +00001813static Sema::TemplateDeductionResult
1814DeduceTemplateArguments(Sema &S,
1815 TemplateParameterList *TemplateParams,
1816 const TemplateArgument *Params, unsigned NumParams,
1817 const TemplateArgument *Args, unsigned NumArgs,
1818 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001819 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001820 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 // If the template argument list of P contains a pack expansion that is not
1822 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001823 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001824 if (hasPackExpansionBeforeEnd(Params, NumParams))
1825 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001827 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001828 // If P has a form that contains <T> or <i>, then each argument Pi of the
1829 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001830 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001831 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001832 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001833 ++ParamIdx) {
1834 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001835 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001836
Douglas Gregor7baabef2010-12-22 18:17:10 +00001837 // Check whether we have enough arguments.
1838 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001839 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001841 if (Args[ArgIdx].isPackExpansion()) {
1842 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1843 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001844 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001847 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001848 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001849 = DeduceTemplateArguments(S, TemplateParams,
1850 Params[ParamIdx], Args[ArgIdx],
1851 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001852 return Result;
1853
Douglas Gregor7baabef2010-12-22 18:17:10 +00001854 // Move to the next argument.
1855 ++ArgIdx;
1856 continue;
1857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001859 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001861 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 // If Pi is a pack expansion, then the pattern of Pi is compared with
1863 // each remaining argument in the template argument list of A. Each
1864 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001865 // template parameter packs expanded by Pi.
1866 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001868 // FIXME: If there are no remaining arguments, we can bail out early
1869 // and set any deduced parameter packs to an empty argument pack.
1870 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001871
Richard Smith0a80d572014-05-29 01:12:14 +00001872 // Prepare to deduce the packs within the pattern.
1873 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001874
1875 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001877 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001878 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001879 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001880 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001882 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001884 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1885 Info, Deduced))
1886 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Richard Smith0a80d572014-05-29 01:12:14 +00001888 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891 // Build argument packs for each of the parameter packs expanded by this
1892 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001893 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001895 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Douglas Gregor7baabef2010-12-22 18:17:10 +00001897 return Sema::TDK_Success;
1898}
1899
Mike Stump11289f42009-09-09 15:08:12 +00001900static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001901DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001902 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001903 const TemplateArgumentList &ParamList,
1904 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001905 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001906 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001908 ParamList.data(), ParamList.size(),
1909 ArgList.data(), ArgList.size(),
1910 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001911}
1912
Douglas Gregor705c9002009-06-26 20:57:09 +00001913/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001914static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001915 const TemplateArgument &X,
1916 const TemplateArgument &Y) {
1917 if (X.getKind() != Y.getKind())
1918 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001919
Douglas Gregor705c9002009-06-26 20:57:09 +00001920 switch (X.getKind()) {
1921 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001922 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001923
Douglas Gregor705c9002009-06-26 20:57:09 +00001924 case TemplateArgument::Type:
1925 return Context.getCanonicalType(X.getAsType()) ==
1926 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001927
Douglas Gregor705c9002009-06-26 20:57:09 +00001928 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001929 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001930
1931 case TemplateArgument::NullPtr:
1932 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001933
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001934 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001935 case TemplateArgument::TemplateExpansion:
1936 return Context.getCanonicalTemplateName(
1937 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1938 Context.getCanonicalTemplateName(
1939 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940
Douglas Gregor705c9002009-06-26 20:57:09 +00001941 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001942 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001943
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001944 case TemplateArgument::Expression: {
1945 llvm::FoldingSetNodeID XID, YID;
1946 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001948 return XID == YID;
1949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Douglas Gregor705c9002009-06-26 20:57:09 +00001951 case TemplateArgument::Pack:
1952 if (X.pack_size() != Y.pack_size())
1953 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001954
1955 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1956 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001957 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001958 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001959 if (!isSameTemplateArg(Context, *XP, *YP))
1960 return false;
1961
1962 return true;
1963 }
1964
David Blaikiee4d798f2012-01-20 21:50:17 +00001965 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00001966}
1967
Douglas Gregorca4686d2011-01-04 23:35:54 +00001968/// \brief Allocate a TemplateArgumentLoc where all locations have
1969/// been initialized to the given location.
1970///
1971/// \param S The semantic analysis object.
1972///
James Dennett634962f2012-06-14 21:40:34 +00001973/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00001974/// location information for.
1975///
1976/// \param NTTPType For a declaration template argument, the type of
1977/// the non-type template parameter that corresponds to this template
1978/// argument.
1979///
1980/// \param Loc The source location to use for the resulting template
1981/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00001983getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001985 QualType NTTPType,
1986 SourceLocation Loc) {
1987 switch (Arg.getKind()) {
1988 case TemplateArgument::Null:
1989 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
Douglas Gregorca4686d2011-01-04 23:35:54 +00001991 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001993 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994
Douglas Gregorca4686d2011-01-04 23:35:54 +00001995 case TemplateArgument::Declaration: {
1996 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00001997 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001998 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00001999 return TemplateArgumentLoc(TemplateArgument(E), E);
2000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001
Eli Friedmanb826a002012-09-26 02:36:12 +00002002 case TemplateArgument::NullPtr: {
2003 Expr *E
2004 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002005 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002006 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2007 E);
2008 }
2009
Douglas Gregorca4686d2011-01-04 23:35:54 +00002010 case TemplateArgument::Integral: {
2011 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002012 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002013 return TemplateArgumentLoc(TemplateArgument(E), E);
2014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregor9d802122011-03-02 17:09:35 +00002016 case TemplateArgument::Template:
2017 case TemplateArgument::TemplateExpansion: {
2018 NestedNameSpecifierLocBuilder Builder;
2019 TemplateName Template = Arg.getAsTemplate();
2020 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2021 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002022 else if (QualifiedTemplateName *QTN =
2023 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002024 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2025
2026 if (Arg.getKind() == TemplateArgument::Template)
2027 return TemplateArgumentLoc(Arg,
2028 Builder.getWithLocInContext(S.Context),
2029 Loc);
2030
2031
2032 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2033 Loc, Loc);
2034 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002035
Douglas Gregorca4686d2011-01-04 23:35:54 +00002036 case TemplateArgument::Expression:
2037 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregorca4686d2011-01-04 23:35:54 +00002039 case TemplateArgument::Pack:
2040 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
David Blaikiee4d798f2012-01-20 21:50:17 +00002043 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002044}
2045
2046
2047/// \brief Convert the given deduced template argument and add it to the set of
2048/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002049static bool
2050ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2051 DeducedTemplateArgument Arg,
2052 NamedDecl *Template,
2053 QualType NTTPType,
2054 unsigned ArgumentPackIndex,
2055 TemplateDeductionInfo &Info,
2056 bool InFunctionTemplate,
2057 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002058 if (Arg.getKind() == TemplateArgument::Pack) {
2059 // This is a template argument pack, so check each of its arguments against
2060 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002061 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002062 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002063 // When converting the deduced template argument, append it to the
2064 // general output list. We need to do this so that the template argument
2065 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002066 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002067 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002068 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002069 NTTPType, PackedArgsBuilder.size(),
2070 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002071 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
Douglas Gregor51bc5712011-01-05 20:52:18 +00002073 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002074 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002076
Douglas Gregorca4686d2011-01-04 23:35:54 +00002077 // Create the resulting argument pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor74c6d192011-01-11 23:09:57 +00002079 PackedArgsBuilder.data(),
2080 PackedArgsBuilder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002081 return false;
2082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083
Douglas Gregorca4686d2011-01-04 23:35:54 +00002084 // Convert the deduced template argument into a template
2085 // argument that we can check, almost as if the user had written
2086 // the template argument explicitly.
2087 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2088 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089
Douglas Gregorca4686d2011-01-04 23:35:54 +00002090 // Check the template argument, converting it as necessary.
2091 return S.CheckTemplateArgument(Param, ArgLoc,
2092 Template,
2093 Template->getLocation(),
2094 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002095 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002096 Output,
2097 InFunctionTemplate
2098 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002099 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002100 : Sema::CTAK_Deduced)
2101 : Sema::CTAK_Specified);
2102}
2103
Douglas Gregor684268d2010-04-29 06:21:43 +00002104/// Complete template argument deduction for a class template partial
2105/// specialization.
2106static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002108 ClassTemplatePartialSpecializationDecl *Partial,
2109 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002110 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002111 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002112 // Unevaluated SFINAE context.
2113 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002114 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115
Douglas Gregor684268d2010-04-29 06:21:43 +00002116 Sema::ContextRAII SavedContext(S, Partial);
2117
2118 // C++ [temp.deduct.type]p2:
2119 // [...] or if any template argument remains neither deduced nor
2120 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002121 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002122 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2123 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002124 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002125 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002126 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002127 return Sema::TDK_Incomplete;
2128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129
Douglas Gregorca4686d2011-01-04 23:35:54 +00002130 // We have deduced this argument, so it still needs to be
2131 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132
Douglas Gregorca4686d2011-01-04 23:35:54 +00002133 // First, for a non-type template parameter type that is
2134 // initialized by a declaration, we need the type of the
2135 // corresponding non-type template parameter.
2136 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002138 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002139 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002140 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002142 Builder.data(), Builder.size());
2143 NTTPType = S.SubstType(NTTPType,
2144 MultiLevelTemplateArgumentList(TemplateArgs),
2145 NTTP->getLocation(),
2146 NTTP->getDeclName());
2147 if (NTTPType.isNull()) {
2148 Info.Param = makeTemplateParameter(Param);
2149 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2151 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002152 Builder.size()));
2153 return Sema::TDK_SubstitutionFailure;
2154 }
2155 }
2156 }
2157
Douglas Gregorca4686d2011-01-04 23:35:54 +00002158 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002159 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002160 Builder)) {
2161 Info.Param = makeTemplateParameter(Param);
2162 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2164 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002165 return Sema::TDK_SubstitutionFailure;
2166 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregor684268d2010-04-29 06:21:43 +00002169 // Form the template argument list from the deduced template arguments.
2170 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002172 Builder.size());
2173
Douglas Gregor684268d2010-04-29 06:21:43 +00002174 Info.reset(DeducedArgumentList);
2175
2176 // Substitute the deduced template arguments into the template
2177 // arguments of the class template partial specialization, and
2178 // verify that the instantiated template arguments are both valid
2179 // and are equivalent to the template arguments originally provided
2180 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002181 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002182 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002183 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002184 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002185 const TemplateArgumentLoc *PartialTemplateArgs
2186 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002187
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002188 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2189 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002190
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002191 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002192 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2193 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2194 if (ParamIdx >= Partial->getTemplateParameters()->size())
2195 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2196
2197 Decl *Param
2198 = const_cast<NamedDecl *>(
2199 Partial->getTemplateParameters()->getParam(ParamIdx));
2200 Info.Param = makeTemplateParameter(Param);
2201 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2202 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002203 }
2204
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002205 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002206 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002207 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002208 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209
Douglas Gregorca4686d2011-01-04 23:35:54 +00002210 TemplateParameterList *TemplateParams
2211 = ClassTemplate->getTemplateParameters();
2212 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002213 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002214 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002215 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002216 Info.FirstArg = TemplateArgs[I];
2217 Info.SecondArg = InstArg;
2218 return Sema::TDK_NonDeducedMismatch;
2219 }
2220 }
2221
2222 if (Trap.hasErrorOccurred())
2223 return Sema::TDK_SubstitutionFailure;
2224
2225 return Sema::TDK_Success;
2226}
2227
Douglas Gregor170bc422009-06-12 22:31:52 +00002228/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002229/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002230/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002231Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002232Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002233 const TemplateArgumentList &TemplateArgs,
2234 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002235 if (Partial->isInvalidDecl())
2236 return TDK_Invalid;
2237
Douglas Gregor170bc422009-06-12 22:31:52 +00002238 // C++ [temp.class.spec.match]p2:
2239 // A partial specialization matches a given actual template
2240 // argument list if the template arguments of the partial
2241 // specialization can be deduced from the actual template argument
2242 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002243
2244 // Unevaluated SFINAE context.
2245 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002246 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002247
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002248 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002249 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002250 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002251 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002252 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002253 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002254 TemplateArgs, Info, Deduced))
2255 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002256
Richard Smith80934652012-07-16 01:09:10 +00002257 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002258 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2259 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002260 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002261 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002262
Douglas Gregore1416332009-06-14 08:02:22 +00002263 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002264 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002265
2266 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002267 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002268}
Douglas Gregor91772d12009-06-13 00:26:55 +00002269
Larisse Voufo39a1e502013-08-06 01:03:05 +00002270/// Complete template argument deduction for a variable template partial
2271/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002272/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2273/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2274/// VarTemplate(Partial)SpecializationDecl with a new data
2275/// structure Template(Partial)SpecializationDecl, and
2276/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002277static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2278 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2279 const TemplateArgumentList &TemplateArgs,
2280 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2281 TemplateDeductionInfo &Info) {
2282 // Unevaluated SFINAE context.
2283 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2284 Sema::SFINAETrap Trap(S);
2285
2286 // C++ [temp.deduct.type]p2:
2287 // [...] or if any template argument remains neither deduced nor
2288 // explicitly specified, template argument deduction fails.
2289 SmallVector<TemplateArgument, 4> Builder;
2290 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2291 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2292 NamedDecl *Param = PartialParams->getParam(I);
2293 if (Deduced[I].isNull()) {
2294 Info.Param = makeTemplateParameter(Param);
2295 return Sema::TDK_Incomplete;
2296 }
2297
2298 // We have deduced this argument, so it still needs to be
2299 // checked and converted.
2300
2301 // First, for a non-type template parameter type that is
2302 // initialized by a declaration, we need the type of the
2303 // corresponding non-type template parameter.
2304 QualType NTTPType;
2305 if (NonTypeTemplateParmDecl *NTTP =
2306 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2307 NTTPType = NTTP->getType();
2308 if (NTTPType->isDependentType()) {
2309 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2310 Builder.data(), Builder.size());
2311 NTTPType =
2312 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2313 NTTP->getLocation(), NTTP->getDeclName());
2314 if (NTTPType.isNull()) {
2315 Info.Param = makeTemplateParameter(Param);
2316 // FIXME: These template arguments are temporary. Free them!
2317 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2318 Builder.size()));
2319 return Sema::TDK_SubstitutionFailure;
2320 }
2321 }
2322 }
2323
2324 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2325 0, Info, false, Builder)) {
2326 Info.Param = makeTemplateParameter(Param);
2327 // FIXME: These template arguments are temporary. Free them!
2328 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2329 Builder.size()));
2330 return Sema::TDK_SubstitutionFailure;
2331 }
2332 }
2333
2334 // Form the template argument list from the deduced template arguments.
2335 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2336 S.Context, Builder.data(), Builder.size());
2337
2338 Info.reset(DeducedArgumentList);
2339
2340 // Substitute the deduced template arguments into the template
2341 // arguments of the class template partial specialization, and
2342 // verify that the instantiated template arguments are both valid
2343 // and are equivalent to the template arguments originally provided
2344 // to the class template.
2345 LocalInstantiationScope InstScope(S);
2346 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002347 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2348 = Partial->getTemplateArgsAsWritten();
2349 const TemplateArgumentLoc *PartialTemplateArgs
2350 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002351
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002352 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2353 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002354
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002355 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002356 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2357 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2358 if (ParamIdx >= Partial->getTemplateParameters()->size())
2359 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2360
2361 Decl *Param = const_cast<NamedDecl *>(
2362 Partial->getTemplateParameters()->getParam(ParamIdx));
2363 Info.Param = makeTemplateParameter(Param);
2364 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2365 return Sema::TDK_SubstitutionFailure;
2366 }
2367 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2368 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2369 false, ConvertedInstArgs))
2370 return Sema::TDK_SubstitutionFailure;
2371
2372 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2373 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2374 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2375 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2376 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2377 Info.FirstArg = TemplateArgs[I];
2378 Info.SecondArg = InstArg;
2379 return Sema::TDK_NonDeducedMismatch;
2380 }
2381 }
2382
2383 if (Trap.hasErrorOccurred())
2384 return Sema::TDK_SubstitutionFailure;
2385
2386 return Sema::TDK_Success;
2387}
2388
2389/// \brief Perform template argument deduction to determine whether
2390/// the given template arguments match the given variable template
2391/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002392/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2393/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2394/// VarTemplate(Partial)SpecializationDecl with a new data
2395/// structure Template(Partial)SpecializationDecl, and
2396/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002397Sema::TemplateDeductionResult
2398Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2399 const TemplateArgumentList &TemplateArgs,
2400 TemplateDeductionInfo &Info) {
2401 if (Partial->isInvalidDecl())
2402 return TDK_Invalid;
2403
2404 // C++ [temp.class.spec.match]p2:
2405 // A partial specialization matches a given actual template
2406 // argument list if the template arguments of the partial
2407 // specialization can be deduced from the actual template argument
2408 // list (14.8.2).
2409
2410 // Unevaluated SFINAE context.
2411 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2412 SFINAETrap Trap(*this);
2413
2414 SmallVector<DeducedTemplateArgument, 4> Deduced;
2415 Deduced.resize(Partial->getTemplateParameters()->size());
2416 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2417 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2418 TemplateArgs, Info, Deduced))
2419 return Result;
2420
2421 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002422 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2423 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002424 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002425 return TDK_InstantiationDepth;
2426
2427 if (Trap.hasErrorOccurred())
2428 return Sema::TDK_SubstitutionFailure;
2429
2430 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2431 Deduced, Info);
2432}
2433
Douglas Gregorfc516c92009-06-26 23:27:24 +00002434/// \brief Determine whether the given type T is a simple-template-id type.
2435static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002436 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002437 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002438 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002439
Douglas Gregorfc516c92009-06-26 23:27:24 +00002440 return false;
2441}
Douglas Gregor9b146582009-07-08 20:55:45 +00002442
2443/// \brief Substitute the explicitly-provided template arguments into the
2444/// given function template according to C++ [temp.arg.explicit].
2445///
2446/// \param FunctionTemplate the function template into which the explicit
2447/// template arguments will be substituted.
2448///
James Dennett634962f2012-06-14 21:40:34 +00002449/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002450/// arguments.
2451///
Mike Stump11289f42009-09-09 15:08:12 +00002452/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002453/// with the converted and checked explicit template arguments.
2454///
Mike Stump11289f42009-09-09 15:08:12 +00002455/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002456/// parameters.
2457///
2458/// \param FunctionType if non-NULL, the result type of the function template
2459/// will also be instantiated and the pointed-to value will be updated with
2460/// the instantiated function type.
2461///
2462/// \param Info if substitution fails for any reason, this object will be
2463/// populated with more information about the failure.
2464///
2465/// \returns TDK_Success if substitution was successful, or some failure
2466/// condition.
2467Sema::TemplateDeductionResult
2468Sema::SubstituteExplicitTemplateArguments(
2469 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002470 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002471 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2472 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002473 QualType *FunctionType,
2474 TemplateDeductionInfo &Info) {
2475 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2476 TemplateParameterList *TemplateParams
2477 = FunctionTemplate->getTemplateParameters();
2478
John McCall6b51f282009-11-23 01:53:49 +00002479 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002480 // No arguments to substitute; just copy over the parameter types and
2481 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002482 for (auto P : Function->params())
2483 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002484
Douglas Gregor9b146582009-07-08 20:55:45 +00002485 if (FunctionType)
2486 *FunctionType = Function->getType();
2487 return TDK_Success;
2488 }
Mike Stump11289f42009-09-09 15:08:12 +00002489
Eli Friedman77dcc722012-02-08 03:07:05 +00002490 // Unevaluated SFINAE context.
2491 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002492 SFINAETrap Trap(*this);
2493
Douglas Gregor9b146582009-07-08 20:55:45 +00002494 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002495 // Template arguments that are present shall be specified in the
2496 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002497 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002498 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002499 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002500
2501 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002502 // explicitly-specified template arguments against this function template,
2503 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002504 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002505 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2506 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002507 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2508 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002509 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002510 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002511
Douglas Gregor9b146582009-07-08 20:55:45 +00002512 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002513 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002514 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002515 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002516 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002517 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002518 if (Index >= TemplateParams->size())
2519 Index = TemplateParams->size() - 1;
2520 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002521 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor9b146582009-07-08 20:55:45 +00002524 // Form the template argument list from the explicitly-specified
2525 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002526 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002527 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002528 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529
John McCall036855a2010-10-12 19:40:14 +00002530 // Template argument deduction and the final substitution should be
2531 // done in the context of the templated declaration. Explicit
2532 // argument substitution, on the other hand, needs to happen in the
2533 // calling context.
2534 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2535
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002536 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002537 // note that the template argument pack is partially substituted and record
2538 // the explicit template arguments. They'll be used as part of deduction
2539 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002540 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2541 const TemplateArgument &Arg = Builder[I];
2542 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002543 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002545 Arg.pack_begin(),
2546 Arg.pack_size());
2547 break;
2548 }
2549 }
2550
Richard Smith5e580292012-02-10 09:58:53 +00002551 const FunctionProtoType *Proto
2552 = Function->getType()->getAs<FunctionProtoType>();
2553 assert(Proto && "Function template does not have a prototype?");
2554
Richard Smith70b13042015-01-09 01:19:56 +00002555 // Isolate our substituted parameters from our caller.
2556 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2557
Douglas Gregor9b146582009-07-08 20:55:45 +00002558 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002559 // explicitly-specified template arguments. If the function has a trailing
2560 // return type, substitute it after the arguments to ensure we substitute
2561 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002562 if (Proto->hasTrailingReturn()) {
2563 if (SubstParmTypes(Function->getLocation(),
2564 Function->param_begin(), Function->getNumParams(),
2565 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2566 ParamTypes))
2567 return TDK_SubstitutionFailure;
2568 }
2569
Richard Smith5e580292012-02-10 09:58:53 +00002570 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002571 QualType ResultType;
2572 {
2573 // C++11 [expr.prim.general]p3:
2574 // If a declaration declares a member function or member function
2575 // template of a class X, the expression this is a prvalue of type
2576 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2577 // and the end of the function-definition, member-declarator, or
2578 // declarator.
2579 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002580 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002581 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2582 ThisContext = Method->getParent();
2583 ThisTypeQuals = Method->getTypeQualifiers();
2584 }
2585
2586 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002587 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002588
2589 ResultType =
2590 SubstType(Proto->getReturnType(),
2591 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2592 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002593 if (ResultType.isNull() || Trap.hasErrorOccurred())
2594 return TDK_SubstitutionFailure;
2595 }
2596
Richard Smith5e580292012-02-10 09:58:53 +00002597 // Instantiate the types of each of the function parameters given the
2598 // explicitly-specified template arguments if we didn't do so earlier.
2599 if (!Proto->hasTrailingReturn() &&
2600 SubstParmTypes(Function->getLocation(),
2601 Function->param_begin(), Function->getNumParams(),
2602 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2603 ParamTypes))
2604 return TDK_SubstitutionFailure;
2605
Douglas Gregor9b146582009-07-08 20:55:45 +00002606 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002607 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002608 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002609 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002610 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002611 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2612 return TDK_SubstitutionFailure;
2613 }
Mike Stump11289f42009-09-09 15:08:12 +00002614
Douglas Gregor9b146582009-07-08 20:55:45 +00002615 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002616 // Trailing template arguments that can be deduced (14.8.2) may be
2617 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002618 // template arguments can be deduced, they may all be omitted; in this
2619 // case, the empty template argument list <> itself may also be omitted.
2620 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002621 // Take all of the explicitly-specified arguments and put them into
2622 // the set of deduced template arguments. Explicitly-specified
2623 // parameter packs, however, will be set to NULL since the deduction
2624 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002625 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002626 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2627 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2628 if (Arg.getKind() == TemplateArgument::Pack)
2629 Deduced.push_back(DeducedTemplateArgument());
2630 else
2631 Deduced.push_back(Arg);
2632 }
Mike Stump11289f42009-09-09 15:08:12 +00002633
Douglas Gregor9b146582009-07-08 20:55:45 +00002634 return TDK_Success;
2635}
2636
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002637/// \brief Check whether the deduced argument type for a call to a function
2638/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2639static bool
2640CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2641 QualType DeducedA) {
2642 ASTContext &Context = S.Context;
2643
2644 QualType A = OriginalArg.OriginalArgType;
2645 QualType OriginalParamType = OriginalArg.OriginalParamType;
2646
2647 // Check for type equality (top-level cv-qualifiers are ignored).
2648 if (Context.hasSameUnqualifiedType(A, DeducedA))
2649 return false;
2650
2651 // Strip off references on the argument types; they aren't needed for
2652 // the following checks.
2653 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2654 DeducedA = DeducedARef->getPointeeType();
2655 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2656 A = ARef->getPointeeType();
2657
2658 // C++ [temp.deduct.call]p4:
2659 // [...] However, there are three cases that allow a difference:
2660 // - If the original P is a reference type, the deduced A (i.e., the
2661 // type referred to by the reference) can be more cv-qualified than
2662 // the transformed A.
2663 if (const ReferenceType *OriginalParamRef
2664 = OriginalParamType->getAs<ReferenceType>()) {
2665 // We don't want to keep the reference around any more.
2666 OriginalParamType = OriginalParamRef->getPointeeType();
2667
2668 Qualifiers AQuals = A.getQualifiers();
2669 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002670
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002671 // Under Objective-C++ ARC, the deduced type may have implicitly
2672 // been given strong or (when dealing with a const reference)
2673 // unsafe_unretained lifetime. If so, update the original
2674 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002675 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002676 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2677 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2678 (DeducedAQuals.hasConst() &&
2679 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2680 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002681 }
2682
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002683 if (AQuals == DeducedAQuals) {
2684 // Qualifiers match; there's nothing to do.
2685 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002686 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002687 } else {
2688 // Qualifiers are compatible, so have the argument type adopt the
2689 // deduced argument type's qualifiers as if we had performed the
2690 // qualification conversion.
2691 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2692 }
2693 }
2694
2695 // - The transformed A can be another pointer or pointer to member
2696 // type that can be converted to the deduced A via a qualification
2697 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002698 //
2699 // Also allow conversions which merely strip [[noreturn]] from function types
2700 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002701 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002702 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002703 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002704 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002705 (S.IsQualificationConversion(A, DeducedA, false,
2706 ObjCLifetimeConversion) ||
2707 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002708 return false;
2709
2710
2711 // - If P is a class and P has the form simple-template-id, then the
2712 // transformed A can be a derived class of the deduced A. [...]
2713 // [...] Likewise, if P is a pointer to a class of the form
2714 // simple-template-id, the transformed A can be a pointer to a
2715 // derived class pointed to by the deduced A.
2716 if (const PointerType *OriginalParamPtr
2717 = OriginalParamType->getAs<PointerType>()) {
2718 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2719 if (const PointerType *APtr = A->getAs<PointerType>()) {
2720 if (A->getPointeeType()->isRecordType()) {
2721 OriginalParamType = OriginalParamPtr->getPointeeType();
2722 DeducedA = DeducedAPtr->getPointeeType();
2723 A = APtr->getPointeeType();
2724 }
2725 }
2726 }
2727 }
2728
2729 if (Context.hasSameUnqualifiedType(A, DeducedA))
2730 return false;
2731
2732 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2733 S.IsDerivedFrom(A, DeducedA))
2734 return false;
2735
2736 return true;
2737}
2738
Mike Stump11289f42009-09-09 15:08:12 +00002739/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002740/// checking the deduced template arguments for completeness and forming
2741/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002742///
2743/// \param OriginalCallArgs If non-NULL, the original call arguments against
2744/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002745Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002746Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002747 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002748 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002749 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002750 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002751 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2752 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002753 TemplateParameterList *TemplateParams
2754 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002755
Eli Friedman77dcc722012-02-08 03:07:05 +00002756 // Unevaluated SFINAE context.
2757 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002758 SFINAETrap Trap(*this);
2759
Douglas Gregor9b146582009-07-08 20:55:45 +00002760 // Enter a new template instantiation context while we instantiate the
2761 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002762 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002763 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2764 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002765 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2766 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002767 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002768 return TDK_InstantiationDepth;
2769
John McCalle23b8712010-04-29 01:18:58 +00002770 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002771
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002772 // C++ [temp.deduct.type]p2:
2773 // [...] or if any template argument remains neither deduced nor
2774 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002775 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002776 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2777 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002778
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002779 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002780 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002781 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002782 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002783 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002784 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002785 // We may have had explicitly-specified template arguments for a
2786 // template parameter pack (that may or may not have been extended
2787 // via additional deduced arguments).
2788 if (Param->isParameterPack() && CurrentInstantiationScope) {
2789 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2790 Param) {
2791 // Forget the partially-substituted pack; its substitution is now
2792 // complete.
2793 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2794 }
2795 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002796 continue;
2797 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002798 // We have deduced this argument, so it still needs to be
2799 // checked and converted.
2800
2801 // First, for a non-type template parameter type that is
2802 // initialized by a declaration, we need the type of the
2803 // corresponding non-type template parameter.
2804 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805 if (NonTypeTemplateParmDecl *NTTP
2806 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002807 NTTPType = NTTP->getType();
2808 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002810 Builder.data(), Builder.size());
2811 NTTPType = SubstType(NTTPType,
2812 MultiLevelTemplateArgumentList(TemplateArgs),
2813 NTTP->getLocation(),
2814 NTTP->getDeclName());
2815 if (NTTPType.isNull()) {
2816 Info.Param = makeTemplateParameter(Param);
2817 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818 Info.reset(TemplateArgumentList::CreateCopy(Context,
2819 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002820 Builder.size()));
2821 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002822 }
2823 }
2824 }
2825
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002826 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002827 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002828 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002829 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002830 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2832 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002833 return TDK_SubstitutionFailure;
2834 }
2835
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002836 continue;
2837 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002839 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002841 // be deduced to an empty sequence of template arguments.
2842 // FIXME: Where did the word "trailing" come from?
2843 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002844 // We may have had explicitly-specified template arguments for this
2845 // template parameter pack. If so, our empty deduction extends the
2846 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2847 const TemplateArgument *ExplicitArgs;
2848 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002849 if (CurrentInstantiationScope &&
2850 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002851 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002852 == Param) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002853 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854
Douglas Gregorcaddba92013-01-18 22:27:09 +00002855 // Forget the partially-substituted pack; it's substitution is now
2856 // complete.
2857 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2858 } else {
2859 Builder.push_back(TemplateArgument::getEmptyPack());
2860 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002861 continue;
2862 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002863
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002865 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002866 TemplateArgumentLoc DefArg
2867 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2868 FunctionTemplate->getLocation(),
2869 FunctionTemplate->getSourceRange().getEnd(),
2870 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002871 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002872
2873 // If there was no default argument, deduction is incomplete.
2874 if (DefArg.getArgument().isNull()) {
2875 Info.Param = makeTemplateParameter(
2876 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002877 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2878 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002879 if (PartialOverloading) break;
2880
Richard Smithc87b9382013-07-04 01:01:24 +00002881 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002883
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002884 // Check whether we can actually use the default argument.
2885 if (CheckTemplateArgument(Param, DefArg,
2886 FunctionTemplate,
2887 FunctionTemplate->getLocation(),
2888 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002889 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002890 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002891 Info.Param = makeTemplateParameter(
2892 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002893 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002894 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002895 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002896 return TDK_SubstitutionFailure;
2897 }
2898
2899 // If we get here, we successfully used the default template argument.
2900 }
2901
2902 // Form the template argument list from the deduced template arguments.
2903 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002904 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002905 Info.reset(DeducedArgumentList);
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002908 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002909 DeclContext *Owner = FunctionTemplate->getDeclContext();
2910 if (FunctionTemplate->getFriendObjectKind())
2911 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002912 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002913 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002914 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002915 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002916 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002919 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920
Mike Stump11289f42009-09-09 15:08:12 +00002921 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002922 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002923 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2924 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002925 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002927 // There may have been an error that did not prevent us from constructing a
2928 // declaration. Mark the declaration invalid and return with a substitution
2929 // failure.
2930 if (Trap.hasErrorOccurred()) {
2931 Specialization->setInvalidDecl(true);
2932 return TDK_SubstitutionFailure;
2933 }
2934
Douglas Gregore65aacb2011-06-16 16:50:48 +00002935 if (OriginalCallArgs) {
2936 // C++ [temp.deduct.call]p4:
2937 // In general, the deduction process attempts to find template argument
2938 // values that will make the deduced A identical to A (after the type A
2939 // is transformed as described above). [...]
2940 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2941 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002942 unsigned ParamIdx = OriginalArg.ArgIdx;
2943
2944 if (ParamIdx >= Specialization->getNumParams())
2945 continue;
2946
2947 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002948 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2949 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002950 }
2951 }
2952
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002953 // If we suppressed any diagnostics while performing template argument
2954 // deduction, and if we haven't already instantiated this declaration,
2955 // keep track of these diagnostics. They'll be emitted if this specialization
2956 // is actually used.
2957 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002958 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002959 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2960 if (Pos == SuppressedDiagnostics.end())
2961 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2962 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002964
Mike Stump11289f42009-09-09 15:08:12 +00002965 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002966}
2967
John McCall8d08b9b2010-08-27 09:08:28 +00002968/// Gets the type of a function for template-argument-deducton
2969/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002970static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002971 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002972 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002973 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002974 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002975 return QualType();
2976
John McCallc1f69982010-02-02 02:21:27 +00002977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002978 if (Method->isInstance()) {
2979 // An instance method that's referenced in a form that doesn't
2980 // look like a member pointer is just invalid.
2981 if (!R.HasFormOfMemberPointer) return QualType();
2982
Richard Smith2a7d4812013-05-04 07:00:32 +00002983 return S.Context.getMemberPointerType(Fn->getType(),
2984 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002985 }
2986
2987 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002988 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002989}
2990
2991/// Apply the deduction rules for overload sets.
2992///
2993/// \return the null type if this argument should be treated as an
2994/// undeduced context
2995static QualType
2996ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002997 Expr *Arg, QualType ParamType,
2998 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999
John McCall8d08b9b2010-08-27 09:08:28 +00003000 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003001
John McCall8d08b9b2010-08-27 09:08:28 +00003002 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003003
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003004 // C++0x [temp.deduct.call]p4
3005 unsigned TDF = 0;
3006 if (ParamWasReference)
3007 TDF |= TDF_ParamWithReferenceType;
3008 if (R.IsAddressOfOperand)
3009 TDF |= TDF_IgnoreQualifiers;
3010
John McCallc1f69982010-02-02 02:21:27 +00003011 // C++0x [temp.deduct.call]p6:
3012 // When P is a function type, pointer to function type, or pointer
3013 // to member function type:
3014
3015 if (!ParamType->isFunctionType() &&
3016 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003017 !ParamType->isMemberFunctionPointerType()) {
3018 if (Ovl->hasExplicitTemplateArgs()) {
3019 // But we can still look for an explicit specialization.
3020 if (FunctionDecl *ExplicitSpec
3021 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003022 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003023 }
John McCallc1f69982010-02-02 02:21:27 +00003024
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003025 return QualType();
3026 }
3027
3028 // Gather the explicit template arguments, if any.
3029 TemplateArgumentListInfo ExplicitTemplateArgs;
3030 if (Ovl->hasExplicitTemplateArgs())
3031 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003032 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003033 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3034 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003035 NamedDecl *D = (*I)->getUnderlyingDecl();
3036
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003037 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3038 // - If the argument is an overload set containing one or more
3039 // function templates, the parameter is treated as a
3040 // non-deduced context.
3041 if (!Ovl->hasExplicitTemplateArgs())
3042 return QualType();
3043
3044 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003045 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003046 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003047 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3048 Specialization, Info))
3049 continue;
3050
3051 D = Specialization;
3052 }
John McCallc1f69982010-02-02 02:21:27 +00003053
3054 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003055 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003056 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003057
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003058 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003060 ArgType->isFunctionType())
3061 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062
John McCallc1f69982010-02-02 02:21:27 +00003063 // - If the argument is an overload set (not containing function
3064 // templates), trial argument deduction is attempted using each
3065 // of the members of the set. If deduction succeeds for only one
3066 // of the overload set members, that member is used as the
3067 // argument value for the deduction. If deduction succeeds for
3068 // more than one member of the overload set the parameter is
3069 // treated as a non-deduced context.
3070
3071 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3072 // Type deduction is done independently for each P/A pair, and
3073 // the deduced template argument values are then combined.
3074 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003075 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003076 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003077 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003078 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003079 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3080 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003081 if (Result) continue;
3082 if (!Match.isNull()) return QualType();
3083 Match = ArgType;
3084 }
3085
3086 return Match;
3087}
3088
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003090/// described in C++ [temp.deduct.call].
3091///
3092/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003093/// argument deduction based on this P/A pair because the argument is an
3094/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003095static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3096 TemplateParameterList *TemplateParams,
3097 QualType &ParamType,
3098 QualType &ArgType,
3099 Expr *Arg,
3100 unsigned &TDF) {
3101 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003102 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003103 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003104 if (ParamType.hasQualifiers())
3105 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003106
3107 // [...] If P is a reference type, the type referred to by P is
3108 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003109 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003110 if (ParamRefType)
3111 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003112
Nathan Sidwell96090022015-01-16 15:20:14 +00003113 // Overload sets usually make this parameter an undeduced context,
3114 // but there are sometimes special circumstances. Typically
3115 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003116 if (ArgType == S.Context.OverloadTy) {
3117 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3118 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003119 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003120 if (ArgType.isNull())
3121 return true;
3122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123
Douglas Gregor7825bf32011-01-06 22:09:01 +00003124 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003125 // If the argument has incomplete array type, try to complete its type.
3126 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
3127 ArgType = Arg->getType();
3128
Douglas Gregor7825bf32011-01-06 22:09:01 +00003129 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003130 // If P is an rvalue reference to a cv-unqualified template
3131 // parameter and the argument is an lvalue, the type "lvalue
3132 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003133 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003134 !ParamType.getQualifiers() &&
3135 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003136 Arg->isLValue())
3137 ArgType = S.Context.getLValueReferenceType(ArgType);
3138 } else {
3139 // C++ [temp.deduct.call]p2:
3140 // If P is not a reference type:
3141 // - If A is an array type, the pointer type produced by the
3142 // array-to-pointer standard conversion (4.2) is used in place of
3143 // A for type deduction; otherwise,
3144 if (ArgType->isArrayType())
3145 ArgType = S.Context.getArrayDecayedType(ArgType);
3146 // - If A is a function type, the pointer type produced by the
3147 // function-to-pointer standard conversion (4.3) is used in place
3148 // of A for type deduction; otherwise,
3149 else if (ArgType->isFunctionType())
3150 ArgType = S.Context.getPointerType(ArgType);
3151 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003152 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003153 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003154 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003155 }
3156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
Douglas Gregor7825bf32011-01-06 22:09:01 +00003158 // C++0x [temp.deduct.call]p4:
3159 // In general, the deduction process attempts to find template argument
3160 // values that will make the deduced A identical to A (after the type A
3161 // is transformed as described above). [...]
3162 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
Douglas Gregor7825bf32011-01-06 22:09:01 +00003164 // - If the original P is a reference type, the deduced A (i.e., the
3165 // type referred to by the reference) can be more cv-qualified than
3166 // the transformed A.
3167 if (ParamRefType)
3168 TDF |= TDF_ParamWithReferenceType;
3169 // - The transformed A can be another pointer or pointer to member
3170 // type that can be converted to the deduced A via a qualification
3171 // conversion (4.4).
3172 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3173 ArgType->isObjCObjectPointerType())
3174 TDF |= TDF_IgnoreQualifiers;
3175 // - If P is a class and P has the form simple-template-id, then the
3176 // transformed A can be a derived class of the deduced A. Likewise,
3177 // if P is a pointer to a class of the form simple-template-id, the
3178 // transformed A can be a pointer to a derived class pointed to by
3179 // the deduced A.
3180 if (isSimpleTemplateIdType(ParamType) ||
3181 (isa<PointerType>(ParamType) &&
3182 isSimpleTemplateIdType(
3183 ParamType->getAs<PointerType>()->getPointeeType())))
3184 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
Douglas Gregor7825bf32011-01-06 22:09:01 +00003186 return false;
3187}
3188
Nico Weberc153d242014-07-28 00:02:09 +00003189static bool
3190hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3191 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003192
Hubert Tong3280b332015-06-25 00:25:49 +00003193static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3194 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3195 Expr *Arg, TemplateDeductionInfo &Info,
3196 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3197
3198/// \brief Attempt template argument deduction from an initializer list
3199/// deemed to be an argument in a function call.
3200static bool
3201DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3202 QualType AdjustedParamType, InitListExpr *ILE,
3203 TemplateDeductionInfo &Info,
3204 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3205 unsigned TDF, Sema::TemplateDeductionResult &Result) {
3206 // If the argument is an initializer list then the parameter is an undeduced
3207 // context, unless the parameter type is (reference to cv)
3208 // std::initializer_list<P'>, in which case deduction is done for each element
3209 // of the initializer list as-if it were an argument in a function call, and
3210 // the result is the deduced type if it's the same for all elements.
3211 QualType X;
3212 if (!S.isStdInitializerList(AdjustedParamType, &X))
3213 return false;
3214
3215 Result = Sema::TDK_Success;
3216
3217 // Recurse down into the init list.
3218 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3219 if ((Result = DeduceTemplateArgumentByListElement(
3220 S, TemplateParams, X, ILE->getInit(i), Info, Deduced, TDF)))
3221 return true;
3222 }
3223
3224 return true;
3225}
3226
Sebastian Redl19181662012-03-15 21:40:51 +00003227/// \brief Perform template argument deduction by matching a parameter type
3228/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003229/// an initializer list that was originally matched against a parameter
3230/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003231static Sema::TemplateDeductionResult
3232DeduceTemplateArgumentByListElement(Sema &S,
3233 TemplateParameterList *TemplateParams,
3234 QualType ParamType, Expr *Arg,
3235 TemplateDeductionInfo &Info,
3236 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3237 unsigned TDF) {
3238 // Handle the case where an init list contains another init list as the
3239 // element.
3240 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003241 Sema::TemplateDeductionResult Result;
3242 if (!DeduceFromInitializerList(S, TemplateParams,
3243 ParamType.getNonReferenceType(), ILE, Info,
3244 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003245 return Sema::TDK_Success; // Just ignore this expression.
3246
Hubert Tong3280b332015-06-25 00:25:49 +00003247 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003248 }
3249
3250 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003251 QualType ArgType = Arg->getType();
3252 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003253 ArgType, Arg, TDF)) {
3254 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003255 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003256 }
Sebastian Redl19181662012-03-15 21:40:51 +00003257 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003258 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003259}
3260
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003261/// \brief Perform template argument deduction from a function call
3262/// (C++ [temp.deduct.call]).
3263///
3264/// \param FunctionTemplate the function template for which we are performing
3265/// template argument deduction.
3266///
James Dennett18348b62012-06-22 08:52:37 +00003267/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003268/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003269///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003270/// \param Args the function call arguments
3271///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003272/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003273/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003274/// template argument deduction.
3275///
3276/// \param Info the argument will be updated to provide additional information
3277/// about template argument deduction.
3278///
3279/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003280Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3281 FunctionTemplateDecl *FunctionTemplate,
3282 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003283 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3284 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003285 if (FunctionTemplate->isInvalidDecl())
3286 return TDK_Invalid;
3287
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003288 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003289 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003290
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003291 // C++ [temp.deduct.call]p1:
3292 // Template argument deduction is done by comparing each function template
3293 // parameter type (call it P) with the type of the corresponding argument
3294 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003295 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003296 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003297 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003298 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003299 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003300 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003301 if (Proto->isTemplateVariadic())
3302 /* Do nothing */;
3303 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003304 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003306 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003307 }
Mike Stump11289f42009-09-09 15:08:12 +00003308
Douglas Gregor89026b52009-06-30 23:57:56 +00003309 // The types of the parameters from which we will perform template argument
3310 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003311 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312 TemplateParameterList *TemplateParams
3313 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003314 SmallVector<DeducedTemplateArgument, 4> Deduced;
3315 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003316 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003317 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003318 TemplateDeductionResult Result =
3319 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003320 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003321 Deduced,
3322 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003324 Info);
3325 if (Result)
3326 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003327
3328 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003329 } else {
3330 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003331 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003332 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3333 }
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregor89026b52009-06-30 23:57:56 +00003335 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003336 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003337 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003338 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003339 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3340 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003341 QualType OrigParamType = ParamTypes[ParamIdx];
3342 QualType ParamType = OrigParamType;
3343
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003345 = dyn_cast<PackExpansionType>(ParamType);
3346 if (!ParamExpansion) {
3347 // Simple case: matching a function parameter to a function argument.
3348 if (ArgIdx >= CheckArgs)
3349 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003350
Douglas Gregor7825bf32011-01-06 22:09:01 +00003351 Expr *Arg = Args[ArgIdx++];
3352 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003353
Douglas Gregor7825bf32011-01-06 22:09:01 +00003354 unsigned TDF = 0;
3355 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3356 ParamType, ArgType, Arg,
3357 TDF))
3358 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359
Douglas Gregor0c83c812011-10-09 22:06:46 +00003360 // If we have nothing to deduce, we're done.
3361 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3362 continue;
3363
Sebastian Redl43144e72012-01-17 22:49:58 +00003364 // If the argument is an initializer list ...
3365 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003366 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003367 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003368 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3369 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003370 continue;
3371
Hubert Tong3280b332015-06-25 00:25:49 +00003372 if (Result)
3373 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003374 // Don't track the argument type, since an initializer list has none.
3375 continue;
3376 }
3377
Douglas Gregore65aacb2011-06-16 16:50:48 +00003378 // Keep track of the argument type and corresponding parameter index,
3379 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003380 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3381 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003382
Douglas Gregor7825bf32011-01-06 22:09:01 +00003383 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003384 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3385 ParamType, ArgType,
3386 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003387 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor7825bf32011-01-06 22:09:01 +00003389 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391
Douglas Gregor7825bf32011-01-06 22:09:01 +00003392 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393 // For a function parameter pack that occurs at the end of the
3394 // parameter-declaration-list, the type A of each remaining argument of
3395 // the call is compared with the type P of the declarator-id of the
3396 // function parameter pack. Each comparison deduces template arguments
3397 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003398 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003400 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003401 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003402 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregor7825bf32011-01-06 22:09:01 +00003404 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003405 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3406 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407
Douglas Gregor7825bf32011-01-06 22:09:01 +00003408 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003409 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003410 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregore65aacb2011-06-16 16:50:48 +00003412 QualType OrigParamType = ParamPattern;
3413 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003414 Expr *Arg = Args[ArgIdx];
3415 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003416
Douglas Gregor7825bf32011-01-06 22:09:01 +00003417 unsigned TDF = 0;
3418 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3419 ParamType, ArgType, Arg,
3420 TDF)) {
3421 // We can't actually perform any deduction for this argument, so stop
3422 // deduction at this point.
3423 ++ArgIdx;
3424 break;
3425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Sebastian Redl43144e72012-01-17 22:49:58 +00003427 // As above, initializer lists need special handling.
3428 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003429 TemplateDeductionResult Result;
3430 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3431 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003432 ++ArgIdx;
3433 break;
3434 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003435
Hubert Tong3280b332015-06-25 00:25:49 +00003436 if (Result)
3437 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003438 } else {
3439
3440 // Keep track of the argument type and corresponding argument index,
3441 // so we can check for compatibility between the deduced A and A.
3442 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3443 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3444 ArgType));
3445
3446 if (TemplateDeductionResult Result
3447 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3448 ParamType, ArgType, Info,
3449 Deduced, TDF))
3450 return Result;
3451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Richard Smith0a80d572014-05-29 01:12:14 +00003453 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregor7825bf32011-01-06 22:09:01 +00003456 // Build argument packs for each of the parameter packs expanded by this
3457 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003458 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003459 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003460
Douglas Gregor7825bf32011-01-06 22:09:01 +00003461 // After we've matching against a parameter pack, we're done.
3462 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003463 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003464
Mike Stump11289f42009-09-09 15:08:12 +00003465 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003466 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003467 Info, &OriginalCallArgs,
3468 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003469}
3470
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003471QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3472 QualType FunctionType) {
3473 if (ArgFunctionType.isNull())
3474 return ArgFunctionType;
3475
3476 const FunctionProtoType *FunctionTypeP =
3477 FunctionType->castAs<FunctionProtoType>();
3478 CallingConv CC = FunctionTypeP->getCallConv();
3479 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3480 const FunctionProtoType *ArgFunctionTypeP =
3481 ArgFunctionType->getAs<FunctionProtoType>();
3482 if (ArgFunctionTypeP->getCallConv() == CC &&
3483 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3484 return ArgFunctionType;
3485
3486 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3487 EI = EI.withNoReturn(NoReturn);
3488 ArgFunctionTypeP =
3489 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3490 return QualType(ArgFunctionTypeP, 0);
3491}
3492
Douglas Gregor9b146582009-07-08 20:55:45 +00003493/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003494/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3495/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003496///
3497/// \param FunctionTemplate the function template for which we are performing
3498/// template argument deduction.
3499///
James Dennett18348b62012-06-22 08:52:37 +00003500/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003501/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003502///
3503/// \param ArgFunctionType the function type that will be used as the
3504/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003505/// function template's function type. This type may be NULL, if there is no
3506/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003507///
3508/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003509/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003510/// template argument deduction.
3511///
3512/// \param Info the argument will be updated to provide additional information
3513/// about template argument deduction.
3514///
3515/// \returns the result of template argument deduction.
3516Sema::TemplateDeductionResult
3517Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003518 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003519 QualType ArgFunctionType,
3520 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003521 TemplateDeductionInfo &Info,
3522 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003523 if (FunctionTemplate->isInvalidDecl())
3524 return TDK_Invalid;
3525
Douglas Gregor9b146582009-07-08 20:55:45 +00003526 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3527 TemplateParameterList *TemplateParams
3528 = FunctionTemplate->getTemplateParameters();
3529 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003530 if (!InOverloadResolution)
3531 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003532
Douglas Gregor9b146582009-07-08 20:55:45 +00003533 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003534 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003535 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003536 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003537 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003538 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003539 if (TemplateDeductionResult Result
3540 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003541 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003542 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003543 &FunctionType, Info))
3544 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003545
3546 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003547 }
3548
Eli Friedman77dcc722012-02-08 03:07:05 +00003549 // Unevaluated SFINAE context.
3550 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003551 SFINAETrap Trap(*this);
3552
John McCallc1f69982010-02-02 02:21:27 +00003553 Deduced.resize(TemplateParams->size());
3554
Richard Smith2a7d4812013-05-04 07:00:32 +00003555 // If the function has a deduced return type, substitute it for a dependent
3556 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003557 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003558 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003559 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003560 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003561 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003562 }
3563
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003564 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003565 unsigned TDF = TDF_TopLevelParameterTypeList;
3566 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003567 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003568 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003569 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003570 FunctionType, ArgFunctionType,
3571 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003572 return Result;
3573 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003576 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3577 NumExplicitlySpecified,
3578 Specialization, Info))
3579 return Result;
3580
Richard Smith2a7d4812013-05-04 07:00:32 +00003581 // If the function has a deduced return type, deduce it now, so we can check
3582 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003583 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003584 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003585 DeduceReturnType(Specialization, Info.getLocation(), false))
3586 return TDK_MiscellaneousDeductionFailure;
3587
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003588 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003589 // specialization with respect to arguments of compatible pointer to function
3590 // types, template argument deduction fails.
3591 if (!ArgFunctionType.isNull()) {
3592 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3593 Context.getCanonicalType(Specialization->getType()),
3594 Context.getCanonicalType(ArgFunctionType)))
3595 return TDK_MiscellaneousDeductionFailure;
3596 else if(!InOverloadResolution &&
3597 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3598 return TDK_MiscellaneousDeductionFailure;
3599 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003600
3601 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003602}
3603
Faisal Vali850da1a2013-09-29 17:08:32 +00003604/// \brief Given a function declaration (e.g. a generic lambda conversion
3605/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003606/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3607/// to replace 'auto' with and not the actual result type you want
3608/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003609static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003610SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003611 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003612 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003613 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003614 assert(AutoResultType->getContainedAutoType());
3615 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003616 TypeToReplaceAutoWith);
3617 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3618}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003619
3620/// \brief Given a specialized conversion operator of a generic lambda
3621/// create the corresponding specializations of the call operator and
3622/// the static-invoker. If the return type of the call operator is auto,
3623/// deduce its return type and check if that matches the
3624/// return type of the destination function ptr.
3625
3626static inline Sema::TemplateDeductionResult
3627SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3628 CXXConversionDecl *ConversionSpecialized,
3629 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3630 QualType ReturnTypeOfDestFunctionPtr,
3631 TemplateDeductionInfo &TDInfo,
3632 Sema &S) {
3633
3634 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3635 assert(LambdaClass && LambdaClass->isGenericLambda());
3636
3637 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003638 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003639 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3640 CallOpResultType->getContainedAutoType();
3641
3642 FunctionTemplateDecl *CallOpTemplate =
3643 CallOpGeneric->getDescribedFunctionTemplate();
3644
Craig Topperc3ec1492014-05-26 06:22:03 +00003645 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003646 // Use the deduced arguments of the conversion function, to specialize our
3647 // generic lambda's call operator.
3648 if (Sema::TemplateDeductionResult Result
3649 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3650 DeducedArguments,
3651 0, CallOpSpecialized, TDInfo))
3652 return Result;
3653
3654 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003655 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3656 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003657 S.DeduceReturnType(CallOpSpecialized,
3658 CallOpSpecialized->getPointOfInstantiation(),
3659 /*Diagnose*/ true);
3660
3661 // Check to see if the return type of the destination ptr-to-function
3662 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003663 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003664 ReturnTypeOfDestFunctionPtr))
3665 return Sema::TDK_NonDeducedMismatch;
3666 // Since we have succeeded in matching the source and destination
3667 // ptr-to-functions (now including return type), and have successfully
3668 // specialized our corresponding call operator, we are ready to
3669 // specialize the static invoker with the deduced arguments of our
3670 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003671 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003672 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3673 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3674
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003675#ifndef NDEBUG
3676 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3677#endif
3678 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003679 InvokerSpecialized, TDInfo);
3680 assert(Result == Sema::TDK_Success &&
3681 "If the call operator succeeded so should the invoker!");
3682 // Set the result type to match the corresponding call operator
3683 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003684 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3685 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003686 // Be sure to get the type to replace 'auto' with and not
3687 // the full result type of the call op specialization
3688 // to substitute into the 'auto' of the invoker and conversion
3689 // function.
3690 // For e.g.
3691 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3692 // We don't want to subst 'int*' into 'auto' to get int**.
3693
Alp Toker314cc812014-01-25 16:55:45 +00003694 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3695 ->getContainedAutoType()
3696 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003697 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3698 TypeToReplaceAutoWith, S);
3699 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3700 TypeToReplaceAutoWith, S);
3701 }
3702
3703 // Ensure that static invoker doesn't have a const qualifier.
3704 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3705 // do not use the CallOperator's TypeSourceInfo which allows
3706 // the const qualifier to leak through.
3707 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3708 getType().getTypePtr()->castAs<FunctionProtoType>();
3709 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3710 EPI.TypeQuals = 0;
3711 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003712 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003713 return Sema::TDK_Success;
3714}
Douglas Gregor05155d82009-08-21 23:19:43 +00003715/// \brief Deduce template arguments for a templated conversion
3716/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3717/// conversion function template specialization.
3718Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003719Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003720 QualType ToType,
3721 CXXConversionDecl *&Specialization,
3722 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003723 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003724 return TDK_Invalid;
3725
Faisal Vali2b3a3012013-10-24 23:40:02 +00003726 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003727 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3728
Faisal Vali2b3a3012013-10-24 23:40:02 +00003729 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003730
3731 // Canonicalize the types for deduction.
3732 QualType P = Context.getCanonicalType(FromType);
3733 QualType A = Context.getCanonicalType(ToType);
3734
Douglas Gregord99609a2011-03-06 09:03:20 +00003735 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003736 // If P is a reference type, the type referred to by P is used for
3737 // type deduction.
3738 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3739 P = PRef->getPointeeType();
3740
Douglas Gregord99609a2011-03-06 09:03:20 +00003741 // C++0x [temp.deduct.conv]p4:
3742 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003743 // for type deduction.
3744 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003745 A = ARef->getPointeeType().getUnqualifiedType();
3746 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003747 //
Mike Stump11289f42009-09-09 15:08:12 +00003748 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003749 else {
3750 assert(!A->isReferenceType() && "Reference types were handled above");
3751
3752 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003753 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003754 // of P for type deduction; otherwise,
3755 if (P->isArrayType())
3756 P = Context.getArrayDecayedType(P);
3757 // - If P is a function type, the pointer type produced by the
3758 // function-to-pointer standard conversion (4.3) is used in
3759 // place of P for type deduction; otherwise,
3760 else if (P->isFunctionType())
3761 P = Context.getPointerType(P);
3762 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003763 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003764 else
3765 P = P.getUnqualifiedType();
3766
Douglas Gregord99609a2011-03-06 09:03:20 +00003767 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003768 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003769 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003770 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003771 A = A.getUnqualifiedType();
3772 }
3773
Eli Friedman77dcc722012-02-08 03:07:05 +00003774 // Unevaluated SFINAE context.
3775 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003776 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003777
3778 // C++ [temp.deduct.conv]p1:
3779 // Template argument deduction is done by comparing the return
3780 // type of the template conversion function (call it P) with the
3781 // type that is required as the result of the conversion (call it
3782 // A) as described in 14.8.2.4.
3783 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003784 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003785 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003786 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003787
3788 // C++0x [temp.deduct.conv]p4:
3789 // In general, the deduction process attempts to find template
3790 // argument values that will make the deduced A identical to
3791 // A. However, there are two cases that allow a difference:
3792 unsigned TDF = 0;
3793 // - If the original A is a reference type, A can be more
3794 // cv-qualified than the deduced A (i.e., the type referred to
3795 // by the reference)
3796 if (ToType->isReferenceType())
3797 TDF |= TDF_ParamWithReferenceType;
3798 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003799 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003800 // conversion.
3801 //
3802 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3803 // both P and A are pointers or member pointers. In this case, we
3804 // just ignore cv-qualifiers completely).
3805 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003806 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003807 TDF |= TDF_IgnoreQualifiers;
3808 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003809 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3810 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003811 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003812
3813 // Create an Instantiation Scope for finalizing the operator.
3814 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003815 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003816 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003817 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003818 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3819 ConversionSpecialized, Info);
3820 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3821
3822 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003823 // to a ptr-to-function, use the deduced arguments from the conversion
3824 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003825 // e.g., int (*fp)(int) = [](auto a) { return a; };
3826 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3827
3828 // Get the return type of the destination ptr-to-function we are converting
3829 // to. This is necessary for matching the lambda call operator's return
3830 // type to that of the destination ptr-to-function's return type.
3831 assert(A->isPointerType() &&
3832 "Can only convert from lambda to ptr-to-function");
3833 const FunctionType *ToFunType =
3834 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003835 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3836
Faisal Vali2b3a3012013-10-24 23:40:02 +00003837 // Create the corresponding specializations of the call operator and
3838 // the static-invoker; and if the return type is auto,
3839 // deduce the return type and check if it matches the
3840 // DestFunctionPtrReturnType.
3841 // For instance:
3842 // auto L = [](auto a) { return f(a); };
3843 // int (*fp)(int) = L;
3844 // char (*fp2)(int) = L; <-- Not OK.
3845
3846 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3847 Specialization, Deduced, DestFunctionPtrReturnType,
3848 Info, *this);
3849 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003850 return Result;
3851}
3852
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003853/// \brief Deduce template arguments for a function template when there is
3854/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3855///
3856/// \param FunctionTemplate the function template for which we are performing
3857/// template argument deduction.
3858///
James Dennett18348b62012-06-22 08:52:37 +00003859/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003860/// arguments.
3861///
3862/// \param Specialization if template argument deduction was successful,
3863/// this will be set to the function template specialization produced by
3864/// template argument deduction.
3865///
3866/// \param Info the argument will be updated to provide additional information
3867/// about template argument deduction.
3868///
3869/// \returns the result of template argument deduction.
3870Sema::TemplateDeductionResult
3871Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003872 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003873 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003874 TemplateDeductionInfo &Info,
3875 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003876 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003877 QualType(), Specialization, Info,
3878 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003879}
3880
Richard Smith30482bc2011-02-20 03:19:35 +00003881namespace {
3882 /// Substitute the 'auto' type specifier within a type for a given replacement
3883 /// type.
3884 class SubstituteAutoTransform :
3885 public TreeTransform<SubstituteAutoTransform> {
3886 QualType Replacement;
3887 public:
Nico Weberc153d242014-07-28 00:02:09 +00003888 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3889 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3890 Replacement(Replacement) {}
3891
Richard Smith30482bc2011-02-20 03:19:35 +00003892 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3893 // If we're building the type pattern to deduce against, don't wrap the
3894 // substituted type in an AutoType. Certain template deduction rules
3895 // apply only when a template type parameter appears directly (and not if
3896 // the parameter is found through desugaring). For instance:
3897 // auto &&lref = lvalue;
3898 // must transform into "rvalue reference to T" not "rvalue reference to
3899 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003900 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003901 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003902 TemplateTypeParmTypeLoc NewTL =
3903 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003904 NewTL.setNameLoc(TL.getNameLoc());
3905 return Result;
3906 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003907 bool Dependent =
3908 !Replacement.isNull() && Replacement->isDependentType();
3909 QualType Result =
3910 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3911 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003912 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003913 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3914 NewTL.setNameLoc(TL.getNameLoc());
3915 return Result;
3916 }
3917 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003918
3919 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3920 // Lambdas never need to be transformed.
3921 return E;
3922 }
Richard Smith061f1e22013-04-30 21:23:01 +00003923
Richard Smith2a7d4812013-05-04 07:00:32 +00003924 QualType Apply(TypeLoc TL) {
3925 // Create some scratch storage for the transformed type locations.
3926 // FIXME: We're just going to throw this information away. Don't build it.
3927 TypeLocBuilder TLB;
3928 TLB.reserve(TL.getFullDataSize());
3929 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003930 }
Richard Smith30482bc2011-02-20 03:19:35 +00003931 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003932}
Richard Smith30482bc2011-02-20 03:19:35 +00003933
Richard Smith2a7d4812013-05-04 07:00:32 +00003934Sema::DeduceAutoResult
3935Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3936 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3937}
3938
Richard Smith061f1e22013-04-30 21:23:01 +00003939/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003940///
3941/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003942/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003943/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003944/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003945Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003946Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003947 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003948 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3949 if (NonPlaceholder.isInvalid())
3950 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003951 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003952 }
3953
Richard Smith2a7d4812013-05-04 07:00:32 +00003954 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003955 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003956 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003957 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003958 }
3959
Richard Smith74aeef52013-04-26 16:15:35 +00003960 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3961 // Since 'decltype(auto)' can only occur at the top of the type, we
3962 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003963 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003964 if (AT->isDecltypeAuto()) {
3965 if (isa<InitListExpr>(Init)) {
3966 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3967 return DAR_FailedAlreadyDiagnosed;
3968 }
3969
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003970 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00003971 if (Deduced.isNull())
3972 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003973 // FIXME: Support a non-canonical deduced type for 'auto'.
3974 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003975 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 if (Result.isNull())
3977 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003978 return DAR_Succeeded;
3979 }
3980 }
3981
Richard Smith30482bc2011-02-20 03:19:35 +00003982 SourceLocation Loc = Init->getExprLoc();
3983
3984 LocalInstantiationScope InstScope(*this);
3985
3986 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00003987 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00003988 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
3989 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00003990 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
3991 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00003992 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
3993 Loc);
3994
Richard Smith061f1e22013-04-30 21:23:01 +00003995 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
3996 assert(!FuncParam.isNull() &&
3997 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00003998
3999 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004000 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004001 Deduced.resize(1);
4002 QualType InitType = Init->getType();
4003 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004004
Craig Toppere6706e42012-09-19 02:26:47 +00004005 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004006
Richard Smith74801c82012-07-08 04:13:07 +00004007 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004008 if (InitList) {
4009 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00004010 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004011 TemplArg,
4012 InitList->getInit(i),
4013 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004014 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004015 }
4016 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004017 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
4018 FuncParam, InitType, Init,
4019 TDF))
4020 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004021
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004022 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4023 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004024 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004025 }
Richard Smith30482bc2011-02-20 03:19:35 +00004026
Eli Friedmane4310952012-11-06 23:56:42 +00004027 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004028 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004029
Eli Friedmane4310952012-11-06 23:56:42 +00004030 QualType DeducedType = Deduced[0].getAsType();
4031
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004032 if (InitList) {
4033 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4034 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004035 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004036 }
4037
Richard Smith061f1e22013-04-30 21:23:01 +00004038 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004039 if (Result.isNull())
4040 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004041
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004042 // Check that the deduced argument type is compatible with the original
4043 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004044 if (!InitList && !Result.isNull() &&
4045 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004046 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004047 Result)) {
4048 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004049 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004050 }
4051
Sebastian Redl09edce02012-01-23 22:09:39 +00004052 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004053}
4054
Faisal Vali2b391ab2013-09-26 19:54:12 +00004055QualType Sema::SubstAutoType(QualType TypeWithAuto,
4056 QualType TypeToReplaceAuto) {
4057 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4058 TransformType(TypeWithAuto);
4059}
4060
4061TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4062 QualType TypeToReplaceAuto) {
4063 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4064 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004065}
4066
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004067void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4068 if (isa<InitListExpr>(Init))
4069 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004070 VDecl->isInitCapture()
4071 ? diag::err_init_capture_deduction_failure_from_init_list
4072 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004073 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4074 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004075 Diag(VDecl->getLocation(),
4076 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4077 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004078 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4079 << Init->getSourceRange();
4080}
4081
Richard Smith2a7d4812013-05-04 07:00:32 +00004082bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4083 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004084 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004085
4086 if (FD->getTemplateInstantiationPattern())
4087 InstantiateFunctionDefinition(Loc, FD);
4088
Alp Toker314cc812014-01-25 16:55:45 +00004089 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004090 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4091 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4092 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4093 }
4094
4095 return StillUndeduced;
4096}
4097
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004098static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004099MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004100 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004101 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004102 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
4104/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004105static void
4106AddImplicitObjectParameterType(ASTContext &Context,
4107 CXXMethodDecl *Method,
4108 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004109 // C++11 [temp.func.order]p3:
4110 // [...] The new parameter is of type "reference to cv A," where cv are
4111 // the cv-qualifiers of the function template (if any) and A is
4112 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004113 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004114 // The standard doesn't say explicitly, but we pick the appropriate kind of
4115 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004116 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4117 ArgTy = Context.getQualifiedType(ArgTy,
4118 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004119 if (Method->getRefQualifier() == RQ_RValue)
4120 ArgTy = Context.getRValueReferenceType(ArgTy);
4121 else
4122 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004123 ArgTypes.push_back(ArgTy);
4124}
4125
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004126/// \brief Determine whether the function template \p FT1 is at least as
4127/// specialized as \p FT2.
4128static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004129 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004130 FunctionTemplateDecl *FT1,
4131 FunctionTemplateDecl *FT2,
4132 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004133 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004134 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004136 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4137 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004139 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4140 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004141 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004142 Deduced.resize(TemplateParams->size());
4143
4144 // C++0x [temp.deduct.partial]p3:
4145 // The types used to determine the ordering depend on the context in which
4146 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004147 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004148 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004149 switch (TPOC) {
4150 case TPOC_Call: {
4151 // - In the context of a function call, the function parameter types are
4152 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004153 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4154 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004155
Eli Friedman3b5774a2012-09-19 23:27:04 +00004156 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004157 // [...] If only one of the function templates is a non-static
4158 // member, that function template is considered to have a new
4159 // first parameter inserted in its function parameter list. The
4160 // new parameter is of type "reference to cv A," where cv are
4161 // the cv-qualifiers of the function template (if any) and A is
4162 // the class of which the function template is a member.
4163 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004164 // Note that we interpret this to mean "if one of the function
4165 // templates is a non-static member and the other is a non-member";
4166 // otherwise, the ordering rules for static functions against non-static
4167 // functions don't make any sense.
4168 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004169 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4170 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004171 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004172
Richard Smithe5b52202013-09-11 00:52:39 +00004173 unsigned NumComparedArguments = NumCallArguments1;
4174
4175 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004176 // Compare 'this' from Method1 against first parameter from Method2.
4177 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4178 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004179 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004180 // Compare 'this' from Method2 against first parameter from Method1.
4181 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004182 }
4183
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004184 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004185 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004186 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004187 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
Douglas Gregorb837ea42011-01-11 17:34:58 +00004189 // C++ [temp.func.order]p5:
4190 // The presence of unused ellipsis and default arguments has no effect on
4191 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004192 if (Args1.size() > NumComparedArguments)
4193 Args1.resize(NumComparedArguments);
4194 if (Args2.size() > NumComparedArguments)
4195 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004196 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4197 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004198 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004199 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004201 break;
4202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004204 case TPOC_Conversion:
4205 // - In the context of a call to a conversion operator, the return types
4206 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004207 if (DeduceTemplateArgumentsByTypeMatch(
4208 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4209 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004210 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004211 return false;
4212 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004214 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004215 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004216 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004217 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4218 FD2->getType(), FD1->getType(),
4219 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004220 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004221 return false;
4222 break;
4223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004225 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226 // In most cases, all template parameters must have values in order for
4227 // deduction to succeed, but for partial ordering purposes a template
4228 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004229 // types being used for partial ordering. [ Note: a template parameter used
4230 // in a non-deduced context is considered used. -end note]
4231 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4232 for (; ArgIdx != NumArgs; ++ArgIdx)
4233 if (Deduced[ArgIdx].isNull())
4234 break;
4235
4236 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004238 // as FT2.
4239 return true;
4240 }
4241
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004242 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004243 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004244 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004245 case TPOC_Call:
4246 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4247 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004248 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004249 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004250 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004252 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004253 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4254 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004255 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004256
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004257 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004258 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004259 TemplateParams->getDepth(),
4260 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004261 break;
4262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004264 for (; ArgIdx != NumArgs; ++ArgIdx)
4265 // If this argument had no value deduced but was used in one of the types
4266 // used for partial ordering, then deduction fails.
4267 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4268 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004270 return true;
4271}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Douglas Gregorcef1a032011-01-16 16:03:23 +00004273/// \brief Determine whether this a function template whose parameter-type-list
4274/// ends with a function parameter pack.
4275static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4276 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4277 unsigned NumParams = Function->getNumParams();
4278 if (NumParams == 0)
4279 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280
Douglas Gregorcef1a032011-01-16 16:03:23 +00004281 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4282 if (!Last->isParameterPack())
4283 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregorcef1a032011-01-16 16:03:23 +00004285 // Make sure that no previous parameter is a parameter pack.
4286 while (--NumParams > 0) {
4287 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4288 return false;
4289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
Douglas Gregorcef1a032011-01-16 16:03:23 +00004291 return true;
4292}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregorbe999392009-09-15 16:23:51 +00004294/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004295/// to the rules of function template partial ordering (C++ [temp.func.order]).
4296///
4297/// \param FT1 the first function template
4298///
4299/// \param FT2 the second function template
4300///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004301/// \param TPOC the context in which we are performing partial ordering of
4302/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004303///
Richard Smithe5b52202013-09-11 00:52:39 +00004304/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4305/// only when \c TPOC is \c TPOC_Call.
4306///
4307/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4308/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004309///
Douglas Gregorbe999392009-09-15 16:23:51 +00004310/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004311/// template is more specialized, returns NULL.
4312FunctionTemplateDecl *
4313Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4314 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004315 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004316 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004317 unsigned NumCallArguments1,
4318 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004320 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004322 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004324 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004325 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004328 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004329
Douglas Gregorcef1a032011-01-16 16:03:23 +00004330 // FIXME: This mimics what GCC implements, but doesn't match up with the
4331 // proposed resolution for core issue 692. This area needs to be sorted out,
4332 // but for now we attempt to maintain compatibility.
4333 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4334 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4335 if (Variadic1 != Variadic2)
4336 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
Craig Topperc3ec1492014-05-26 06:22:03 +00004338 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004339}
Douglas Gregor9b146582009-07-08 20:55:45 +00004340
Douglas Gregor450f00842009-09-25 18:43:00 +00004341/// \brief Determine if the two templates are equivalent.
4342static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4343 if (T1 == T2)
4344 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
Douglas Gregor450f00842009-09-25 18:43:00 +00004346 if (!T1 || !T2)
4347 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
Douglas Gregor450f00842009-09-25 18:43:00 +00004349 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4350}
4351
4352/// \brief Retrieve the most specialized of the given function template
4353/// specializations.
4354///
John McCall58cc69d2010-01-27 01:50:18 +00004355/// \param SpecBegin the start iterator of the function template
4356/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004357///
John McCall58cc69d2010-01-27 01:50:18 +00004358/// \param SpecEnd the end iterator of the function template
4359/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004360///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004362/// diagnostic should occur.
4363///
4364/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4365/// no matching candidates.
4366///
4367/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4368/// occurs.
4369///
4370/// \param CandidateDiag partial diagnostic used for each function template
4371/// specialization that is a candidate in the ambiguous ordering. One parameter
4372/// in this diagnostic should be unbound, which will correspond to the string
4373/// describing the template arguments for the function template specialization.
4374///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004376/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004377UnresolvedSetIterator Sema::getMostSpecialized(
4378 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4379 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004380 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4381 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4382 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004383 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004384 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004385 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004386 FailedCandidates.NoteCandidates(*this, Loc);
4387 }
John McCall58cc69d2010-01-27 01:50:18 +00004388 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
4391 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004392 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393
Douglas Gregor450f00842009-09-25 18:43:00 +00004394 // Find the function template that is better than all of the templates it
4395 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004396 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004398 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004399 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004400 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4401 FunctionTemplateDecl *Challenger
4402 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004403 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004404 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004405 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004406 Challenger)) {
4407 Best = I;
4408 BestTemplate = Challenger;
4409 }
4410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregor450f00842009-09-25 18:43:00 +00004412 // Make sure that the "best" function template is more specialized than all
4413 // of the others.
4414 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004415 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4416 FunctionTemplateDecl *Challenger
4417 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004418 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004420 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004421 BestTemplate)) {
4422 Ambiguous = true;
4423 break;
4424 }
4425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
Douglas Gregor450f00842009-09-25 18:43:00 +00004427 if (!Ambiguous) {
4428 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004429 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregor450f00842009-09-25 18:43:00 +00004432 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004433 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004434 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435
Richard Smithb875c432013-05-04 01:51:08 +00004436 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004437 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4438 PartialDiagnostic PD = CandidateDiag;
4439 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004440 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004441 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004442 if (!TargetType.isNull())
4443 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4444 TargetType);
4445 Diag((*I)->getLocation(), PD);
4446 }
Richard Smithb875c432013-05-04 01:51:08 +00004447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448
John McCall58cc69d2010-01-27 01:50:18 +00004449 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004450}
4451
Douglas Gregorbe999392009-09-15 16:23:51 +00004452/// \brief Returns the more specialized class template partial specialization
4453/// according to the rules of partial ordering of class template partial
4454/// specializations (C++ [temp.class.order]).
4455///
4456/// \param PS1 the first class template partial specialization
4457///
4458/// \param PS2 the second class template partial specialization
4459///
4460/// \returns the more specialized class template partial specialization. If
4461/// neither partial specialization is more specialized, returns NULL.
4462ClassTemplatePartialSpecializationDecl *
4463Sema::getMoreSpecializedPartialSpecialization(
4464 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004465 ClassTemplatePartialSpecializationDecl *PS2,
4466 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004467 // C++ [temp.class.order]p1:
4468 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469 // specialized as the second if, given the following rewrite to two
4470 // function templates, the first function template is at least as
4471 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004472 // templates (14.6.6.2):
4473 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474 // first partial specialization and has a single function parameter
4475 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004476 // arguments of the first partial specialization, and
4477 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478 // second partial specialization and has a single function parameter
4479 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004480 // arguments of the second partial specialization.
4481 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004482 // Rather than synthesize function templates, we merely perform the
4483 // equivalent partial ordering by performing deduction directly on
4484 // the template arguments of the class template partial
4485 // specializations. This computation is slightly simpler than the
4486 // general problem of function template partial ordering, because
4487 // class template partial specializations are more constrained. We
4488 // know that every template parameter is deducible from the class
4489 // template partial specialization's template arguments, for
4490 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004491 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004492 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004493
4494 QualType PT1 = PS1->getInjectedSpecializationType();
4495 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
Douglas Gregorbe999392009-09-15 16:23:51 +00004497 // Determine whether PS1 is at least as specialized as PS2
4498 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004499 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4500 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004501 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004502 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004503 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004504 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004505 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004506 Better1 = !::FinishTemplateArgumentDeduction(
4507 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4508 }
4509
4510 // Determine whether PS2 is at least as specialized as PS1
4511 Deduced.clear();
4512 Deduced.resize(PS1->getTemplateParameters()->size());
4513 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4514 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004515 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004516 if (Better2) {
4517 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4518 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004519 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004520 Better2 = !::FinishTemplateArgumentDeduction(
4521 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4522 }
4523
4524 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004525 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004526
4527 return Better1 ? PS1 : PS2;
4528}
4529
Larisse Voufo30616382013-08-23 22:21:36 +00004530/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4531/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4532/// VarTemplate(Partial)SpecializationDecl with a new data
4533/// structure Template(Partial)SpecializationDecl, and
4534/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004535VarTemplatePartialSpecializationDecl *
4536Sema::getMoreSpecializedPartialSpecialization(
4537 VarTemplatePartialSpecializationDecl *PS1,
4538 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4539 SmallVector<DeducedTemplateArgument, 4> Deduced;
4540 TemplateDeductionInfo Info(Loc);
4541
Richard Smithf04fd0b2013-12-12 23:14:16 +00004542 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004543 "the partial specializations being compared should specialize"
4544 " the same template.");
4545 TemplateName Name(PS1->getSpecializedTemplate());
4546 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4547 QualType PT1 = Context.getTemplateSpecializationType(
4548 CanonTemplate, PS1->getTemplateArgs().data(),
4549 PS1->getTemplateArgs().size());
4550 QualType PT2 = Context.getTemplateSpecializationType(
4551 CanonTemplate, PS2->getTemplateArgs().data(),
4552 PS2->getTemplateArgs().size());
4553
4554 // Determine whether PS1 is at least as specialized as PS2
4555 Deduced.resize(PS2->getTemplateParameters()->size());
4556 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4557 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004558 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004559 if (Better1) {
4560 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4561 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004562 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4564 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004565 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004566 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567
Douglas Gregorbe999392009-09-15 16:23:51 +00004568 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004569 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004570 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004571 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4572 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004573 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004574 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004575 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004576 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004577 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4579 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004580 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582
Douglas Gregorbe999392009-09-15 16:23:51 +00004583 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004584 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Douglas Gregorbe999392009-09-15 16:23:51 +00004586 return Better1? PS1 : PS2;
4587}
4588
Mike Stump11289f42009-09-09 15:08:12 +00004589static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004590MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004591 const TemplateArgument &TemplateArg,
4592 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004593 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004594 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004595
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004596/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004597/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004598static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004599MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004600 const Expr *E,
4601 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004602 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004603 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004604 // We can deduce from a pack expansion.
4605 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4606 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607
Richard Smith34349002012-07-09 03:07:20 +00004608 // Skip through any implicit casts we added while type-checking, and any
4609 // substitutions performed by template alias expansion.
4610 while (1) {
4611 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4612 E = ICE->getSubExpr();
4613 else if (const SubstNonTypeTemplateParmExpr *Subst =
4614 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4615 E = Subst->getReplacement();
4616 else
4617 break;
4618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619
4620 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004621 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004622 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004623 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004624 return;
4625
Mike Stump11289f42009-09-09 15:08:12 +00004626 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004627 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4628 if (!NTTP)
4629 return;
4630
Douglas Gregor21610382009-10-29 00:04:11 +00004631 if (NTTP->getDepth() == Depth)
4632 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004633}
4634
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004635/// \brief Mark the template parameters that are used by the given
4636/// nested name specifier.
4637static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004638MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004639 NestedNameSpecifier *NNS,
4640 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004641 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004642 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004643 if (!NNS)
4644 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004646 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004647 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004648 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004649 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004650}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004651
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004652/// \brief Mark the template parameters that are used by the given
4653/// template name.
4654static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004655MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004656 TemplateName Name,
4657 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004658 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004659 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004660 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4661 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004662 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4663 if (TTP->getDepth() == Depth)
4664 Used[TTP->getIndex()] = true;
4665 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004666 return;
4667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004669 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004670 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004671 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004672 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004673 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004674 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004675}
4676
4677/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004678/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004679static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004680MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004681 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004682 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004683 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004684 if (T.isNull())
4685 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
Douglas Gregor91772d12009-06-13 00:26:55 +00004687 // Non-dependent types have nothing deducible
4688 if (!T->isDependentType())
4689 return;
4690
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004691 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004692 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004693 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004694 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004695 cast<PointerType>(T)->getPointeeType(),
4696 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004697 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004698 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004699 break;
4700
4701 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004702 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004703 cast<BlockPointerType>(T)->getPointeeType(),
4704 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004705 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004706 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004707 break;
4708
4709 case Type::LValueReference:
4710 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004711 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004712 cast<ReferenceType>(T)->getPointeeType(),
4713 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004714 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004715 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004716 break;
4717
4718 case Type::MemberPointer: {
4719 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004720 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004721 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004722 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004723 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004724 break;
4725 }
4726
4727 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004728 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004729 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004730 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004731 // Fall through to check the element type
4732
4733 case Type::ConstantArray:
4734 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004735 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004736 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004737 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004738 break;
4739
4740 case Type::Vector:
4741 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004742 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004743 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004744 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004745 break;
4746
Douglas Gregor758a8692009-06-17 21:51:59 +00004747 case Type::DependentSizedExtVector: {
4748 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004749 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004750 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004751 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004752 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004753 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004754 break;
4755 }
4756
Douglas Gregor91772d12009-06-13 00:26:55 +00004757 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004758 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004759 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4760 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004761 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4762 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004763 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004764 break;
4765 }
4766
Douglas Gregor21610382009-10-29 00:04:11 +00004767 case Type::TemplateTypeParm: {
4768 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4769 if (TTP->getDepth() == Depth)
4770 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004771 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004772 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004773
Douglas Gregorfb322d82011-01-14 05:11:40 +00004774 case Type::SubstTemplateTypeParmPack: {
4775 const SubstTemplateTypeParmPackType *Subst
4776 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004777 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004778 QualType(Subst->getReplacedParameter(), 0),
4779 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004780 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004781 OnlyDeduced, Depth, Used);
4782 break;
4783 }
4784
John McCall2408e322010-04-27 00:57:59 +00004785 case Type::InjectedClassName:
4786 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4787 // fall through
4788
Douglas Gregor91772d12009-06-13 00:26:55 +00004789 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004790 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004791 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004792 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004793 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Douglas Gregord0ad2942010-12-23 01:24:45 +00004795 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004796 // If the template argument list of P contains a pack expansion that is
4797 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004798 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004800 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4801 break;
4802
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004803 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004804 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004805 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004806 break;
4807 }
4808
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004809 case Type::Complex:
4810 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004811 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004812 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004813 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004814 break;
4815
Eli Friedman0dfb8892011-10-06 23:00:33 +00004816 case Type::Atomic:
4817 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004818 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004819 cast<AtomicType>(T)->getValueType(),
4820 OnlyDeduced, Depth, Used);
4821 break;
4822
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004823 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004824 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004825 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004826 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004827 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004828 break;
4829
John McCallc392f372010-06-11 00:33:02 +00004830 case Type::DependentTemplateSpecialization: {
4831 const DependentTemplateSpecializationType *Spec
4832 = cast<DependentTemplateSpecializationType>(T);
4833 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004834 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004835 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836
Douglas Gregord0ad2942010-12-23 01:24:45 +00004837 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838 // If the template argument list of P contains a pack expansion that is not
4839 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004840 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004842 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4843 break;
4844
John McCallc392f372010-06-11 00:33:02 +00004845 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004846 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004847 Used);
4848 break;
4849 }
4850
John McCallbd8d9bd2010-03-01 23:49:17 +00004851 case Type::TypeOf:
4852 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004853 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004854 cast<TypeOfType>(T)->getUnderlyingType(),
4855 OnlyDeduced, Depth, Used);
4856 break;
4857
4858 case Type::TypeOfExpr:
4859 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004860 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004861 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4862 OnlyDeduced, Depth, Used);
4863 break;
4864
4865 case Type::Decltype:
4866 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004867 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004868 cast<DecltypeType>(T)->getUnderlyingExpr(),
4869 OnlyDeduced, Depth, Used);
4870 break;
4871
Alexis Hunte852b102011-05-24 22:41:36 +00004872 case Type::UnaryTransform:
4873 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004875 cast<UnaryTransformType>(T)->getUnderlyingType(),
4876 OnlyDeduced, Depth, Used);
4877 break;
4878
Douglas Gregord2fa7662010-12-20 02:24:11 +00004879 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004880 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004881 cast<PackExpansionType>(T)->getPattern(),
4882 OnlyDeduced, Depth, Used);
4883 break;
4884
Richard Smith30482bc2011-02-20 03:19:35 +00004885 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004886 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004887 cast<AutoType>(T)->getDeducedType(),
4888 OnlyDeduced, Depth, Used);
4889
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004890 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004891 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004892 case Type::VariableArray:
4893 case Type::FunctionNoProto:
4894 case Type::Record:
4895 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004896 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004897 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004898 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004899 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004900#define TYPE(Class, Base)
4901#define ABSTRACT_TYPE(Class, Base)
4902#define DEPENDENT_TYPE(Class, Base)
4903#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4904#include "clang/AST/TypeNodes.def"
4905 break;
4906 }
4907}
4908
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004909/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004910/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004911static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004912MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004913 const TemplateArgument &TemplateArg,
4914 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004915 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004916 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004917 switch (TemplateArg.getKind()) {
4918 case TemplateArgument::Null:
4919 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004920 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004921 break;
Mike Stump11289f42009-09-09 15:08:12 +00004922
Eli Friedmanb826a002012-09-26 02:36:12 +00004923 case TemplateArgument::NullPtr:
4924 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4925 Depth, Used);
4926 break;
4927
Douglas Gregor91772d12009-06-13 00:26:55 +00004928 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004929 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004930 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004931 break;
4932
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004933 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004934 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004937 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004938 break;
4939
4940 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004941 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004942 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004943 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
Anders Carlssonbc343912009-06-15 17:04:53 +00004945 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00004946 for (const auto &P : TemplateArg.pack_elements())
4947 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00004948 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00004949 }
4950}
4951
James Dennett41725122012-06-22 10:16:05 +00004952/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00004953/// template argument list.
4954///
4955/// \param TemplateArgs the template argument list from which template
4956/// parameters will be deduced.
4957///
James Dennett41725122012-06-22 10:16:05 +00004958/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00004959/// to indicate when the corresponding template parameter will be
4960/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00004961void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004962Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00004963 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004964 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00004965 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966 // If the template argument list of P contains a pack expansion that is not
4967 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004968 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004970 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
4971 return;
4972
Douglas Gregor91772d12009-06-13 00:26:55 +00004973 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004974 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004975 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004976}
Douglas Gregorce23bae2009-09-18 23:21:38 +00004977
4978/// \brief Marks all of the template parameters that will be deduced by a
4979/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00004980void Sema::MarkDeducedTemplateParameters(
4981 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
4982 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00004984 = FunctionTemplate->getTemplateParameters();
4985 Deduced.clear();
4986 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987
Douglas Gregorce23bae2009-09-18 23:21:38 +00004988 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4989 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004990 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004991 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00004992}
Douglas Gregore65aacb2011-06-16 16:50:48 +00004993
4994bool hasDeducibleTemplateParameters(Sema &S,
4995 FunctionTemplateDecl *FunctionTemplate,
4996 QualType T) {
4997 if (!T->isDependentType())
4998 return false;
4999
5000 TemplateParameterList *TemplateParams
5001 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005002 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005003 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005004 Deduced);
5005
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005006 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005007}