blob: 15503036532a603990d8cc2af562bcfa36eb70d9 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000042 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000045}
46
Nick Lewycky134af912013-02-07 05:08:22 +000047/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000048static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000049CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000051 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000053 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000054 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000062 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000063 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000065 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000066 VK_LValue, Loc, LocInfo);
67 if (HadMultipleCandidates)
68 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000069
70 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000071 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000073}
74
John McCall5c32be02010-08-24 20:38:10 +000075static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000077 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000078 bool CStyle,
79 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000080
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000081static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82 QualType &ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000086static OverloadingResult
87IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88 UserDefinedConversionSequence& User,
89 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000090 bool AllowExplicit,
91 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000092
93
94static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000095CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000096 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareQualificationConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000105CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
108
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109/// GetConversionRank - Retrieve the implicit conversion rank
110/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000111ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000112 static const ImplicitConversionRank
113 Rank[(int)ICK_Num_Conversion_Kinds] = {
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000119 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 ICR_Promotion,
121 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000122 ICR_Promotion,
123 ICR_Conversion,
124 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000130 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000131 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000132 ICR_Conversion,
133 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000134 ICR_Complex_Real_Conversion,
135 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000136 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000137 ICR_Writeback_Conversion,
138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139 // it was omitted by the patch that added
140 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000141 ICR_C_Conversion,
142 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143 };
144 return Rank[(int)Kind];
145}
146
147/// GetImplicitConversionName - Return the name of this kind of
148/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000149static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "No conversion",
152 "Lvalue-to-rvalue",
153 "Array-to-pointer",
154 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000155 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Qualification",
157 "Integral promotion",
158 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000159 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Integral conversion",
161 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000162 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Floating-integral conversion",
164 "Pointer conversion",
165 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000166 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000167 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000168 "Derived-to-base conversion",
169 "Vector conversion",
170 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000171 "Complex-real conversion",
172 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000173 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000174 "Writeback conversion",
175 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000176 "C specific type conversion",
177 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000178 };
179 return Name[Kind];
180}
181
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000182/// StandardConversionSequence - Set the standard conversion
183/// sequence to the identity conversion.
184void StandardConversionSequence::setAsIdentityConversion() {
185 First = ICK_Identity;
186 Second = ICK_Identity;
187 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000188 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000189 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000190 ReferenceBinding = false;
191 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000192 IsLvalueReference = true;
193 BindsToFunctionLvalue = false;
194 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000195 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000196 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000197 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000198}
199
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200/// getRank - Retrieve the rank of this standard conversion sequence
201/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202/// implicit conversions.
203ImplicitConversionRank StandardConversionSequence::getRank() const {
204 ImplicitConversionRank Rank = ICR_Exact_Match;
205 if (GetConversionRank(First) > Rank)
206 Rank = GetConversionRank(First);
207 if (GetConversionRank(Second) > Rank)
208 Rank = GetConversionRank(Second);
209 if (GetConversionRank(Third) > Rank)
210 Rank = GetConversionRank(Third);
211 return Rank;
212}
213
214/// isPointerConversionToBool - Determines whether this conversion is
215/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000216/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000218bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 // Note that FromType has not necessarily been transformed by the
220 // array-to-pointer or function-to-pointer implicit conversions, so
221 // check for their presence as well as checking whether FromType is
222 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000223 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000224 (getFromType()->isPointerType() ||
225 getFromType()->isObjCObjectPointerType() ||
226 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000227 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
229 return true;
230
231 return false;
232}
233
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234/// isPointerConversionToVoidPointer - Determines whether this
235/// conversion is a conversion of a pointer to a void pointer. This is
236/// used as part of the ranking of standard conversion sequences (C++
237/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000238bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000240isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000241 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000242 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243
244 // Note that FromType has not necessarily been transformed by the
245 // array-to-pointer implicit conversion, so check for its presence
246 // and redo the conversion to get a pointer.
247 if (First == ICK_Array_To_Pointer)
248 FromType = Context.getArrayDecayedType(FromType);
249
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000252 return ToPtrType->getPointeeType()->isVoidType();
253
254 return false;
255}
256
Richard Smith66e05fe2012-01-18 05:21:49 +0000257/// Skip any implicit casts which could be either part of a narrowing conversion
258/// or after one in an implicit conversion.
259static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261 switch (ICE->getCastKind()) {
262 case CK_NoOp:
263 case CK_IntegralCast:
264 case CK_IntegralToBoolean:
265 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000266 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000267 case CK_FloatingToIntegral:
268 case CK_FloatingToBoolean:
269 case CK_FloatingCast:
270 Converted = ICE->getSubExpr();
271 continue;
272
273 default:
274 return Converted;
275 }
276 }
277
278 return Converted;
279}
280
281/// Check if this standard conversion sequence represents a narrowing
282/// conversion, according to C++11 [dcl.init.list]p7.
283///
284/// \param Ctx The AST context.
285/// \param Converted The result of applying this standard conversion sequence.
286/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
287/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000288/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
289/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000290NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000291StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000293 APValue &ConstantValue,
294 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000301
302 // A conversion to an enumeration type is narrowing if the conversion to
303 // the underlying type is narrowing. This only arises for expressions of
304 // the form 'Enum{init}'.
305 if (auto *ET = ToType->getAs<EnumType>())
306 ToType = ET->getDecl()->getIntegerType();
307
Richard Smith66e05fe2012-01-18 05:21:49 +0000308 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000309 // 'bool' is an integral type; dispatch to the right place to handle it.
310 case ICK_Boolean_Conversion:
311 if (FromType->isRealFloatingType())
312 goto FloatingIntegralConversion;
313 if (FromType->isIntegralOrUnscopedEnumerationType())
314 goto IntegralConversion;
315 // Boolean conversions can be from pointers and pointers to members
316 // [conv.bool], and those aren't considered narrowing conversions.
317 return NK_Not_Narrowing;
318
Richard Smith66e05fe2012-01-18 05:21:49 +0000319 // -- from a floating-point type to an integer type, or
320 //
321 // -- from an integer type or unscoped enumeration type to a floating-point
322 // type, except where the source is a constant expression and the actual
323 // value after conversion will fit into the target type and will produce
324 // the original value when converted back to the original type, or
325 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000326 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000332
333 // If it's value-dependent, we can't tell whether it's narrowing.
334 if (Initializer->isValueDependent())
335 return NK_Dependent_Narrowing;
336
Richard Smith66e05fe2012-01-18 05:21:49 +0000337 if (Initializer &&
338 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
339 // Convert the integer to the floating type.
340 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
341 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
342 llvm::APFloat::rmNearestTiesToEven);
343 // And back.
344 llvm::APSInt ConvertedValue = IntConstantValue;
345 bool ignored;
346 Result.convertToInteger(ConvertedValue,
347 llvm::APFloat::rmTowardZero, &ignored);
348 // If the resulting value is different, this was a narrowing conversion.
349 if (IntConstantValue != ConvertedValue) {
350 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000351 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000352 return NK_Constant_Narrowing;
353 }
354 } else {
355 // Variables are always narrowings.
356 return NK_Variable_Narrowing;
357 }
358 }
359 return NK_Not_Narrowing;
360
361 // -- from long double to double or float, or from double to float, except
362 // where the source is a constant expression and the actual value after
363 // conversion is within the range of values that can be represented (even
364 // if it cannot be represented exactly), or
365 case ICK_Floating_Conversion:
366 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
367 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
368 // FromType is larger than ToType.
369 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000370
371 // If it's value-dependent, we can't tell whether it's narrowing.
372 if (Initializer->isValueDependent())
373 return NK_Dependent_Narrowing;
374
Richard Smith66e05fe2012-01-18 05:21:49 +0000375 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
376 // Constant!
377 assert(ConstantValue.isFloat());
378 llvm::APFloat FloatVal = ConstantValue.getFloat();
379 // Convert the source value into the target type.
380 bool ignored;
381 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
382 Ctx.getFloatTypeSemantics(ToType),
383 llvm::APFloat::rmNearestTiesToEven, &ignored);
384 // If there was no overflow, the source value is within the range of
385 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000386 if (ConvertStatus & llvm::APFloat::opOverflow) {
387 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000388 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000389 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 } else {
391 return NK_Variable_Narrowing;
392 }
393 }
394 return NK_Not_Narrowing;
395
396 // -- from an integer type or unscoped enumeration type to an integer type
397 // that cannot represent all the values of the original type, except where
398 // the source is a constant expression and the actual value after
399 // conversion will fit into the target type and will produce the original
400 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000401 case ICK_Integral_Conversion:
402 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000403 assert(FromType->isIntegralOrUnscopedEnumerationType());
404 assert(ToType->isIntegralOrUnscopedEnumerationType());
405 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
406 const unsigned FromWidth = Ctx.getIntWidth(FromType);
407 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
408 const unsigned ToWidth = Ctx.getIntWidth(ToType);
409
410 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000411 (FromWidth == ToWidth && FromSigned != ToSigned) ||
412 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000413 // Not all values of FromType can be represented in ToType.
414 llvm::APSInt InitializerValue;
415 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000416
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
419 return NK_Dependent_Narrowing;
420
Richard Smith25a80d42012-06-13 01:07:41 +0000421 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
422 // Such conversions on variables are always narrowing.
423 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000424 }
425 bool Narrowing = false;
426 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000427 // Negative -> unsigned is narrowing. Otherwise, more bits is never
428 // narrowing.
429 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000430 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000431 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000432 // Add a bit to the InitializerValue so we don't have to worry about
433 // signed vs. unsigned comparisons.
434 InitializerValue = InitializerValue.extend(
435 InitializerValue.getBitWidth() + 1);
436 // Convert the initializer to and from the target width and signed-ness.
437 llvm::APSInt ConvertedValue = InitializerValue;
438 ConvertedValue = ConvertedValue.trunc(ToWidth);
439 ConvertedValue.setIsSigned(ToSigned);
440 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
441 ConvertedValue.setIsSigned(InitializerValue.isSigned());
442 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000443 if (ConvertedValue != InitializerValue)
444 Narrowing = true;
445 }
446 if (Narrowing) {
447 ConstantType = Initializer->getType();
448 ConstantValue = APValue(InitializerValue);
449 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000450 }
451 }
452 return NK_Not_Narrowing;
453 }
454
455 default:
456 // Other kinds of conversions are not narrowings.
457 return NK_Not_Narrowing;
458 }
459}
460
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000461/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000463LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 bool PrintedSomething = false;
466 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (Second != ICK_Identity) {
472 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000475 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000476
477 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000479 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000483 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (Third != ICK_Identity) {
488 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 PrintedSomething = true;
493 }
494
495 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 }
498}
499
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000502void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000508 if (ConversionFunction)
509 OS << '\'' << *ConversionFunction << '\'';
510 else
511 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000514 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 }
516}
517
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000518/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000520void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000521 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000522 if (isStdInitializerListElement())
523 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 switch (ConversionKind) {
525 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000527 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528 break;
529 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000530 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000531 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 break;
533 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000534 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000535 break;
John McCall0d1da222010-01-12 00:44:57 +0000536 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000537 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000538 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000540 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000541 break;
542 }
543
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000544 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545}
546
John McCall0d1da222010-01-12 00:44:57 +0000547void AmbiguousConversionSequence::construct() {
548 new (&conversions()) ConversionSet();
549}
550
551void AmbiguousConversionSequence::destruct() {
552 conversions().~ConversionSet();
553}
554
555void
556AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
557 FromTypePtr = O.FromTypePtr;
558 ToTypePtr = O.ToTypePtr;
559 new (&conversions()) ConversionSet(O.conversions());
560}
561
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000563 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 // template argument information.
565 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 TemplateArgument FirstArg;
567 TemplateArgument SecondArg;
568 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000569 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000570 // template parameter and template argument information.
571 struct DFIParamWithArguments : DFIArguments {
572 TemplateParameter Param;
573 };
Richard Smith9b534542015-12-31 02:02:54 +0000574 // Structure used by DeductionFailureInfo to store template argument
575 // information and the index of the problematic call argument.
576 struct DFIDeducedMismatchArgs : DFIArguments {
577 TemplateArgumentList *TemplateArgs;
578 unsigned CallArgIndex;
579 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000580}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582/// \brief Convert from Sema's representation of template deduction information
583/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000584DeductionFailureInfo
585clang::MakeDeductionFailureInfo(ASTContext &Context,
586 Sema::TemplateDeductionResult TDK,
587 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000588 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000589 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000590 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 switch (TDK) {
Renato Golindad96d62017-01-02 11:15:42 +0000592 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smithc92d2062017-01-05 23:02:44 +0000607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000629 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 return Result;
651}
John McCall0d1da222010-01-12 00:44:57 +0000652
Larisse Voufo98b20f12013-07-19 23:00:19 +0000653void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
655 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000656 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 case Sema::TDK_InstantiationDepth:
658 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000659 case Sema::TDK_TooManyArguments:
660 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000661 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000662 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000666 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000667 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000668 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000669 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000670 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000671 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000673
674 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000675 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000677 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
678 Diag->~PartialDiagnosticAt();
679 HasDiagnostic = false;
680 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000681 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor461761d2010-05-08 18:20:53 +0000683 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000684 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685 break;
686 }
687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Larisse Voufo98b20f12013-07-19 23:00:19 +0000689PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000690 if (HasDiagnostic)
691 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000692 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000693}
694
Larisse Voufo98b20f12013-07-19 23:00:19 +0000695TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
697 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000698 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000699 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000703 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000704 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000705 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000706 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000708
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000709 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000710 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712
713 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000714 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 return TemplateParameter();
723}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000727 case Sema::TDK_Success:
728 case Sema::TDK_Invalid:
729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_TooManyArguments:
731 case Sema::TDK_TooFewArguments:
732 case Sema::TDK_Incomplete:
733 case Sema::TDK_InvalidExplicitArguments:
734 case Sema::TDK_Inconsistent:
735 case Sema::TDK_Underqualified:
736 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000737 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000738 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000739
Richard Smith9b534542015-12-31 02:02:54 +0000740 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000741 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000742 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
743
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_SubstitutionFailure:
745 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000746
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 // Unhandled
748 case Sema::TDK_MiscellaneousDeductionFailure:
749 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000750 }
751
Craig Topperc3ec1492014-05-26 06:22:03 +0000752 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000753}
754
Larisse Voufo98b20f12013-07-19 23:00:19 +0000755const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
757 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000758 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000759 case Sema::TDK_InstantiationDepth:
760 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000761 case Sema::TDK_TooManyArguments:
762 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000763 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000764 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000765 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000766 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000769 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000770 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000771 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000772 case Sema::TDK_NonDeducedMismatch:
773 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774
Douglas Gregor461761d2010-05-08 18:20:53 +0000775 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000776 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000777 break;
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Craig Topperc3ec1492014-05-26 06:22:03 +0000780 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Larisse Voufo98b20f12013-07-19 23:00:19 +0000783const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000784 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
785 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000786 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000787 case Sema::TDK_InstantiationDepth:
788 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000789 case Sema::TDK_TooManyArguments:
790 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000791 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000792 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000793 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000794 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000796 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000797 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000798 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000799 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000800 case Sema::TDK_NonDeducedMismatch:
801 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000802
Douglas Gregor461761d2010-05-08 18:20:53 +0000803 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000804 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 break;
806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807
Craig Topperc3ec1492014-05-26 06:22:03 +0000808 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000809}
810
Richard Smith9b534542015-12-31 02:02:54 +0000811llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813 case Sema::TDK_DeducedMismatch:
814 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000815 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
816
Richard Smithc92d2062017-01-05 23:02:44 +0000817 default:
818 return llvm::None;
819 }
Richard Smith9b534542015-12-31 02:02:54 +0000820}
821
Benjamin Kramer97e59492012-10-09 15:52:25 +0000822void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000823 for (iterator i = begin(), e = end(); i != e; ++i) {
Renato Golindad96d62017-01-02 11:15:42 +0000824 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
825 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000826 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
827 i->DeductionFailure.Destroy();
828 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000829}
830
831void OverloadCandidateSet::clear() {
832 destroyCandidates();
George Burgess IVbc7f44c2016-12-02 21:00:12 +0000833 ConversionSequenceAllocator.Reset();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000834 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000835 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000836 Functions.clear();
837}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838
John McCall4124c492011-10-17 18:40:02 +0000839namespace {
840 class UnbridgedCastsSet {
841 struct Entry {
842 Expr **Addr;
843 Expr *Saved;
844 };
845 SmallVector<Entry, 2> Entries;
846
847 public:
848 void save(Sema &S, Expr *&E) {
849 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
850 Entry entry = { &E, E };
851 Entries.push_back(entry);
852 E = S.stripARCUnbridgedCast(E);
853 }
854
855 void restore() {
856 for (SmallVectorImpl<Entry>::iterator
857 i = Entries.begin(), e = Entries.end(); i != e; ++i)
858 *i->Addr = i->Saved;
859 }
860 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000861}
John McCall4124c492011-10-17 18:40:02 +0000862
863/// checkPlaceholderForOverload - Do any interesting placeholder-like
864/// preprocessing on the given expression.
865///
866/// \param unbridgedCasts a collection to which to add unbridged casts;
867/// without this, they will be immediately diagnosed as errors
868///
869/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000870static bool
871checkPlaceholderForOverload(Sema &S, Expr *&E,
872 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000873 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
874 // We can't handle overloaded expressions here because overload
875 // resolution might reasonably tweak them.
876 if (placeholder->getKind() == BuiltinType::Overload) return false;
877
878 // If the context potentially accepts unbridged ARC casts, strip
879 // the unbridged cast and add it to the collection for later restoration.
880 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
881 unbridgedCasts) {
882 unbridgedCasts->save(S, E);
883 return false;
884 }
885
886 // Go ahead and check everything else.
887 ExprResult result = S.CheckPlaceholderExpr(E);
888 if (result.isInvalid())
889 return true;
890
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000891 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000892 return false;
893 }
894
895 // Nothing to do.
896 return false;
897}
898
899/// checkArgPlaceholdersForOverload - Check a set of call operands for
900/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000901static bool checkArgPlaceholdersForOverload(Sema &S,
902 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000903 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000904 for (unsigned i = 0, e = Args.size(); i != e; ++i)
905 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000906 return true;
907
908 return false;
909}
910
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000912// overload of the declarations in Old. This routine returns false if
913// New and Old cannot be overloaded, e.g., if New has the same
914// signature as some function in Old (C++ 1.3.10) or if the Old
915// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000916// it does return false, MatchedDecl will point to the decl that New
917// cannot be overloaded with. This decl may be a UsingShadowDecl on
918// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000919//
920// Example: Given the following input:
921//
922// void f(int, float); // #1
923// void f(int, int); // #2
924// int f(int, int); // #3
925//
926// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000927// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928//
John McCall3d988d92009-12-02 08:47:38 +0000929// When we process #2, Old contains only the FunctionDecl for #1. By
930// comparing the parameter types, we see that #1 and #2 are overloaded
931// (since they have different signatures), so this routine returns
932// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000933//
John McCall3d988d92009-12-02 08:47:38 +0000934// When we process #3, Old is an overload set containing #1 and #2. We
935// compare the signatures of #3 to #1 (they're overloaded, so we do
936// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
937// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938// signature), IsOverload returns false and MatchedDecl will be set to
939// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000940//
941// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
942// into a class by a using declaration. The rules for whether to hide
943// shadow declarations ignore some properties which otherwise figure
944// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000945Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000946Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
947 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000948 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000949 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000950 NamedDecl *OldD = *I;
951
952 bool OldIsUsingDecl = false;
953 if (isa<UsingShadowDecl>(OldD)) {
954 OldIsUsingDecl = true;
955
956 // We can always introduce two using declarations into the same
957 // context, even if they have identical signatures.
958 if (NewIsUsingDecl) continue;
959
960 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
961 }
962
Richard Smithf091e122015-09-15 01:28:55 +0000963 // A using-declaration does not conflict with another declaration
964 // if one of them is hidden.
965 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
966 continue;
967
John McCalle9cccd82010-06-16 08:42:20 +0000968 // If either declaration was introduced by a using declaration,
969 // we'll need to use slightly different rules for matching.
970 // Essentially, these rules are the normal rules, except that
971 // function templates hide function templates with different
972 // return types or template parameter lists.
973 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000974 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
975 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000976
Alp Tokera2794f92014-01-22 07:29:52 +0000977 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000978 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
979 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
980 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
981 continue;
982 }
983
Alp Tokera2794f92014-01-22 07:29:52 +0000984 if (!isa<FunctionTemplateDecl>(OldD) &&
985 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000986 continue;
987
John McCalldaa3d6b2009-12-09 03:35:25 +0000988 Match = *I;
989 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000990 }
Richard Smith151c4562016-12-20 21:35:28 +0000991 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000992 // We can overload with these, which can show up when doing
993 // redeclaration checks for UsingDecls.
994 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000995 } else if (isa<TagDecl>(OldD)) {
996 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +0000997 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000998 // Optimistically assume that an unresolved using decl will
999 // overload; if it doesn't, we'll have to diagnose during
1000 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001001 //
1002 // Exception: if the scope is dependent and this is not a class
1003 // member, the using declaration can only introduce an enumerator.
1004 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1005 Match = *I;
1006 return Ovl_NonFunction;
1007 }
John McCall84d87672009-12-10 09:41:52 +00001008 } else {
John McCall1f82f242009-11-18 22:49:29 +00001009 // (C++ 13p1):
1010 // Only function declarations can be overloaded; object and type
1011 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001012 Match = *I;
1013 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001014 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015 }
John McCall1f82f242009-11-18 22:49:29 +00001016
John McCalldaa3d6b2009-12-09 03:35:25 +00001017 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001018}
1019
Richard Smithac974a32013-06-30 09:48:50 +00001020bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001021 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001022 // C++ [basic.start.main]p2: This function shall not be overloaded.
1023 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001024 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001025
David Majnemerc729b0b2013-09-16 22:44:20 +00001026 // MSVCRT user defined entry points cannot be overloaded.
1027 if (New->isMSVCRTEntryPoint())
1028 return false;
1029
John McCall1f82f242009-11-18 22:49:29 +00001030 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1031 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1032
1033 // C++ [temp.fct]p2:
1034 // A function template can be overloaded with other function templates
1035 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001036 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001037 return true;
1038
1039 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001040 QualType OldQType = Context.getCanonicalType(Old->getType());
1041 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001042
1043 // Compare the signatures (C++ 1.3.10) of the two functions to
1044 // determine whether they are overloads. If we find any mismatch
1045 // in the signature, they are overloads.
1046
1047 // If either of these functions is a K&R-style function (no
1048 // prototype), then we consider them to have matching signatures.
1049 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1050 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1051 return false;
1052
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001053 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1054 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001055
1056 // The signature of a function includes the types of its
1057 // parameters (C++ 1.3.10), which includes the presence or absence
1058 // of the ellipsis; see C++ DR 357).
1059 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001060 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001061 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001062 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001063 return true;
1064
1065 // C++ [temp.over.link]p4:
1066 // The signature of a function template consists of its function
1067 // signature, its return type and its template parameter list. The names
1068 // of the template parameters are significant only for establishing the
1069 // relationship between the template parameters and the rest of the
1070 // signature.
1071 //
1072 // We check the return type and template parameter lists for function
1073 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001074 //
1075 // However, we don't consider either of these when deciding whether
1076 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001077 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001078 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1079 OldTemplate->getTemplateParameters(),
1080 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001081 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001082 return true;
1083
1084 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001085 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001086 //
1087 // As part of this, also check whether one of the member functions
1088 // is static, in which case they are not overloads (C++
1089 // 13.1p2). While not part of the definition of the signature,
1090 // this check is important to determine whether these functions
1091 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001092 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1093 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001094 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001095 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1096 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001097 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001098 (OldMethod->getRefQualifier() == RQ_None ||
1099 NewMethod->getRefQualifier() == RQ_None)) {
1100 // C++0x [over.load]p2:
1101 // - Member function declarations with the same name and the same
1102 // parameter-type-list as well as member function template
1103 // declarations with the same name, the same parameter-type-list, and
1104 // the same template parameter lists cannot be overloaded if any of
1105 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001106 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001107 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001108 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001109 }
1110 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Richard Smith574f4f62013-01-14 05:37:29 +00001113 // We may not have applied the implicit const for a constexpr member
1114 // function yet (because we haven't yet resolved whether this is a static
1115 // or non-static member function). Add it now, on the assumption that this
1116 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001117 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001118 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001119 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001120 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001121 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001122
1123 // We do not allow overloading based off of '__restrict'.
1124 OldQuals &= ~Qualifiers::Restrict;
1125 NewQuals &= ~Qualifiers::Restrict;
1126 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001127 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001130 // Though pass_object_size is placed on parameters and takes an argument, we
1131 // consider it to be a function-level modifier for the sake of function
1132 // identity. Either the function has one or more parameters with
1133 // pass_object_size or it doesn't.
1134 if (functionHasPassObjectSizeParams(New) !=
1135 functionHasPassObjectSizeParams(Old))
1136 return true;
1137
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001138 // enable_if attributes are an order-sensitive part of the signature.
1139 for (specific_attr_iterator<EnableIfAttr>
1140 NewI = New->specific_attr_begin<EnableIfAttr>(),
1141 NewE = New->specific_attr_end<EnableIfAttr>(),
1142 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1143 OldE = Old->specific_attr_end<EnableIfAttr>();
1144 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1145 if (NewI == NewE || OldI == OldE)
1146 return true;
1147 llvm::FoldingSetNodeID NewID, OldID;
1148 NewI->getCond()->Profile(NewID, Context, true);
1149 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001150 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001151 return true;
1152 }
1153
Justin Lebarba122ab2016-03-30 23:30:21 +00001154 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001155 // Don't allow overloading of destructors. (In theory we could, but it
1156 // would be a giant change to clang.)
1157 if (isa<CXXDestructorDecl>(New))
1158 return false;
1159
Artem Belevich94a55e82015-09-22 17:22:59 +00001160 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1161 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001162 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001163 return false;
1164
1165 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1166
Justin Lebar53b000af2016-10-03 16:48:27 +00001167 // Allow overloading of functions with same signature and different CUDA
1168 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001169 return NewTarget != OldTarget;
1170 }
1171
John McCall1f82f242009-11-18 22:49:29 +00001172 // The signatures match; this is not an overload.
1173 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174}
1175
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001176/// \brief Checks availability of the function depending on the current
1177/// function context. Inside an unavailable function, unavailability is ignored.
1178///
1179/// \returns true if \arg FD is unavailable and current context is inside
1180/// an available function, false otherwise.
1181bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001182 if (!FD->isUnavailable())
1183 return false;
1184
1185 // Walk up the context of the caller.
1186 Decl *C = cast<Decl>(CurContext);
1187 do {
1188 if (C->isUnavailable())
1189 return false;
1190 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1191 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001192}
1193
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001194/// \brief Tries a user-defined conversion from From to ToType.
1195///
1196/// Produces an implicit conversion sequence for when a standard conversion
1197/// is not an option. See TryImplicitConversion for more information.
1198static ImplicitConversionSequence
1199TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1200 bool SuppressUserConversions,
1201 bool AllowExplicit,
1202 bool InOverloadResolution,
1203 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001204 bool AllowObjCWritebackConversion,
1205 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001206 ImplicitConversionSequence ICS;
1207
1208 if (SuppressUserConversions) {
1209 // We're not in the case above, so there is no conversion that
1210 // we can perform.
1211 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1212 return ICS;
1213 }
1214
1215 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001216 OverloadCandidateSet Conversions(From->getExprLoc(),
1217 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001218 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1219 Conversions, AllowExplicit,
1220 AllowObjCConversionOnExplicit)) {
1221 case OR_Success:
1222 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001223 ICS.setUserDefined();
1224 // C++ [over.ics.user]p4:
1225 // A conversion of an expression of class type to the same class
1226 // type is given Exact Match rank, and a conversion of an
1227 // expression of class type to a base class of that type is
1228 // given Conversion rank, in spite of the fact that a copy
1229 // constructor (i.e., a user-defined conversion function) is
1230 // called for those cases.
1231 if (CXXConstructorDecl *Constructor
1232 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1233 QualType FromCanon
1234 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1235 QualType ToCanon
1236 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1237 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001238 (FromCanon == ToCanon ||
1239 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001240 // Turn this into a "standard" conversion sequence, so that it
1241 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001242 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001243 ICS.setStandard();
1244 ICS.Standard.setAsIdentityConversion();
1245 ICS.Standard.setFromType(From->getType());
1246 ICS.Standard.setAllToTypes(ToType);
1247 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001248 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001249 if (ToCanon != FromCanon)
1250 ICS.Standard.Second = ICK_Derived_To_Base;
1251 }
1252 }
Richard Smith48372b62015-01-27 03:30:40 +00001253 break;
1254
1255 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001256 ICS.setAmbiguous();
1257 ICS.Ambiguous.setFromType(From->getType());
1258 ICS.Ambiguous.setToType(ToType);
1259 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1260 Cand != Conversions.end(); ++Cand)
1261 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001262 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001263 break;
Richard Smith48372b62015-01-27 03:30:40 +00001264
1265 // Fall through.
1266 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001267 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001268 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001269 }
1270
1271 return ICS;
1272}
1273
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001274/// TryImplicitConversion - Attempt to perform an implicit conversion
1275/// from the given expression (Expr) to the given type (ToType). This
1276/// function returns an implicit conversion sequence that can be used
1277/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001278///
1279/// void f(float f);
1280/// void g(int i) { f(i); }
1281///
1282/// this routine would produce an implicit conversion sequence to
1283/// describe the initialization of f from i, which will be a standard
1284/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1285/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1286//
1287/// Note that this routine only determines how the conversion can be
1288/// performed; it does not actually perform the conversion. As such,
1289/// it will not produce any diagnostics if no conversion is available,
1290/// but will instead return an implicit conversion sequence of kind
1291/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001292///
1293/// If @p SuppressUserConversions, then user-defined conversions are
1294/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001295/// If @p AllowExplicit, then explicit user-defined conversions are
1296/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001297///
1298/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1299/// writeback conversion, which allows __autoreleasing id* parameters to
1300/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001301static ImplicitConversionSequence
1302TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1303 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001305 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001306 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001307 bool AllowObjCWritebackConversion,
1308 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001309 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001310 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001311 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001312 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001313 return ICS;
1314 }
1315
David Blaikiebbafb8a2012-03-11 07:00:24 +00001316 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001317 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001318 return ICS;
1319 }
1320
Douglas Gregor836a7e82010-08-11 02:15:33 +00001321 // C++ [over.ics.user]p4:
1322 // A conversion of an expression of class type to the same class
1323 // type is given Exact Match rank, and a conversion of an
1324 // expression of class type to a base class of that type is
1325 // given Conversion rank, in spite of the fact that a copy/move
1326 // constructor (i.e., a user-defined conversion function) is
1327 // called for those cases.
1328 QualType FromType = From->getType();
1329 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001330 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001331 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001332 ICS.setStandard();
1333 ICS.Standard.setAsIdentityConversion();
1334 ICS.Standard.setFromType(FromType);
1335 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
Douglas Gregor5ab11652010-04-17 22:01:05 +00001337 // We don't actually check at this point whether there is a valid
1338 // copy/move constructor, since overloading just assumes that it
1339 // exists. When we actually perform initialization, we'll find the
1340 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001341 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001342
Douglas Gregor5ab11652010-04-17 22:01:05 +00001343 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001344 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001345 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001346
Douglas Gregor836a7e82010-08-11 02:15:33 +00001347 return ICS;
1348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001350 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1351 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001352 AllowObjCWritebackConversion,
1353 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001354}
1355
John McCall31168b02011-06-15 23:02:42 +00001356ImplicitConversionSequence
1357Sema::TryImplicitConversion(Expr *From, QualType ToType,
1358 bool SuppressUserConversions,
1359 bool AllowExplicit,
1360 bool InOverloadResolution,
1361 bool CStyle,
1362 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001363 return ::TryImplicitConversion(*this, From, ToType,
1364 SuppressUserConversions, AllowExplicit,
1365 InOverloadResolution, CStyle,
1366 AllowObjCWritebackConversion,
1367 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001368}
1369
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001370/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001371/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001372/// converted expression. Flavor is the kind of conversion we're
1373/// performing, used in the error message. If @p AllowExplicit,
1374/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001375ExprResult
1376Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001377 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001378 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001379 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380}
1381
John Wiegley01296292011-04-08 18:41:53 +00001382ExprResult
1383Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001384 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001385 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001386 if (checkPlaceholderForOverload(*this, From))
1387 return ExprError();
1388
John McCall31168b02011-06-15 23:02:42 +00001389 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1390 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001391 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001392 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001393 if (getLangOpts().ObjC1)
1394 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1395 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001396 ICS = ::TryImplicitConversion(*this, From, ToType,
1397 /*SuppressUserConversions=*/false,
1398 AllowExplicit,
1399 /*InOverloadResolution=*/false,
1400 /*CStyle=*/false,
1401 AllowObjCWritebackConversion,
1402 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001403 return PerformImplicitConversion(From, ToType, ICS, Action);
1404}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
1406/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001407/// conversion that strips "noexcept" or "noreturn" off the nested function
1408/// type.
1409bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001410 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001411 if (Context.hasSameUnqualifiedType(FromType, ToType))
1412 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
John McCall991eb4b2010-12-21 00:44:39 +00001414 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001415 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001416 // where F adds one of the following at most once:
1417 // - a pointer
1418 // - a member pointer
1419 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001420 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001421 CanQualType CanTo = Context.getCanonicalType(ToType);
1422 CanQualType CanFrom = Context.getCanonicalType(FromType);
1423 Type::TypeClass TyClass = CanTo->getTypeClass();
1424 if (TyClass != CanFrom->getTypeClass()) return false;
1425 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1426 if (TyClass == Type::Pointer) {
1427 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1428 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1429 } else if (TyClass == Type::BlockPointer) {
1430 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1431 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1432 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001433 auto ToMPT = CanTo.getAs<MemberPointerType>();
1434 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1435 // A function pointer conversion cannot change the class of the function.
1436 if (ToMPT->getClass() != FromMPT->getClass())
1437 return false;
1438 CanTo = ToMPT->getPointeeType();
1439 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001440 } else {
1441 return false;
1442 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001443
John McCall991eb4b2010-12-21 00:44:39 +00001444 TyClass = CanTo->getTypeClass();
1445 if (TyClass != CanFrom->getTypeClass()) return false;
1446 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1447 return false;
1448 }
1449
Richard Smith3c4f8d22016-10-16 17:54:23 +00001450 const auto *FromFn = cast<FunctionType>(CanFrom);
1451 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001452
Richard Smith6f427402016-10-20 00:01:36 +00001453 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001454 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1455
1456 bool Changed = false;
1457
1458 // Drop 'noreturn' if not present in target type.
1459 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1460 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1461 Changed = true;
1462 }
1463
1464 // Drop 'noexcept' if not present in target type.
1465 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001466 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001467 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1468 FromFn = cast<FunctionType>(
1469 Context.getFunctionType(FromFPT->getReturnType(),
1470 FromFPT->getParamTypes(),
1471 FromFPT->getExtProtoInfo().withExceptionSpec(
1472 FunctionProtoType::ExceptionSpecInfo()))
1473 .getTypePtr());
1474 Changed = true;
1475 }
1476 }
1477
1478 if (!Changed)
1479 return false;
1480
John McCall991eb4b2010-12-21 00:44:39 +00001481 assert(QualType(FromFn, 0).isCanonical());
1482 if (QualType(FromFn, 0) != CanTo) return false;
1483
1484 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001485 return true;
1486}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregor46188682010-05-18 22:42:18 +00001488/// \brief Determine whether the conversion from FromType to ToType is a valid
1489/// vector conversion.
1490///
1491/// \param ICK Will be set to the vector conversion kind, if this is a vector
1492/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001493static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001495 // We need at least one of these types to be a vector type to have a vector
1496 // conversion.
1497 if (!ToType->isVectorType() && !FromType->isVectorType())
1498 return false;
1499
1500 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001501 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001502 return false;
1503
1504 // There are no conversions between extended vector types, only identity.
1505 if (ToType->isExtVectorType()) {
1506 // There are no conversions between extended vector types other than the
1507 // identity conversion.
1508 if (FromType->isExtVectorType())
1509 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001510
Douglas Gregor46188682010-05-18 22:42:18 +00001511 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001512 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001513 ICK = ICK_Vector_Splat;
1514 return true;
1515 }
1516 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001517
1518 // We can perform the conversion between vector types in the following cases:
1519 // 1)vector types are equivalent AltiVec and GCC vector types
1520 // 2)lax vector conversions are permitted and the vector types are of the
1521 // same size
1522 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001523 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1524 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001525 ICK = ICK_Vector_Conversion;
1526 return true;
1527 }
Douglas Gregor46188682010-05-18 22:42:18 +00001528 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001529
Douglas Gregor46188682010-05-18 22:42:18 +00001530 return false;
1531}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001532
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001533static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1534 bool InOverloadResolution,
1535 StandardConversionSequence &SCS,
1536 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001537
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001538/// IsStandardConversion - Determines whether there is a standard
1539/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1540/// expression From to the type ToType. Standard conversion sequences
1541/// only consider non-class types; for conversions that involve class
1542/// types, use TryImplicitConversion. If a conversion exists, SCS will
1543/// contain the standard conversion sequence required to perform this
1544/// conversion and this routine will return true. Otherwise, this
1545/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001546static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1547 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001548 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001549 bool CStyle,
1550 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001554 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001555 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001556 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001557 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001559 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001560 // abort early. When overloading in C, however, we do permit them.
1561 if (S.getLangOpts().CPlusPlus &&
1562 (FromType->isRecordType() || ToType->isRecordType()))
1563 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001564
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 // The first conversion can be an lvalue-to-rvalue conversion,
1566 // array-to-pointer conversion, or function-to-pointer conversion
1567 // (C++ 4p1).
1568
John McCall5c32be02010-08-24 20:38:10 +00001569 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001570 DeclAccessPair AccessPair;
1571 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001572 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001573 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001574 // We were able to resolve the address of the overloaded function,
1575 // so we can convert to the type of that function.
1576 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001577 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001578
1579 // we can sometimes resolve &foo<int> regardless of ToType, so check
1580 // if the type matches (identity) or we are converting to bool
1581 if (!S.Context.hasSameUnqualifiedType(
1582 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1583 QualType resultTy;
1584 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001585 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001586 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1587 // otherwise, only a boolean conversion is standard
1588 if (!ToType->isBooleanType())
1589 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591
Chandler Carruthffce2452011-03-29 08:08:18 +00001592 // Check if the "from" expression is taking the address of an overloaded
1593 // function and recompute the FromType accordingly. Take advantage of the
1594 // fact that non-static member functions *must* have such an address-of
1595 // expression.
1596 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1597 if (Method && !Method->isStatic()) {
1598 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1599 "Non-unary operator on non-static member address");
1600 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1601 == UO_AddrOf &&
1602 "Non-address-of operator on non-static member address");
1603 const Type *ClassType
1604 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1605 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001606 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1607 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1608 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001609 "Non-address-of operator for overloaded function expression");
1610 FromType = S.Context.getPointerType(FromType);
1611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001612
Douglas Gregor980fb162010-04-29 18:24:40 +00001613 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001614 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1615 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001616 assert(S.Context.hasSameType(
1617 FromType,
1618 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001619 } else {
1620 return false;
1621 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001622 }
John McCall154a2fd2011-08-30 00:57:29 +00001623 // Lvalue-to-rvalue conversion (C++11 4.1):
1624 // A glvalue (3.10) of a non-function, non-array type T can
1625 // be converted to a prvalue.
1626 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001627 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001628 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001629 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001630 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631
Douglas Gregorc79862f2012-04-12 17:51:55 +00001632 // C11 6.3.2.1p2:
1633 // ... if the lvalue has atomic type, the value has the non-atomic version
1634 // of the type of the lvalue ...
1635 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1636 FromType = Atomic->getValueType();
1637
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 // If T is a non-class type, the type of the rvalue is the
1639 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001640 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1641 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001642 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001643 } else if (FromType->isArrayType()) {
1644 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646
1647 // An lvalue or rvalue of type "array of N T" or "array of unknown
1648 // bound of T" can be converted to an rvalue of type "pointer to
1649 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001650 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001651
John McCall5c32be02010-08-24 20:38:10 +00001652 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001653 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001654 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655
1656 // For the purpose of ranking in overload resolution
1657 // (13.3.3.1.1), this conversion is considered an
1658 // array-to-pointer conversion followed by a qualification
1659 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001660 SCS.Second = ICK_Identity;
1661 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001662 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001663 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001664 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 }
John McCall086a4642010-11-24 05:12:34 +00001666 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001667 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001670 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1671 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1672 if (!S.checkAddressOfFunctionIsAvailable(FD))
1673 return false;
1674
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 // An lvalue of function type T can be converted to an rvalue of
1676 // type "pointer to T." The result is a pointer to the
1677 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001678 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001679 } else {
1680 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001681 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001683 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684
1685 // The second conversion can be an integral promotion, floating
1686 // point promotion, integral conversion, floating point conversion,
1687 // floating-integral conversion, pointer conversion,
1688 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001689 // For overloading in C, this can also be a "compatible-type"
1690 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001691 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001692 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001693 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694 // The unqualified versions of the types are the same: there's no
1695 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001697 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001698 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001699 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001700 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001701 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001702 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001703 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001705 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001706 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001707 SCS.Second = ICK_Complex_Promotion;
1708 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001709 } else if (ToType->isBooleanType() &&
1710 (FromType->isArithmeticType() ||
1711 FromType->isAnyPointerType() ||
1712 FromType->isBlockPointerType() ||
1713 FromType->isMemberPointerType() ||
1714 FromType->isNullPtrType())) {
1715 // Boolean conversions (C++ 4.12).
1716 SCS.Second = ICK_Boolean_Conversion;
1717 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001718 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001719 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001720 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001721 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001723 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001724 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001725 SCS.Second = ICK_Complex_Conversion;
1726 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001727 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1728 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001729 // Complex-real conversions (C99 6.3.1.7)
1730 SCS.Second = ICK_Complex_Real;
1731 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001732 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001733 // FIXME: disable conversions between long double and __float128 if
1734 // their representation is different until there is back end support
1735 // We of course allow this conversion if long double is really double.
1736 if (&S.Context.getFloatTypeSemantics(FromType) !=
1737 &S.Context.getFloatTypeSemantics(ToType)) {
1738 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1739 ToType == S.Context.LongDoubleTy) ||
1740 (FromType == S.Context.LongDoubleTy &&
1741 ToType == S.Context.Float128Ty));
1742 if (Float128AndLongDouble &&
1743 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001744 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001745 return false;
1746 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001747 // Floating point conversions (C++ 4.8).
1748 SCS.Second = ICK_Floating_Conversion;
1749 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001750 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001751 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001752 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001753 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001754 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001755 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001757 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001758 SCS.Second = ICK_Block_Pointer_Conversion;
1759 } else if (AllowObjCWritebackConversion &&
1760 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1761 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001762 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1763 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001764 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001765 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001766 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001767 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001768 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001769 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001770 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001771 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001772 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001773 SCS.Second = SecondICK;
1774 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001775 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001776 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001777 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001778 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001779 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001780 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1781 InOverloadResolution,
1782 SCS, CStyle)) {
1783 SCS.Second = ICK_TransparentUnionConversion;
1784 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001785 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1786 CStyle)) {
1787 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001788 // appropriately.
1789 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001790 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001791 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001792 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001793 SCS.Second = ICK_Zero_Event_Conversion;
1794 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001795 } else if (ToType->isQueueT() &&
1796 From->isIntegerConstantExpr(S.getASTContext()) &&
1797 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1798 SCS.Second = ICK_Zero_Queue_Conversion;
1799 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800 } else {
1801 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001802 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001804 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001805
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001806 // The third conversion can be a function pointer conversion or a
1807 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001808 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001809 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1810 // Function pointer conversions (removing 'noexcept') including removal of
1811 // 'noreturn' (Clang extension).
1812 SCS.Third = ICK_Function_Conversion;
1813 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1814 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001815 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001816 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 FromType = ToType;
1818 } else {
1819 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001820 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001821 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001822
1823 // C++ [over.best.ics]p6:
1824 // [...] Any difference in top-level cv-qualification is
1825 // subsumed by the initialization itself and does not constitute
1826 // a conversion. [...]
1827 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1828 QualType CanonTo = S.Context.getCanonicalType(ToType);
1829 if (CanonFrom.getLocalUnqualifiedType()
1830 == CanonTo.getLocalUnqualifiedType() &&
1831 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1832 FromType = ToType;
1833 CanonFrom = CanonTo;
1834 }
1835
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001836 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001837
George Burgess IV45461812015-10-11 20:13:20 +00001838 if (CanonFrom == CanonTo)
1839 return true;
1840
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001842 // this is a bad conversion sequence, unless we're resolving an overload in C.
1843 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001844 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845
George Burgess IV45461812015-10-11 20:13:20 +00001846 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001847 Sema::AssignConvertType Conv =
1848 S.CheckSingleAssignmentConstraints(ToType, ER,
1849 /*Diagnose=*/false,
1850 /*DiagnoseCFAudited=*/false,
1851 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001852 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001853 switch (Conv) {
1854 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001855 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001856 break;
1857 // For our purposes, discarding qualifiers is just as bad as using an
1858 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1859 // qualifiers, as well.
1860 case Sema::CompatiblePointerDiscardsQualifiers:
1861 case Sema::IncompatiblePointer:
1862 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001863 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001864 break;
1865 default:
George Burgess IV45461812015-10-11 20:13:20 +00001866 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001867 }
George Burgess IV45461812015-10-11 20:13:20 +00001868
George Burgess IV6098fd12016-09-03 00:28:25 +00001869 // First can only be an lvalue conversion, so we pretend that this was the
1870 // second conversion. First should already be valid from earlier in the
1871 // function.
1872 SCS.Second = SecondConv;
1873 SCS.setToType(1, ToType);
1874
1875 // Third is Identity, because Second should rank us worse than any other
1876 // conversion. This could also be ICK_Qualification, but it's simpler to just
1877 // lump everything in with the second conversion, and we don't gain anything
1878 // from making this ICK_Qualification.
1879 SCS.Third = ICK_Identity;
1880 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001881 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882}
George Burgess IV2099b542016-09-02 22:59:57 +00001883
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001884static bool
1885IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1886 QualType &ToType,
1887 bool InOverloadResolution,
1888 StandardConversionSequence &SCS,
1889 bool CStyle) {
1890
1891 const RecordType *UT = ToType->getAsUnionType();
1892 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1893 return false;
1894 // The field to initialize within the transparent union.
1895 RecordDecl *UD = UT->getDecl();
1896 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001897 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001898 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1899 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001900 ToType = it->getType();
1901 return true;
1902 }
1903 }
1904 return false;
1905}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001906
1907/// IsIntegralPromotion - Determines whether the conversion from the
1908/// expression From (whose potentially-adjusted type is FromType) to
1909/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1910/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001911bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001912 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001913 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001914 if (!To) {
1915 return false;
1916 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001917
1918 // An rvalue of type char, signed char, unsigned char, short int, or
1919 // unsigned short int can be converted to an rvalue of type int if
1920 // int can represent all the values of the source type; otherwise,
1921 // the source rvalue can be converted to an rvalue of type unsigned
1922 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001923 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1924 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001925 if (// We can promote any signed, promotable integer type to an int
1926 (FromType->isSignedIntegerType() ||
1927 // We can promote any unsigned integer type whose size is
1928 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001929 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001930 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001931 }
1932
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001933 return To->getKind() == BuiltinType::UInt;
1934 }
1935
Richard Smithb9c5a602012-09-13 21:18:54 +00001936 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937 // A prvalue of an unscoped enumeration type whose underlying type is not
1938 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1939 // following types that can represent all the values of the enumeration
1940 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1941 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001942 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001944 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 // with lowest integer conversion rank (4.13) greater than the rank of long
1946 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001947 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001948 // C++11 [conv.prom]p4:
1949 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1950 // can be converted to a prvalue of its underlying type. Moreover, if
1951 // integral promotion can be applied to its underlying type, a prvalue of an
1952 // unscoped enumeration type whose underlying type is fixed can also be
1953 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001954 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1955 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1956 // provided for a scoped enumeration.
1957 if (FromEnumType->getDecl()->isScoped())
1958 return false;
1959
Richard Smithb9c5a602012-09-13 21:18:54 +00001960 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001961 // even if that's not the promoted type. Note that the check for promoting
1962 // the underlying type is based on the type alone, and does not consider
1963 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001964 if (FromEnumType->getDecl()->isFixed()) {
1965 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1966 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001967 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001968 }
1969
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001970 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001972 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001973 return Context.hasSameUnqualifiedType(
1974 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001975 }
John McCall56774992009-12-09 09:09:27 +00001976
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001977 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001978 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1979 // to an rvalue a prvalue of the first of the following types that can
1980 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001981 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001983 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001985 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001987 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001988 // Determine whether the type we're converting from is signed or
1989 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001990 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001991 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001993 // The types we'll try to promote to, in the appropriate
1994 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001995 QualType PromoteTypes[6] = {
1996 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001997 Context.LongTy, Context.UnsignedLongTy ,
1998 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002000 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2002 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002003 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002004 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2005 // We found the type that we can promote to. If this is the
2006 // type we wanted, we have a promotion. Otherwise, no
2007 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002008 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009 }
2010 }
2011 }
2012
2013 // An rvalue for an integral bit-field (9.6) can be converted to an
2014 // rvalue of type int if int can represent all the values of the
2015 // bit-field; otherwise, it can be converted to unsigned int if
2016 // unsigned int can represent all the values of the bit-field. If
2017 // the bit-field is larger yet, no integral promotion applies to
2018 // it. If the bit-field has an enumerated type, it is treated as any
2019 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002020 // FIXME: We should delay checking of bit-fields until we actually perform the
2021 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002022 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002023 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002024 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002025 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002026 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002027 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002028 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002030 // Are we promoting to an int from a bitfield that fits in an int?
2031 if (BitWidth < ToSize ||
2032 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2033 return To->getKind() == BuiltinType::Int;
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002036 // Are we promoting to an unsigned int from an unsigned bitfield
2037 // that fits into an unsigned int?
2038 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2039 return To->getKind() == BuiltinType::UInt;
2040 }
Mike Stump11289f42009-09-09 15:08:12 +00002041
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002042 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002043 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002044 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002045 }
Mike Stump11289f42009-09-09 15:08:12 +00002046
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047 // An rvalue of type bool can be converted to an rvalue of type int,
2048 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002049 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002051 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052
2053 return false;
2054}
2055
2056/// IsFloatingPointPromotion - Determines whether the conversion from
2057/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2058/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002059bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002060 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2061 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002062 /// An rvalue of type float can be converted to an rvalue of type
2063 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002064 if (FromBuiltin->getKind() == BuiltinType::Float &&
2065 ToBuiltin->getKind() == BuiltinType::Double)
2066 return true;
2067
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002068 // C99 6.3.1.5p1:
2069 // When a float is promoted to double or long double, or a
2070 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002071 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002072 (FromBuiltin->getKind() == BuiltinType::Float ||
2073 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002074 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2075 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002076 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002077
2078 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002079 if (!getLangOpts().NativeHalfType &&
2080 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002081 ToBuiltin->getKind() == BuiltinType::Float)
2082 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002083 }
2084
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002085 return false;
2086}
2087
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002088/// \brief Determine if a conversion is a complex promotion.
2089///
2090/// A complex promotion is defined as a complex -> complex conversion
2091/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002092/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002093bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002094 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002095 if (!FromComplex)
2096 return false;
2097
John McCall9dd450b2009-09-21 23:43:11 +00002098 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002099 if (!ToComplex)
2100 return false;
2101
2102 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002103 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002104 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002105 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002106}
2107
Douglas Gregor237f96c2008-11-26 23:31:11 +00002108/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2109/// the pointer type FromPtr to a pointer to type ToPointee, with the
2110/// same type qualifiers as FromPtr has on its pointee type. ToType,
2111/// if non-empty, will be a pointer to ToType that may or may not have
2112/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002113///
Mike Stump11289f42009-09-09 15:08:12 +00002114static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002115BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002116 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002117 ASTContext &Context,
2118 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002119 assert((FromPtr->getTypeClass() == Type::Pointer ||
2120 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2121 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122
John McCall31168b02011-06-15 23:02:42 +00002123 /// Conversions to 'id' subsume cv-qualifier conversions.
2124 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002125 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002126
2127 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002128 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002129 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002130 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002131
John McCall31168b02011-06-15 23:02:42 +00002132 if (StripObjCLifetime)
2133 Quals.removeObjCLifetime();
2134
Mike Stump11289f42009-09-09 15:08:12 +00002135 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002136 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002137 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002138 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002139 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002140
2141 // Build a pointer to ToPointee. It has the right qualifiers
2142 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002143 if (isa<ObjCObjectPointerType>(ToType))
2144 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 return Context.getPointerType(ToPointee);
2146 }
2147
2148 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002149 QualType QualifiedCanonToPointee
2150 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002152 if (isa<ObjCObjectPointerType>(ToType))
2153 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2154 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002155}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Mike Stump11289f42009-09-09 15:08:12 +00002157static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002158 bool InOverloadResolution,
2159 ASTContext &Context) {
2160 // Handle value-dependent integral null pointer constants correctly.
2161 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2162 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002163 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002164 return !InOverloadResolution;
2165
Douglas Gregor56751b52009-09-25 04:25:58 +00002166 return Expr->isNullPointerConstant(Context,
2167 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2168 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002169}
Mike Stump11289f42009-09-09 15:08:12 +00002170
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002171/// IsPointerConversion - Determines whether the conversion of the
2172/// expression From, which has the (possibly adjusted) type FromType,
2173/// can be converted to the type ToType via a pointer conversion (C++
2174/// 4.10). If so, returns true and places the converted type (that
2175/// might differ from ToType in its cv-qualifiers at some level) into
2176/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002177///
Douglas Gregora29dc052008-11-27 01:19:21 +00002178/// This routine also supports conversions to and from block pointers
2179/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2180/// pointers to interfaces. FIXME: Once we've determined the
2181/// appropriate overloading rules for Objective-C, we may want to
2182/// split the Objective-C checks into a different routine; however,
2183/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002184/// conversions, so for now they live here. IncompatibleObjC will be
2185/// set if the conversion is an allowed Objective-C conversion that
2186/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002188 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002189 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002190 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002191 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002192 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2193 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002194 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002195
Mike Stump11289f42009-09-09 15:08:12 +00002196 // Conversion from a null pointer constant to any Objective-C pointer type.
2197 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002198 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002199 ConvertedType = ToType;
2200 return true;
2201 }
2202
Douglas Gregor231d1c62008-11-27 00:15:41 +00002203 // Blocks: Block pointers can be converted to void*.
2204 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002205 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002206 ConvertedType = ToType;
2207 return true;
2208 }
2209 // Blocks: A null pointer constant can be converted to a block
2210 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002211 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002212 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002213 ConvertedType = ToType;
2214 return true;
2215 }
2216
Sebastian Redl576fd422009-05-10 18:38:11 +00002217 // If the left-hand-side is nullptr_t, the right side can be a null
2218 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002219 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002220 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002221 ConvertedType = ToType;
2222 return true;
2223 }
2224
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002225 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002226 if (!ToTypePtr)
2227 return false;
2228
2229 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002230 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002231 ConvertedType = ToType;
2232 return true;
2233 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002234
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002235 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002236 // , including objective-c pointers.
2237 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002238 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002239 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002240 ConvertedType = BuildSimilarlyQualifiedPointerType(
2241 FromType->getAs<ObjCObjectPointerType>(),
2242 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002243 ToType, Context);
2244 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002245 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002246 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002247 if (!FromTypePtr)
2248 return false;
2249
2250 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002251
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002253 // pointer conversion, so don't do all of the work below.
2254 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2255 return false;
2256
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002257 // An rvalue of type "pointer to cv T," where T is an object type,
2258 // can be converted to an rvalue of type "pointer to cv void" (C++
2259 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002260 if (FromPointeeType->isIncompleteOrObjectType() &&
2261 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002262 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002263 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002264 ToType, Context,
2265 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002266 return true;
2267 }
2268
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002269 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002270 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002271 ToPointeeType->isVoidType()) {
2272 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2273 ToPointeeType,
2274 ToType, Context);
2275 return true;
2276 }
2277
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002278 // When we're overloading in C, we allow a special kind of pointer
2279 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002280 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002281 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002282 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002283 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002284 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002285 return true;
2286 }
2287
Douglas Gregor5c407d92008-10-23 00:40:37 +00002288 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002289 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002290 // An rvalue of type "pointer to cv D," where D is a class type,
2291 // can be converted to an rvalue of type "pointer to cv B," where
2292 // B is a base class (clause 10) of D. If B is an inaccessible
2293 // (clause 11) or ambiguous (10.2) base class of D, a program that
2294 // necessitates this conversion is ill-formed. The result of the
2295 // conversion is a pointer to the base class sub-object of the
2296 // derived class object. The null pointer value is converted to
2297 // the null pointer value of the destination type.
2298 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002299 // Note that we do not check for ambiguity or inaccessibility
2300 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002301 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002302 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002303 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002304 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002305 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002306 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002307 ToType, Context);
2308 return true;
2309 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002310
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002311 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2312 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2313 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2314 ToPointeeType,
2315 ToType, Context);
2316 return true;
2317 }
2318
Douglas Gregora119f102008-12-19 19:13:09 +00002319 return false;
2320}
Douglas Gregoraec25842011-04-26 23:16:46 +00002321
2322/// \brief Adopt the given qualifiers for the given type.
2323static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2324 Qualifiers TQs = T.getQualifiers();
2325
2326 // Check whether qualifiers already match.
2327 if (TQs == Qs)
2328 return T;
2329
2330 if (Qs.compatiblyIncludes(TQs))
2331 return Context.getQualifiedType(T, Qs);
2332
2333 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2334}
Douglas Gregora119f102008-12-19 19:13:09 +00002335
2336/// isObjCPointerConversion - Determines whether this is an
2337/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2338/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002339bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002340 QualType& ConvertedType,
2341 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002342 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002343 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344
Douglas Gregoraec25842011-04-26 23:16:46 +00002345 // The set of qualifiers on the type we're converting from.
2346 Qualifiers FromQualifiers = FromType.getQualifiers();
2347
Steve Naroff7cae42b2009-07-10 23:34:53 +00002348 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002349 const ObjCObjectPointerType* ToObjCPtr =
2350 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002351 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002352 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002353
Steve Naroff7cae42b2009-07-10 23:34:53 +00002354 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002355 // If the pointee types are the same (ignoring qualifications),
2356 // then this is not a pointer conversion.
2357 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2358 FromObjCPtr->getPointeeType()))
2359 return false;
2360
Douglas Gregorab209d82015-07-07 03:58:42 +00002361 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002362 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002363 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2364 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002365 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002366 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2367 FromObjCPtr->getPointeeType()))
2368 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002370 ToObjCPtr->getPointeeType(),
2371 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002372 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002373 return true;
2374 }
2375
2376 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2377 // Okay: this is some kind of implicit downcast of Objective-C
2378 // interfaces, which is permitted. However, we're going to
2379 // complain about it.
2380 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002381 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002382 ToObjCPtr->getPointeeType(),
2383 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002384 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002385 return true;
2386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002388 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002389 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002390 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002391 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002393 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002394 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002395 // to a block pointer type.
2396 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002397 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002398 return true;
2399 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002400 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002402 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002403 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002405 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002407 return true;
2408 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002409 else
Douglas Gregora119f102008-12-19 19:13:09 +00002410 return false;
2411
Douglas Gregor033f56d2008-12-23 00:53:59 +00002412 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002413 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002414 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002415 else if (const BlockPointerType *FromBlockPtr =
2416 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002417 FromPointeeType = FromBlockPtr->getPointeeType();
2418 else
Douglas Gregora119f102008-12-19 19:13:09 +00002419 return false;
2420
Douglas Gregora119f102008-12-19 19:13:09 +00002421 // If we have pointers to pointers, recursively check whether this
2422 // is an Objective-C conversion.
2423 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2424 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2425 IncompatibleObjC)) {
2426 // We always complain about this conversion.
2427 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002428 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002429 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002430 return true;
2431 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002432 // Allow conversion of pointee being objective-c pointer to another one;
2433 // as in I* to id.
2434 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2435 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2436 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2437 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002438
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002439 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002440 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002441 return true;
2442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002443
Douglas Gregor033f56d2008-12-23 00:53:59 +00002444 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002445 // differences in the argument and result types are in Objective-C
2446 // pointer conversions. If so, we permit the conversion (but
2447 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002448 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002449 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002450 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002451 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002452 if (FromFunctionType && ToFunctionType) {
2453 // If the function types are exactly the same, this isn't an
2454 // Objective-C pointer conversion.
2455 if (Context.getCanonicalType(FromPointeeType)
2456 == Context.getCanonicalType(ToPointeeType))
2457 return false;
2458
2459 // Perform the quick checks that will tell us whether these
2460 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002461 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002462 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2463 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2464 return false;
2465
2466 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002467 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2468 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002469 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002470 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2471 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002472 ConvertedType, IncompatibleObjC)) {
2473 // Okay, we have an Objective-C pointer conversion.
2474 HasObjCConversion = true;
2475 } else {
2476 // Function types are too different. Abort.
2477 return false;
2478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Douglas Gregora119f102008-12-19 19:13:09 +00002480 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002481 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002482 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002485 if (Context.getCanonicalType(FromArgType)
2486 == Context.getCanonicalType(ToArgType)) {
2487 // Okay, the types match exactly. Nothing to do.
2488 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2489 ConvertedType, IncompatibleObjC)) {
2490 // Okay, we have an Objective-C pointer conversion.
2491 HasObjCConversion = true;
2492 } else {
2493 // Argument types are too different. Abort.
2494 return false;
2495 }
2496 }
2497
2498 if (HasObjCConversion) {
2499 // We had an Objective-C conversion. Allow this pointer
2500 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002501 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002502 IncompatibleObjC = true;
2503 return true;
2504 }
2505 }
2506
Sebastian Redl72b597d2009-01-25 19:43:20 +00002507 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002508}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002509
John McCall31168b02011-06-15 23:02:42 +00002510/// \brief Determine whether this is an Objective-C writeback conversion,
2511/// used for parameter passing when performing automatic reference counting.
2512///
2513/// \param FromType The type we're converting form.
2514///
2515/// \param ToType The type we're converting to.
2516///
2517/// \param ConvertedType The type that will be produced after applying
2518/// this conversion.
2519bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2520 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002521 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002522 Context.hasSameUnqualifiedType(FromType, ToType))
2523 return false;
2524
2525 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2526 QualType ToPointee;
2527 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2528 ToPointee = ToPointer->getPointeeType();
2529 else
2530 return false;
2531
2532 Qualifiers ToQuals = ToPointee.getQualifiers();
2533 if (!ToPointee->isObjCLifetimeType() ||
2534 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002535 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002536 return false;
2537
2538 // Argument must be a pointer to __strong to __weak.
2539 QualType FromPointee;
2540 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2541 FromPointee = FromPointer->getPointeeType();
2542 else
2543 return false;
2544
2545 Qualifiers FromQuals = FromPointee.getQualifiers();
2546 if (!FromPointee->isObjCLifetimeType() ||
2547 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2548 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2549 return false;
2550
2551 // Make sure that we have compatible qualifiers.
2552 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2553 if (!ToQuals.compatiblyIncludes(FromQuals))
2554 return false;
2555
2556 // Remove qualifiers from the pointee type we're converting from; they
2557 // aren't used in the compatibility check belong, and we'll be adding back
2558 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2559 FromPointee = FromPointee.getUnqualifiedType();
2560
2561 // The unqualified form of the pointee types must be compatible.
2562 ToPointee = ToPointee.getUnqualifiedType();
2563 bool IncompatibleObjC;
2564 if (Context.typesAreCompatible(FromPointee, ToPointee))
2565 FromPointee = ToPointee;
2566 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2567 IncompatibleObjC))
2568 return false;
2569
2570 /// \brief Construct the type we're converting to, which is a pointer to
2571 /// __autoreleasing pointee.
2572 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2573 ConvertedType = Context.getPointerType(FromPointee);
2574 return true;
2575}
2576
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002577bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2578 QualType& ConvertedType) {
2579 QualType ToPointeeType;
2580 if (const BlockPointerType *ToBlockPtr =
2581 ToType->getAs<BlockPointerType>())
2582 ToPointeeType = ToBlockPtr->getPointeeType();
2583 else
2584 return false;
2585
2586 QualType FromPointeeType;
2587 if (const BlockPointerType *FromBlockPtr =
2588 FromType->getAs<BlockPointerType>())
2589 FromPointeeType = FromBlockPtr->getPointeeType();
2590 else
2591 return false;
2592 // We have pointer to blocks, check whether the only
2593 // differences in the argument and result types are in Objective-C
2594 // pointer conversions. If so, we permit the conversion.
2595
2596 const FunctionProtoType *FromFunctionType
2597 = FromPointeeType->getAs<FunctionProtoType>();
2598 const FunctionProtoType *ToFunctionType
2599 = ToPointeeType->getAs<FunctionProtoType>();
2600
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002601 if (!FromFunctionType || !ToFunctionType)
2602 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002603
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002604 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002605 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002606
2607 // Perform the quick checks that will tell us whether these
2608 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002609 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002610 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2611 return false;
2612
2613 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2614 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2615 if (FromEInfo != ToEInfo)
2616 return false;
2617
2618 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002619 if (Context.hasSameType(FromFunctionType->getReturnType(),
2620 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002621 // Okay, the types match exactly. Nothing to do.
2622 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002623 QualType RHS = FromFunctionType->getReturnType();
2624 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002625 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002626 !RHS.hasQualifiers() && LHS.hasQualifiers())
2627 LHS = LHS.getUnqualifiedType();
2628
2629 if (Context.hasSameType(RHS,LHS)) {
2630 // OK exact match.
2631 } else if (isObjCPointerConversion(RHS, LHS,
2632 ConvertedType, IncompatibleObjC)) {
2633 if (IncompatibleObjC)
2634 return false;
2635 // Okay, we have an Objective-C pointer conversion.
2636 }
2637 else
2638 return false;
2639 }
2640
2641 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002642 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002643 ArgIdx != NumArgs; ++ArgIdx) {
2644 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002645 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2646 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002647 if (Context.hasSameType(FromArgType, ToArgType)) {
2648 // Okay, the types match exactly. Nothing to do.
2649 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2650 ConvertedType, IncompatibleObjC)) {
2651 if (IncompatibleObjC)
2652 return false;
2653 // Okay, we have an Objective-C pointer conversion.
2654 } else
2655 // Argument types are too different. Abort.
2656 return false;
2657 }
John McCall18afab72016-03-01 00:49:02 +00002658 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2659 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002660 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002661
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002662 ConvertedType = ToType;
2663 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002664}
2665
Richard Trieucaff2472011-11-23 22:32:32 +00002666enum {
2667 ft_default,
2668 ft_different_class,
2669 ft_parameter_arity,
2670 ft_parameter_mismatch,
2671 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002672 ft_qualifer_mismatch,
2673 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002674};
2675
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002676/// Attempts to get the FunctionProtoType from a Type. Handles
2677/// MemberFunctionPointers properly.
2678static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2679 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2680 return FPT;
2681
2682 if (auto *MPT = FromType->getAs<MemberPointerType>())
2683 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2684
2685 return nullptr;
2686}
2687
Richard Trieucaff2472011-11-23 22:32:32 +00002688/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2689/// function types. Catches different number of parameter, mismatch in
2690/// parameter types, and different return types.
2691void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2692 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002693 // If either type is not valid, include no extra info.
2694 if (FromType.isNull() || ToType.isNull()) {
2695 PDiag << ft_default;
2696 return;
2697 }
2698
Richard Trieucaff2472011-11-23 22:32:32 +00002699 // Get the function type from the pointers.
2700 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2701 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2702 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002703 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002704 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2705 << QualType(FromMember->getClass(), 0);
2706 return;
2707 }
2708 FromType = FromMember->getPointeeType();
2709 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002710 }
2711
Richard Trieu96ed5b62011-12-13 23:19:45 +00002712 if (FromType->isPointerType())
2713 FromType = FromType->getPointeeType();
2714 if (ToType->isPointerType())
2715 ToType = ToType->getPointeeType();
2716
2717 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002718 FromType = FromType.getNonReferenceType();
2719 ToType = ToType.getNonReferenceType();
2720
Richard Trieucaff2472011-11-23 22:32:32 +00002721 // Don't print extra info for non-specialized template functions.
2722 if (FromType->isInstantiationDependentType() &&
2723 !FromType->getAs<TemplateSpecializationType>()) {
2724 PDiag << ft_default;
2725 return;
2726 }
2727
Richard Trieu96ed5b62011-12-13 23:19:45 +00002728 // No extra info for same types.
2729 if (Context.hasSameType(FromType, ToType)) {
2730 PDiag << ft_default;
2731 return;
2732 }
2733
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002734 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2735 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002736
2737 // Both types need to be function types.
2738 if (!FromFunction || !ToFunction) {
2739 PDiag << ft_default;
2740 return;
2741 }
2742
Alp Toker9cacbab2014-01-20 20:26:09 +00002743 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2744 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2745 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002746 return;
2747 }
2748
2749 // Handle different parameter types.
2750 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002751 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002752 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002753 << ToFunction->getParamType(ArgPos)
2754 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002755 return;
2756 }
2757
2758 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002759 if (!Context.hasSameType(FromFunction->getReturnType(),
2760 ToFunction->getReturnType())) {
2761 PDiag << ft_return_type << ToFunction->getReturnType()
2762 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002763 return;
2764 }
2765
2766 unsigned FromQuals = FromFunction->getTypeQuals(),
2767 ToQuals = ToFunction->getTypeQuals();
2768 if (FromQuals != ToQuals) {
2769 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2770 return;
2771 }
2772
Richard Smith3c4f8d22016-10-16 17:54:23 +00002773 // Handle exception specification differences on canonical type (in C++17
2774 // onwards).
2775 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2776 ->isNothrow(Context) !=
2777 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2778 ->isNothrow(Context)) {
2779 PDiag << ft_noexcept;
2780 return;
2781 }
2782
Richard Trieucaff2472011-11-23 22:32:32 +00002783 // Unable to find a difference, so add no extra info.
2784 PDiag << ft_default;
2785}
2786
Alp Toker9cacbab2014-01-20 20:26:09 +00002787/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002788/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002789/// they have same number of arguments. If the parameters are different,
2790/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002791bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2792 const FunctionProtoType *NewType,
2793 unsigned *ArgPos) {
2794 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2795 N = NewType->param_type_begin(),
2796 E = OldType->param_type_end();
2797 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002798 if (!Context.hasSameType(O->getUnqualifiedType(),
2799 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002800 if (ArgPos)
2801 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002802 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002803 }
2804 }
2805 return true;
2806}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002807
Douglas Gregor39c16d42008-10-24 04:54:22 +00002808/// CheckPointerConversion - Check the pointer conversion from the
2809/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002810/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002811/// conversions for which IsPointerConversion has already returned
2812/// true. It returns true and produces a diagnostic if there was an
2813/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002814bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002815 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002816 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002817 bool IgnoreBaseAccess,
2818 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002819 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002820 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002821
John McCall8cb679e2010-11-15 09:13:47 +00002822 Kind = CK_BitCast;
2823
George Burgess IV60bc9722016-01-13 23:36:34 +00002824 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002825 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002826 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002827 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2828 DiagRuntimeBehavior(From->getExprLoc(), From,
2829 PDiag(diag::warn_impcast_bool_to_null_pointer)
2830 << ToType << From->getSourceRange());
2831 else if (!isUnevaluatedContext())
2832 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2833 << ToType << From->getSourceRange();
2834 }
John McCall9320b872011-09-09 05:25:32 +00002835 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2836 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002837 QualType FromPointeeType = FromPtrType->getPointeeType(),
2838 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002839
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002840 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2841 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002842 // We must have a derived-to-base conversion. Check an
2843 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002844 unsigned InaccessibleID = 0;
2845 unsigned AmbigiousID = 0;
2846 if (Diagnose) {
2847 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2848 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2849 }
2850 if (CheckDerivedToBaseConversion(
2851 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2852 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2853 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002854 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002856 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002857 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002858 }
David Majnemer6bf02822015-10-31 08:42:14 +00002859
George Burgess IV60bc9722016-01-13 23:36:34 +00002860 if (Diagnose && !IsCStyleOrFunctionalCast &&
2861 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002862 assert(getLangOpts().MSVCCompat &&
2863 "this should only be possible with MSVCCompat!");
2864 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2865 << From->getSourceRange();
2866 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002867 }
John McCall9320b872011-09-09 05:25:32 +00002868 } else if (const ObjCObjectPointerType *ToPtrType =
2869 ToType->getAs<ObjCObjectPointerType>()) {
2870 if (const ObjCObjectPointerType *FromPtrType =
2871 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002872 // Objective-C++ conversions are always okay.
2873 // FIXME: We should have a different class of conversions for the
2874 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002875 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002876 return false;
John McCall9320b872011-09-09 05:25:32 +00002877 } else if (FromType->isBlockPointerType()) {
2878 Kind = CK_BlockPointerToObjCPointerCast;
2879 } else {
2880 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002881 }
John McCall9320b872011-09-09 05:25:32 +00002882 } else if (ToType->isBlockPointerType()) {
2883 if (!FromType->isBlockPointerType())
2884 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002885 }
John McCall8cb679e2010-11-15 09:13:47 +00002886
2887 // We shouldn't fall into this case unless it's valid for other
2888 // reasons.
2889 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2890 Kind = CK_NullToPointer;
2891
Douglas Gregor39c16d42008-10-24 04:54:22 +00002892 return false;
2893}
2894
Sebastian Redl72b597d2009-01-25 19:43:20 +00002895/// IsMemberPointerConversion - Determines whether the conversion of the
2896/// expression From, which has the (possibly adjusted) type FromType, can be
2897/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2898/// If so, returns true and places the converted type (that might differ from
2899/// ToType in its cv-qualifiers at some level) into ConvertedType.
2900bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002901 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002902 bool InOverloadResolution,
2903 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002904 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002905 if (!ToTypePtr)
2906 return false;
2907
2908 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002909 if (From->isNullPointerConstant(Context,
2910 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2911 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002912 ConvertedType = ToType;
2913 return true;
2914 }
2915
2916 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002917 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002918 if (!FromTypePtr)
2919 return false;
2920
2921 // A pointer to member of B can be converted to a pointer to member of D,
2922 // where D is derived from B (C++ 4.11p2).
2923 QualType FromClass(FromTypePtr->getClass(), 0);
2924 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002925
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002926 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002927 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002928 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2929 ToClass.getTypePtr());
2930 return true;
2931 }
2932
2933 return false;
2934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
Sebastian Redl72b597d2009-01-25 19:43:20 +00002936/// CheckMemberPointerConversion - Check the member pointer conversion from the
2937/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002938/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002939/// for which IsMemberPointerConversion has already returned true. It returns
2940/// true and produces a diagnostic if there was an error, or returns false
2941/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002942bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002943 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002944 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002945 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002946 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002947 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002948 if (!FromPtrType) {
2949 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002951 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002952 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002953 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002954 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002955 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002956
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002957 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002958 assert(ToPtrType && "No member pointer cast has a target type "
2959 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002960
Sebastian Redled8f2002009-01-28 18:33:18 +00002961 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2962 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002963
Sebastian Redled8f2002009-01-28 18:33:18 +00002964 // FIXME: What about dependent types?
2965 assert(FromClass->isRecordType() && "Pointer into non-class.");
2966 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002967
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002968 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002969 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002970 bool DerivationOkay =
2971 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002972 assert(DerivationOkay &&
2973 "Should not have been called if derivation isn't OK.");
2974 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002975
Sebastian Redled8f2002009-01-28 18:33:18 +00002976 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2977 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002978 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2979 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2980 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2981 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002982 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002983
Douglas Gregor89ee6822009-02-28 01:32:25 +00002984 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002985 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2986 << FromClass << ToClass << QualType(VBase, 0)
2987 << From->getSourceRange();
2988 return true;
2989 }
2990
John McCall5b0829a2010-02-10 09:31:12 +00002991 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002992 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2993 Paths.front(),
2994 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002995
Anders Carlssond7923c62009-08-22 23:33:40 +00002996 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002997 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002998 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002999 return false;
3000}
3001
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003002/// Determine whether the lifetime conversion between the two given
3003/// qualifiers sets is nontrivial.
3004static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3005 Qualifiers ToQuals) {
3006 // Converting anything to const __unsafe_unretained is trivial.
3007 if (ToQuals.hasConst() &&
3008 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3009 return false;
3010
3011 return true;
3012}
3013
Douglas Gregor9a657932008-10-21 23:43:52 +00003014/// IsQualificationConversion - Determines whether the conversion from
3015/// an rvalue of type FromType to ToType is a qualification conversion
3016/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003017///
3018/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3019/// when the qualification conversion involves a change in the Objective-C
3020/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003021bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003023 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003024 FromType = Context.getCanonicalType(FromType);
3025 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003026 ObjCLifetimeConversion = false;
3027
Douglas Gregor9a657932008-10-21 23:43:52 +00003028 // If FromType and ToType are the same type, this is not a
3029 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003030 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003031 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003032
Douglas Gregor9a657932008-10-21 23:43:52 +00003033 // (C++ 4.4p4):
3034 // A conversion can add cv-qualifiers at levels other than the first
3035 // in multi-level pointers, subject to the following rules: [...]
3036 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003037 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003038 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003039 // Within each iteration of the loop, we check the qualifiers to
3040 // determine if this still looks like a qualification
3041 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003042 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003043 // until there are no more pointers or pointers-to-members left to
3044 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003045 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003046
Douglas Gregor90609aa2011-04-25 18:40:17 +00003047 Qualifiers FromQuals = FromType.getQualifiers();
3048 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003049
3050 // Ignore __unaligned qualifier if this type is void.
3051 if (ToType.getUnqualifiedType()->isVoidType())
3052 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003053
John McCall31168b02011-06-15 23:02:42 +00003054 // Objective-C ARC:
3055 // Check Objective-C lifetime conversions.
3056 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3057 UnwrappedAnyPointer) {
3058 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003059 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3060 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003061 FromQuals.removeObjCLifetime();
3062 ToQuals.removeObjCLifetime();
3063 } else {
3064 // Qualification conversions cannot cast between different
3065 // Objective-C lifetime qualifiers.
3066 return false;
3067 }
3068 }
3069
Douglas Gregorf30053d2011-05-08 06:09:53 +00003070 // Allow addition/removal of GC attributes but not changing GC attributes.
3071 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3072 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3073 FromQuals.removeObjCGCAttr();
3074 ToQuals.removeObjCGCAttr();
3075 }
3076
Douglas Gregor9a657932008-10-21 23:43:52 +00003077 // -- for every j > 0, if const is in cv 1,j then const is in cv
3078 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003079 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003080 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003081
Douglas Gregor9a657932008-10-21 23:43:52 +00003082 // -- if the cv 1,j and cv 2,j are different, then const is in
3083 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003084 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003085 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003086 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003087
Douglas Gregor9a657932008-10-21 23:43:52 +00003088 // Keep track of whether all prior cv-qualifiers in the "to" type
3089 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003090 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003091 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003092 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003093
3094 // We are left with FromType and ToType being the pointee types
3095 // after unwrapping the original FromType and ToType the same number
3096 // of types. If we unwrapped any pointers, and if FromType and
3097 // ToType have the same unqualified type (since we checked
3098 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003099 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003100}
3101
Douglas Gregorc79862f2012-04-12 17:51:55 +00003102/// \brief - Determine whether this is a conversion from a scalar type to an
3103/// atomic type.
3104///
3105/// If successful, updates \c SCS's second and third steps in the conversion
3106/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003107static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3108 bool InOverloadResolution,
3109 StandardConversionSequence &SCS,
3110 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003111 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3112 if (!ToAtomic)
3113 return false;
3114
3115 StandardConversionSequence InnerSCS;
3116 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3117 InOverloadResolution, InnerSCS,
3118 CStyle, /*AllowObjCWritebackConversion=*/false))
3119 return false;
3120
3121 SCS.Second = InnerSCS.Second;
3122 SCS.setToType(1, InnerSCS.getToType(1));
3123 SCS.Third = InnerSCS.Third;
3124 SCS.QualificationIncludesObjCLifetime
3125 = InnerSCS.QualificationIncludesObjCLifetime;
3126 SCS.setToType(2, InnerSCS.getToType(2));
3127 return true;
3128}
3129
Sebastian Redle5417162012-03-27 18:33:03 +00003130static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3131 CXXConstructorDecl *Constructor,
3132 QualType Type) {
3133 const FunctionProtoType *CtorType =
3134 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003135 if (CtorType->getNumParams() > 0) {
3136 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003137 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3138 return true;
3139 }
3140 return false;
3141}
3142
Sebastian Redl82ace982012-02-11 23:51:08 +00003143static OverloadingResult
3144IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3145 CXXRecordDecl *To,
3146 UserDefinedConversionSequence &User,
3147 OverloadCandidateSet &CandidateSet,
3148 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003149 for (auto *D : S.LookupConstructors(To)) {
3150 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003151 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003152 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003153
Richard Smithc2bebe92016-05-11 20:37:46 +00003154 bool Usable = !Info.Constructor->isInvalidDecl() &&
3155 S.isInitListConstructor(Info.Constructor) &&
3156 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003157 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003158 // If the first argument is (a reference to) the target type,
3159 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003160 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3161 S.Context, Info.Constructor, ToType);
3162 if (Info.ConstructorTmpl)
3163 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3164 /*ExplicitArgs*/ nullptr, From,
3165 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003166 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003167 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3168 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003169 }
3170 }
3171
3172 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3173
3174 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003175 switch (auto Result =
3176 CandidateSet.BestViableFunction(S, From->getLocStart(),
3177 Best, true)) {
3178 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003179 case OR_Success: {
3180 // Record the standard conversion we used and the conversion function.
3181 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003182 QualType ThisType = Constructor->getThisType(S.Context);
3183 // Initializer lists don't have conversions as such.
3184 User.Before.setAsIdentityConversion();
3185 User.HadMultipleCandidates = HadMultipleCandidates;
3186 User.ConversionFunction = Constructor;
3187 User.FoundConversionFunction = Best->FoundDecl;
3188 User.After.setAsIdentityConversion();
3189 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3190 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003191 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003192 }
3193
3194 case OR_No_Viable_Function:
3195 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003196 case OR_Ambiguous:
3197 return OR_Ambiguous;
3198 }
3199
3200 llvm_unreachable("Invalid OverloadResult!");
3201}
3202
Douglas Gregor576e98c2009-01-30 23:27:23 +00003203/// Determines whether there is a user-defined conversion sequence
3204/// (C++ [over.ics.user]) that converts expression From to the type
3205/// ToType. If such a conversion exists, User will contain the
3206/// user-defined conversion sequence that performs such a conversion
3207/// and this routine will return true. Otherwise, this routine returns
3208/// false and User is unspecified.
3209///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003210/// \param AllowExplicit true if the conversion should consider C++0x
3211/// "explicit" conversion functions as well as non-explicit conversion
3212/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003213///
3214/// \param AllowObjCConversionOnExplicit true if the conversion should
3215/// allow an extra Objective-C pointer conversion on uses of explicit
3216/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003217static OverloadingResult
3218IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003219 UserDefinedConversionSequence &User,
3220 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003221 bool AllowExplicit,
3222 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003223 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003224
Douglas Gregor5ab11652010-04-17 22:01:05 +00003225 // Whether we will only visit constructors.
3226 bool ConstructorsOnly = false;
3227
3228 // If the type we are conversion to is a class type, enumerate its
3229 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003230 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003231 // C++ [over.match.ctor]p1:
3232 // When objects of class type are direct-initialized (8.5), or
3233 // copy-initialized from an expression of the same or a
3234 // derived class type (8.5), overload resolution selects the
3235 // constructor. [...] For copy-initialization, the candidate
3236 // functions are all the converting constructors (12.3.1) of
3237 // that class. The argument list is the expression-list within
3238 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003239 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003240 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003241 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003242 ConstructorsOnly = true;
3243
Richard Smithdb0ac552015-12-18 22:40:25 +00003244 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003245 // We're not going to find any constructors.
3246 } else if (CXXRecordDecl *ToRecordDecl
3247 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003248
3249 Expr **Args = &From;
3250 unsigned NumArgs = 1;
3251 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003252 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003253 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003254 OverloadingResult Result = IsInitializerListConstructorConversion(
3255 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3256 if (Result != OR_No_Viable_Function)
3257 return Result;
3258 // Never mind.
3259 CandidateSet.clear();
3260
3261 // If we're list-initializing, we pass the individual elements as
3262 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003263 Args = InitList->getInits();
3264 NumArgs = InitList->getNumInits();
3265 ListInitializing = true;
3266 }
3267
Richard Smithc2bebe92016-05-11 20:37:46 +00003268 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3269 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003270 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003271 continue;
John McCalla0296f72010-03-19 07:35:19 +00003272
Richard Smithc2bebe92016-05-11 20:37:46 +00003273 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003274 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003275 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003276 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003277 Usable = Usable &&
3278 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003279 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003280 bool SuppressUserConversions = !ConstructorsOnly;
3281 if (SuppressUserConversions && ListInitializing) {
3282 SuppressUserConversions = false;
3283 if (NumArgs == 1) {
3284 // If the first argument is (a reference to) the target type,
3285 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003286 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003287 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003288 }
3289 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003290 if (Info.ConstructorTmpl)
3291 S.AddTemplateOverloadCandidate(
3292 Info.ConstructorTmpl, Info.FoundDecl,
3293 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3294 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003295 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003296 // Allow one user-defined conversion when user specifies a
3297 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003298 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003299 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003300 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003301 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003302 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003303 }
3304 }
3305
Douglas Gregor5ab11652010-04-17 22:01:05 +00003306 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003307 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003308 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003309 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003310 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003311 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003312 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003313 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3314 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003315 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3316 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003317 DeclAccessPair FoundDecl = I.getPair();
3318 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003319 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3320 if (isa<UsingShadowDecl>(D))
3321 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3322
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003323 CXXConversionDecl *Conv;
3324 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003325 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3326 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003327 else
John McCallda4458e2010-03-31 01:36:47 +00003328 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003329
3330 if (AllowExplicit || !Conv->isExplicit()) {
3331 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003332 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3333 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003334 CandidateSet,
3335 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003336 else
John McCall5c32be02010-08-24 20:38:10 +00003337 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003338 From, ToType, CandidateSet,
3339 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003340 }
3341 }
3342 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003343 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003344
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3346
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003347 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003348 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3349 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003350 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003351 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003352 // Record the standard conversion we used and the conversion function.
3353 if (CXXConstructorDecl *Constructor
3354 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3355 // C++ [over.ics.user]p1:
3356 // If the user-defined conversion is specified by a
3357 // constructor (12.3.1), the initial standard conversion
3358 // sequence converts the source type to the type required by
3359 // the argument of the constructor.
3360 //
3361 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003362 if (isa<InitListExpr>(From)) {
3363 // Initializer lists don't have conversions as such.
3364 User.Before.setAsIdentityConversion();
3365 } else {
3366 if (Best->Conversions[0].isEllipsis())
3367 User.EllipsisConversion = true;
3368 else {
3369 User.Before = Best->Conversions[0].Standard;
3370 User.EllipsisConversion = false;
3371 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003372 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003373 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003374 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003375 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003376 User.After.setAsIdentityConversion();
3377 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3378 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003379 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003380 }
3381 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003382 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3383 // C++ [over.ics.user]p1:
3384 //
3385 // [...] If the user-defined conversion is specified by a
3386 // conversion function (12.3.2), the initial standard
3387 // conversion sequence converts the source type to the
3388 // implicit object parameter of the conversion function.
3389 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003390 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003391 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003392 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003393 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003394
John McCall5c32be02010-08-24 20:38:10 +00003395 // C++ [over.ics.user]p2:
3396 // The second standard conversion sequence converts the
3397 // result of the user-defined conversion to the target type
3398 // for the sequence. Since an implicit conversion sequence
3399 // is an initialization, the special rules for
3400 // initialization by user-defined conversion apply when
3401 // selecting the best user-defined conversion for a
3402 // user-defined conversion sequence (see 13.3.3 and
3403 // 13.3.3.1).
3404 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003405 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003406 }
David Blaikie8a40f702012-01-17 06:56:22 +00003407 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003408
John McCall5c32be02010-08-24 20:38:10 +00003409 case OR_No_Viable_Function:
3410 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
John McCall5c32be02010-08-24 20:38:10 +00003412 case OR_Ambiguous:
3413 return OR_Ambiguous;
3414 }
3415
David Blaikie8a40f702012-01-17 06:56:22 +00003416 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003417}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003419bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003420Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003421 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003422 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3423 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003425 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003426 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003427 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003428 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3429 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003430 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003431 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003432 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003433 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003434 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003435 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003436 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003437 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003438 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003440}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003441
Douglas Gregor2837aa22012-02-22 17:32:19 +00003442/// \brief Compare the user-defined conversion functions or constructors
3443/// of two user-defined conversion sequences to determine whether any ordering
3444/// is possible.
3445static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003446compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003447 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003448 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003449 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003450
Douglas Gregor2837aa22012-02-22 17:32:19 +00003451 // Objective-C++:
3452 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003453 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003454 // respectively, always prefer the conversion to a function pointer,
3455 // because the function pointer is more lightweight and is more likely
3456 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003457 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003458 if (!Conv1)
3459 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003460
Douglas Gregor2837aa22012-02-22 17:32:19 +00003461 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3462 if (!Conv2)
3463 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003464
Douglas Gregor2837aa22012-02-22 17:32:19 +00003465 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3466 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3467 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3468 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003469 return Block1 ? ImplicitConversionSequence::Worse
3470 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003471 }
3472
3473 return ImplicitConversionSequence::Indistinguishable;
3474}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003475
3476static bool hasDeprecatedStringLiteralToCharPtrConversion(
3477 const ImplicitConversionSequence &ICS) {
3478 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3479 (ICS.isUserDefined() &&
3480 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3481}
3482
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003483/// CompareImplicitConversionSequences - Compare two implicit
3484/// conversion sequences to determine whether one is better than the
3485/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003486static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003487CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003488 const ImplicitConversionSequence& ICS1,
3489 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003490{
3491 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3492 // conversion sequences (as defined in 13.3.3.1)
3493 // -- a standard conversion sequence (13.3.3.1.1) is a better
3494 // conversion sequence than a user-defined conversion sequence or
3495 // an ellipsis conversion sequence, and
3496 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3497 // conversion sequence than an ellipsis conversion sequence
3498 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003499 //
John McCall0d1da222010-01-12 00:44:57 +00003500 // C++0x [over.best.ics]p10:
3501 // For the purpose of ranking implicit conversion sequences as
3502 // described in 13.3.3.2, the ambiguous conversion sequence is
3503 // treated as a user-defined sequence that is indistinguishable
3504 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003505
3506 // String literal to 'char *' conversion has been deprecated in C++03. It has
3507 // been removed from C++11. We still accept this conversion, if it happens at
3508 // the best viable function. Otherwise, this conversion is considered worse
3509 // than ellipsis conversion. Consider this as an extension; this is not in the
3510 // standard. For example:
3511 //
3512 // int &f(...); // #1
3513 // void f(char*); // #2
3514 // void g() { int &r = f("foo"); }
3515 //
3516 // In C++03, we pick #2 as the best viable function.
3517 // In C++11, we pick #1 as the best viable function, because ellipsis
3518 // conversion is better than string-literal to char* conversion (since there
3519 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3520 // convert arguments, #2 would be the best viable function in C++11.
3521 // If the best viable function has this conversion, a warning will be issued
3522 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3523
3524 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3525 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3526 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3527 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3528 ? ImplicitConversionSequence::Worse
3529 : ImplicitConversionSequence::Better;
3530
Douglas Gregor5ab11652010-04-17 22:01:05 +00003531 if (ICS1.getKindRank() < ICS2.getKindRank())
3532 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003533 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003534 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003535
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003536 // The following checks require both conversion sequences to be of
3537 // the same kind.
3538 if (ICS1.getKind() != ICS2.getKind())
3539 return ImplicitConversionSequence::Indistinguishable;
3540
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003541 ImplicitConversionSequence::CompareKind Result =
3542 ImplicitConversionSequence::Indistinguishable;
3543
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003544 // Two implicit conversion sequences of the same form are
3545 // indistinguishable conversion sequences unless one of the
3546 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003547
3548 // List-initialization sequence L1 is a better conversion sequence than
3549 // list-initialization sequence L2 if:
3550 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3551 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003552 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003553 // and N1 is smaller than N2.,
3554 // even if one of the other rules in this paragraph would otherwise apply.
3555 if (!ICS1.isBad()) {
3556 if (ICS1.isStdInitializerListElement() &&
3557 !ICS2.isStdInitializerListElement())
3558 return ImplicitConversionSequence::Better;
3559 if (!ICS1.isStdInitializerListElement() &&
3560 ICS2.isStdInitializerListElement())
3561 return ImplicitConversionSequence::Worse;
3562 }
3563
John McCall0d1da222010-01-12 00:44:57 +00003564 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003565 // Standard conversion sequence S1 is a better conversion sequence than
3566 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003567 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003568 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003569 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003570 // User-defined conversion sequence U1 is a better conversion
3571 // sequence than another user-defined conversion sequence U2 if
3572 // they contain the same user-defined conversion function or
3573 // constructor and if the second standard conversion sequence of
3574 // U1 is better than the second standard conversion sequence of
3575 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003576 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003577 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003578 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003579 ICS1.UserDefined.After,
3580 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003581 else
3582 Result = compareConversionFunctions(S,
3583 ICS1.UserDefined.ConversionFunction,
3584 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003585 }
3586
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003587 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003588}
3589
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003590static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3591 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3592 Qualifiers Quals;
3593 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003597 return Context.hasSameUnqualifiedType(T1, T2);
3598}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003600// Per 13.3.3.2p3, compare the given standard conversion sequences to
3601// determine if one is a proper subset of the other.
3602static ImplicitConversionSequence::CompareKind
3603compareStandardConversionSubsets(ASTContext &Context,
3604 const StandardConversionSequence& SCS1,
3605 const StandardConversionSequence& SCS2) {
3606 ImplicitConversionSequence::CompareKind Result
3607 = ImplicitConversionSequence::Indistinguishable;
3608
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003610 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003611 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3612 return ImplicitConversionSequence::Better;
3613 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3614 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003616 if (SCS1.Second != SCS2.Second) {
3617 if (SCS1.Second == ICK_Identity)
3618 Result = ImplicitConversionSequence::Better;
3619 else if (SCS2.Second == ICK_Identity)
3620 Result = ImplicitConversionSequence::Worse;
3621 else
3622 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003623 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003624 return ImplicitConversionSequence::Indistinguishable;
3625
3626 if (SCS1.Third == SCS2.Third) {
3627 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3628 : ImplicitConversionSequence::Indistinguishable;
3629 }
3630
3631 if (SCS1.Third == ICK_Identity)
3632 return Result == ImplicitConversionSequence::Worse
3633 ? ImplicitConversionSequence::Indistinguishable
3634 : ImplicitConversionSequence::Better;
3635
3636 if (SCS2.Third == ICK_Identity)
3637 return Result == ImplicitConversionSequence::Better
3638 ? ImplicitConversionSequence::Indistinguishable
3639 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003641 return ImplicitConversionSequence::Indistinguishable;
3642}
3643
Douglas Gregore696ebb2011-01-26 14:52:12 +00003644/// \brief Determine whether one of the given reference bindings is better
3645/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003646static bool
3647isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3648 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003649 // C++0x [over.ics.rank]p3b4:
3650 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3651 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003653 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003655 // reference*.
3656 //
3657 // FIXME: Rvalue references. We're going rogue with the above edits,
3658 // because the semantics in the current C++0x working paper (N3225 at the
3659 // time of this writing) break the standard definition of std::forward
3660 // and std::reference_wrapper when dealing with references to functions.
3661 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003662 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3663 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3664 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665
Douglas Gregore696ebb2011-01-26 14:52:12 +00003666 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3667 SCS2.IsLvalueReference) ||
3668 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003669 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003670}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003672/// CompareStandardConversionSequences - Compare two standard
3673/// conversion sequences to determine whether one is better than the
3674/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003675static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003676CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003677 const StandardConversionSequence& SCS1,
3678 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003679{
3680 // Standard conversion sequence S1 is a better conversion sequence
3681 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3682
3683 // -- S1 is a proper subsequence of S2 (comparing the conversion
3684 // sequences in the canonical form defined by 13.3.3.1.1,
3685 // excluding any Lvalue Transformation; the identity conversion
3686 // sequence is considered to be a subsequence of any
3687 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003688 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003689 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003690 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003691
3692 // -- the rank of S1 is better than the rank of S2 (by the rules
3693 // defined below), or, if not that,
3694 ImplicitConversionRank Rank1 = SCS1.getRank();
3695 ImplicitConversionRank Rank2 = SCS2.getRank();
3696 if (Rank1 < Rank2)
3697 return ImplicitConversionSequence::Better;
3698 else if (Rank2 < Rank1)
3699 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003700
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003701 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3702 // are indistinguishable unless one of the following rules
3703 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003705 // A conversion that is not a conversion of a pointer, or
3706 // pointer to member, to bool is better than another conversion
3707 // that is such a conversion.
3708 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3709 return SCS2.isPointerConversionToBool()
3710 ? ImplicitConversionSequence::Better
3711 : ImplicitConversionSequence::Worse;
3712
Douglas Gregor5c407d92008-10-23 00:40:37 +00003713 // C++ [over.ics.rank]p4b2:
3714 //
3715 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003716 // conversion of B* to A* is better than conversion of B* to
3717 // void*, and conversion of A* to void* is better than conversion
3718 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003719 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003720 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003721 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003722 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003723 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3724 // Exactly one of the conversion sequences is a conversion to
3725 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003726 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3727 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003728 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3729 // Neither conversion sequence converts to a void pointer; compare
3730 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003731 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003732 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003733 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003734 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3735 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003736 // Both conversion sequences are conversions to void
3737 // pointers. Compare the source types to determine if there's an
3738 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003739 QualType FromType1 = SCS1.getFromType();
3740 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003741
3742 // Adjust the types we're converting from via the array-to-pointer
3743 // conversion, if we need to.
3744 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003745 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003746 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003747 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003748
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003749 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3750 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003751
Richard Smith0f59cb32015-12-18 21:45:41 +00003752 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003753 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003754 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003755 return ImplicitConversionSequence::Worse;
3756
3757 // Objective-C++: If one interface is more specific than the
3758 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003759 const ObjCObjectPointerType* FromObjCPtr1
3760 = FromType1->getAs<ObjCObjectPointerType>();
3761 const ObjCObjectPointerType* FromObjCPtr2
3762 = FromType2->getAs<ObjCObjectPointerType>();
3763 if (FromObjCPtr1 && FromObjCPtr2) {
3764 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3765 FromObjCPtr2);
3766 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3767 FromObjCPtr1);
3768 if (AssignLeft != AssignRight) {
3769 return AssignLeft? ImplicitConversionSequence::Better
3770 : ImplicitConversionSequence::Worse;
3771 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003772 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003773 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003774
3775 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3776 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003777 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003778 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003779 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003780
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003782 // Check for a better reference binding based on the kind of bindings.
3783 if (isBetterReferenceBindingKind(SCS1, SCS2))
3784 return ImplicitConversionSequence::Better;
3785 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3786 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Sebastian Redlb28b4072009-03-22 23:49:27 +00003788 // C++ [over.ics.rank]p3b4:
3789 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3790 // which the references refer are the same type except for
3791 // top-level cv-qualifiers, and the type to which the reference
3792 // initialized by S2 refers is more cv-qualified than the type
3793 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003794 QualType T1 = SCS1.getToType(2);
3795 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003796 T1 = S.Context.getCanonicalType(T1);
3797 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003798 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003799 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3800 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003801 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003802 // Objective-C++ ARC: If the references refer to objects with different
3803 // lifetimes, prefer bindings that don't change lifetime.
3804 if (SCS1.ObjCLifetimeConversionBinding !=
3805 SCS2.ObjCLifetimeConversionBinding) {
3806 return SCS1.ObjCLifetimeConversionBinding
3807 ? ImplicitConversionSequence::Worse
3808 : ImplicitConversionSequence::Better;
3809 }
3810
Chandler Carruth8e543b32010-12-12 08:17:55 +00003811 // If the type is an array type, promote the element qualifiers to the
3812 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003813 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003814 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003815 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003816 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003817 if (T2.isMoreQualifiedThan(T1))
3818 return ImplicitConversionSequence::Better;
3819 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003820 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003821 }
3822 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003823
Francois Pichet08d2fa02011-09-18 21:37:37 +00003824 // In Microsoft mode, prefer an integral conversion to a
3825 // floating-to-integral conversion if the integral conversion
3826 // is between types of the same size.
3827 // For example:
3828 // void f(float);
3829 // void f(int);
3830 // int main {
3831 // long a;
3832 // f(a);
3833 // }
3834 // Here, MSVC will call f(int) instead of generating a compile error
3835 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003836 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3837 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003838 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003839 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003840 return ImplicitConversionSequence::Better;
3841
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003842 return ImplicitConversionSequence::Indistinguishable;
3843}
3844
3845/// CompareQualificationConversions - Compares two standard conversion
3846/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003847/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003848static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003849CompareQualificationConversions(Sema &S,
3850 const StandardConversionSequence& SCS1,
3851 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003852 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003853 // -- S1 and S2 differ only in their qualification conversion and
3854 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3855 // cv-qualification signature of type T1 is a proper subset of
3856 // the cv-qualification signature of type T2, and S1 is not the
3857 // deprecated string literal array-to-pointer conversion (4.2).
3858 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3859 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3860 return ImplicitConversionSequence::Indistinguishable;
3861
3862 // FIXME: the example in the standard doesn't use a qualification
3863 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003864 QualType T1 = SCS1.getToType(2);
3865 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003866 T1 = S.Context.getCanonicalType(T1);
3867 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003868 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003869 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3870 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003871
3872 // If the types are the same, we won't learn anything by unwrapped
3873 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003874 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003875 return ImplicitConversionSequence::Indistinguishable;
3876
Chandler Carruth607f38e2009-12-29 07:16:59 +00003877 // If the type is an array type, promote the element qualifiers to the type
3878 // for comparison.
3879 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003880 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003881 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003882 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003883
Mike Stump11289f42009-09-09 15:08:12 +00003884 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003885 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003886
3887 // Objective-C++ ARC:
3888 // Prefer qualification conversions not involving a change in lifetime
3889 // to qualification conversions that do not change lifetime.
3890 if (SCS1.QualificationIncludesObjCLifetime !=
3891 SCS2.QualificationIncludesObjCLifetime) {
3892 Result = SCS1.QualificationIncludesObjCLifetime
3893 ? ImplicitConversionSequence::Worse
3894 : ImplicitConversionSequence::Better;
3895 }
3896
John McCall5c32be02010-08-24 20:38:10 +00003897 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003898 // Within each iteration of the loop, we check the qualifiers to
3899 // determine if this still looks like a qualification
3900 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003901 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003902 // until there are no more pointers or pointers-to-members left
3903 // to unwrap. This essentially mimics what
3904 // IsQualificationConversion does, but here we're checking for a
3905 // strict subset of qualifiers.
3906 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3907 // The qualifiers are the same, so this doesn't tell us anything
3908 // about how the sequences rank.
3909 ;
3910 else if (T2.isMoreQualifiedThan(T1)) {
3911 // T1 has fewer qualifiers, so it could be the better sequence.
3912 if (Result == ImplicitConversionSequence::Worse)
3913 // Neither has qualifiers that are a subset of the other's
3914 // qualifiers.
3915 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003916
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003917 Result = ImplicitConversionSequence::Better;
3918 } else if (T1.isMoreQualifiedThan(T2)) {
3919 // T2 has fewer qualifiers, so it could be the better sequence.
3920 if (Result == ImplicitConversionSequence::Better)
3921 // Neither has qualifiers that are a subset of the other's
3922 // qualifiers.
3923 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003925 Result = ImplicitConversionSequence::Worse;
3926 } else {
3927 // Qualifiers are disjoint.
3928 return ImplicitConversionSequence::Indistinguishable;
3929 }
3930
3931 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003932 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003933 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003934 }
3935
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003936 // Check that the winning standard conversion sequence isn't using
3937 // the deprecated string literal array to pointer conversion.
3938 switch (Result) {
3939 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003940 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003941 Result = ImplicitConversionSequence::Indistinguishable;
3942 break;
3943
3944 case ImplicitConversionSequence::Indistinguishable:
3945 break;
3946
3947 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003948 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003949 Result = ImplicitConversionSequence::Indistinguishable;
3950 break;
3951 }
3952
3953 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003954}
3955
Douglas Gregor5c407d92008-10-23 00:40:37 +00003956/// CompareDerivedToBaseConversions - Compares two standard conversion
3957/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003958/// various kinds of derived-to-base conversions (C++
3959/// [over.ics.rank]p4b3). As part of these checks, we also look at
3960/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003961static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003962CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003963 const StandardConversionSequence& SCS1,
3964 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003965 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003966 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003967 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003968 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003969
3970 // Adjust the types we're converting from via the array-to-pointer
3971 // conversion, if we need to.
3972 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003973 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003974 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003975 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003976
3977 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003978 FromType1 = S.Context.getCanonicalType(FromType1);
3979 ToType1 = S.Context.getCanonicalType(ToType1);
3980 FromType2 = S.Context.getCanonicalType(FromType2);
3981 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003982
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003983 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003984 //
3985 // If class B is derived directly or indirectly from class A and
3986 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003987 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003988 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003989 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003990 SCS2.Second == ICK_Pointer_Conversion &&
3991 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3992 FromType1->isPointerType() && FromType2->isPointerType() &&
3993 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003994 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003995 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003996 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003997 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003998 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003999 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004000 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004001 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004002
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004003 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004004 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004005 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004006 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004007 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004008 return ImplicitConversionSequence::Worse;
4009 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004010
4011 // -- conversion of B* to A* is better than conversion of C* to A*,
4012 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004013 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004014 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004015 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004016 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004017 }
4018 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4019 SCS2.Second == ICK_Pointer_Conversion) {
4020 const ObjCObjectPointerType *FromPtr1
4021 = FromType1->getAs<ObjCObjectPointerType>();
4022 const ObjCObjectPointerType *FromPtr2
4023 = FromType2->getAs<ObjCObjectPointerType>();
4024 const ObjCObjectPointerType *ToPtr1
4025 = ToType1->getAs<ObjCObjectPointerType>();
4026 const ObjCObjectPointerType *ToPtr2
4027 = ToType2->getAs<ObjCObjectPointerType>();
4028
4029 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4030 // Apply the same conversion ranking rules for Objective-C pointer types
4031 // that we do for C++ pointers to class types. However, we employ the
4032 // Objective-C pseudo-subtyping relationship used for assignment of
4033 // Objective-C pointer types.
4034 bool FromAssignLeft
4035 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4036 bool FromAssignRight
4037 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4038 bool ToAssignLeft
4039 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4040 bool ToAssignRight
4041 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4042
4043 // A conversion to an a non-id object pointer type or qualified 'id'
4044 // type is better than a conversion to 'id'.
4045 if (ToPtr1->isObjCIdType() &&
4046 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4047 return ImplicitConversionSequence::Worse;
4048 if (ToPtr2->isObjCIdType() &&
4049 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4050 return ImplicitConversionSequence::Better;
4051
4052 // A conversion to a non-id object pointer type is better than a
4053 // conversion to a qualified 'id' type
4054 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4055 return ImplicitConversionSequence::Worse;
4056 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4057 return ImplicitConversionSequence::Better;
4058
4059 // A conversion to an a non-Class object pointer type or qualified 'Class'
4060 // type is better than a conversion to 'Class'.
4061 if (ToPtr1->isObjCClassType() &&
4062 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4063 return ImplicitConversionSequence::Worse;
4064 if (ToPtr2->isObjCClassType() &&
4065 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4066 return ImplicitConversionSequence::Better;
4067
4068 // A conversion to a non-Class object pointer type is better than a
4069 // conversion to a qualified 'Class' type.
4070 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4071 return ImplicitConversionSequence::Worse;
4072 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4073 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004074
Douglas Gregor058d3de2011-01-31 18:51:41 +00004075 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4076 if (S.Context.hasSameType(FromType1, FromType2) &&
4077 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4078 (ToAssignLeft != ToAssignRight))
4079 return ToAssignLeft? ImplicitConversionSequence::Worse
4080 : ImplicitConversionSequence::Better;
4081
4082 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4083 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4084 (FromAssignLeft != FromAssignRight))
4085 return FromAssignLeft? ImplicitConversionSequence::Better
4086 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004087 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004088 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004089
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004090 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004091 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4092 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4093 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004094 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004095 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004097 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004099 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004101 ToType2->getAs<MemberPointerType>();
4102 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4103 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4104 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4105 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4106 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4107 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4108 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4109 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004110 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004111 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004112 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004113 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004114 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004115 return ImplicitConversionSequence::Better;
4116 }
4117 // conversion of B::* to C::* is better than conversion of A::* to C::*
4118 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004119 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004120 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004121 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004122 return ImplicitConversionSequence::Worse;
4123 }
4124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125
Douglas Gregor5ab11652010-04-17 22:01:05 +00004126 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004127 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004128 // -- binding of an expression of type C to a reference of type
4129 // B& is better than binding an expression of type C to a
4130 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004131 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4132 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004133 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004134 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004135 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004136 return ImplicitConversionSequence::Worse;
4137 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004138
Douglas Gregor2fe98832008-11-03 19:09:14 +00004139 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004140 // -- binding of an expression of type B to a reference of type
4141 // A& is better than binding an expression of type C to a
4142 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004143 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4144 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004145 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004146 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004147 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004148 return ImplicitConversionSequence::Worse;
4149 }
4150 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004151
Douglas Gregor5c407d92008-10-23 00:40:37 +00004152 return ImplicitConversionSequence::Indistinguishable;
4153}
4154
Douglas Gregor45bb4832013-03-26 23:36:30 +00004155/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4156/// C++ class.
4157static bool isTypeValid(QualType T) {
4158 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4159 return !Record->isInvalidDecl();
4160
4161 return true;
4162}
4163
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004164/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4165/// determine whether they are reference-related,
4166/// reference-compatible, reference-compatible with added
4167/// qualification, or incompatible, for use in C++ initialization by
4168/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4169/// type, and the first type (T1) is the pointee type of the reference
4170/// type being initialized.
4171Sema::ReferenceCompareResult
4172Sema::CompareReferenceRelationship(SourceLocation Loc,
4173 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004174 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004175 bool &ObjCConversion,
4176 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004177 assert(!OrigT1->isReferenceType() &&
4178 "T1 must be the pointee type of the reference type");
4179 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4180
4181 QualType T1 = Context.getCanonicalType(OrigT1);
4182 QualType T2 = Context.getCanonicalType(OrigT2);
4183 Qualifiers T1Quals, T2Quals;
4184 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4185 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4186
4187 // C++ [dcl.init.ref]p4:
4188 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4189 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4190 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004191 DerivedToBase = false;
4192 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004193 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004194 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004195 if (UnqualT1 == UnqualT2) {
4196 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004197 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004198 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004199 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004200 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004201 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4202 UnqualT2->isObjCObjectOrInterfaceType() &&
4203 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4204 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004205 else if (UnqualT2->isFunctionType() &&
4206 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4207 // C++1z [dcl.init.ref]p4:
4208 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4209 // function" and T1 is "function"
4210 //
4211 // We extend this to also apply to 'noreturn', so allow any function
4212 // conversion between function types.
4213 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004214 else
4215 return Ref_Incompatible;
4216
4217 // At this point, we know that T1 and T2 are reference-related (at
4218 // least).
4219
4220 // If the type is an array type, promote the element qualifiers to the type
4221 // for comparison.
4222 if (isa<ArrayType>(T1) && T1Quals)
4223 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4224 if (isa<ArrayType>(T2) && T2Quals)
4225 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4226
4227 // C++ [dcl.init.ref]p4:
4228 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4229 // reference-related to T2 and cv1 is the same cv-qualification
4230 // as, or greater cv-qualification than, cv2. For purposes of
4231 // overload resolution, cases for which cv1 is greater
4232 // cv-qualification than cv2 are identified as
4233 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004234 //
4235 // Note that we also require equivalence of Objective-C GC and address-space
4236 // qualifiers when performing these computations, so that e.g., an int in
4237 // address space 1 is not reference-compatible with an int in address
4238 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004239 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4240 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004241 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4242 ObjCLifetimeConversion = true;
4243
John McCall31168b02011-06-15 23:02:42 +00004244 T1Quals.removeObjCLifetime();
4245 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004246 }
4247
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004248 // MS compiler ignores __unaligned qualifier for references; do the same.
4249 T1Quals.removeUnaligned();
4250 T2Quals.removeUnaligned();
4251
Richard Smithce766292016-10-21 23:01:55 +00004252 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004253 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004254 else
4255 return Ref_Related;
4256}
4257
Douglas Gregor836a7e82010-08-11 02:15:33 +00004258/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004259/// with DeclType. Return true if something definite is found.
4260static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004261FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4262 QualType DeclType, SourceLocation DeclLoc,
4263 Expr *Init, QualType T2, bool AllowRvalues,
4264 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 assert(T2->isRecordType() && "Can only find conversions of record types.");
4266 CXXRecordDecl *T2RecordDecl
4267 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4268
Richard Smith100b24a2014-04-17 01:52:14 +00004269 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004270 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4271 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004272 NamedDecl *D = *I;
4273 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4274 if (isa<UsingShadowDecl>(D))
4275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4276
4277 FunctionTemplateDecl *ConvTemplate
4278 = dyn_cast<FunctionTemplateDecl>(D);
4279 CXXConversionDecl *Conv;
4280 if (ConvTemplate)
4281 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4282 else
4283 Conv = cast<CXXConversionDecl>(D);
4284
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004286 // explicit conversions, skip it.
4287 if (!AllowExplicit && Conv->isExplicit())
4288 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004289
Douglas Gregor836a7e82010-08-11 02:15:33 +00004290 if (AllowRvalues) {
4291 bool DerivedToBase = false;
4292 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004293 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004294
4295 // If we are initializing an rvalue reference, don't permit conversion
4296 // functions that return lvalues.
4297 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4298 const ReferenceType *RefType
4299 = Conv->getConversionType()->getAs<LValueReferenceType>();
4300 if (RefType && !RefType->getPointeeType()->isFunctionType())
4301 continue;
4302 }
4303
Douglas Gregor836a7e82010-08-11 02:15:33 +00004304 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004305 S.CompareReferenceRelationship(
4306 DeclLoc,
4307 Conv->getConversionType().getNonReferenceType()
4308 .getUnqualifiedType(),
4309 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004310 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004311 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004312 continue;
4313 } else {
4314 // If the conversion function doesn't return a reference type,
4315 // it can't be considered for this conversion. An rvalue reference
4316 // is only acceptable if its referencee is a function type.
4317
4318 const ReferenceType *RefType =
4319 Conv->getConversionType()->getAs<ReferenceType>();
4320 if (!RefType ||
4321 (!RefType->isLValueReferenceType() &&
4322 !RefType->getPointeeType()->isFunctionType()))
4323 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325
Douglas Gregor836a7e82010-08-11 02:15:33 +00004326 if (ConvTemplate)
4327 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004328 Init, DeclType, CandidateSet,
4329 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004330 else
4331 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004332 DeclType, CandidateSet,
4333 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004334 }
4335
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004336 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4337
Sebastian Redld92badf2010-06-30 18:13:39 +00004338 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004339 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004340 case OR_Success:
4341 // C++ [over.ics.ref]p1:
4342 //
4343 // [...] If the parameter binds directly to the result of
4344 // applying a conversion function to the argument
4345 // expression, the implicit conversion sequence is a
4346 // user-defined conversion sequence (13.3.3.1.2), with the
4347 // second standard conversion sequence either an identity
4348 // conversion or, if the conversion function returns an
4349 // entity of a type that is a derived class of the parameter
4350 // type, a derived-to-base Conversion.
4351 if (!Best->FinalConversion.DirectBinding)
4352 return false;
4353
4354 ICS.setUserDefined();
4355 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4356 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004357 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004358 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004359 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004360 ICS.UserDefined.EllipsisConversion = false;
4361 assert(ICS.UserDefined.After.ReferenceBinding &&
4362 ICS.UserDefined.After.DirectBinding &&
4363 "Expected a direct reference binding!");
4364 return true;
4365
4366 case OR_Ambiguous:
4367 ICS.setAmbiguous();
4368 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4369 Cand != CandidateSet.end(); ++Cand)
4370 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004371 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004372 return true;
4373
4374 case OR_No_Viable_Function:
4375 case OR_Deleted:
4376 // There was no suitable conversion, or we found a deleted
4377 // conversion; continue with other checks.
4378 return false;
4379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380
David Blaikie8a40f702012-01-17 06:56:22 +00004381 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004382}
4383
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004384/// \brief Compute an implicit conversion sequence for reference
4385/// initialization.
4386static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004387TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004388 SourceLocation DeclLoc,
4389 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004390 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004391 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4392
4393 // Most paths end in a failed conversion.
4394 ImplicitConversionSequence ICS;
4395 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4396
4397 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4398 QualType T2 = Init->getType();
4399
4400 // If the initializer is the address of an overloaded function, try
4401 // to resolve the overloaded function. If all goes well, T2 is the
4402 // type of the resulting function.
4403 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4404 DeclAccessPair Found;
4405 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4406 false, Found))
4407 T2 = Fn->getType();
4408 }
4409
4410 // Compute some basic properties of the types and the initializer.
4411 bool isRValRef = DeclType->isRValueReferenceType();
4412 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004413 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004414 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004415 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004416 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004417 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004418 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004419
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004420
Sebastian Redld92badf2010-06-30 18:13:39 +00004421 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004422 // A reference to type "cv1 T1" is initialized by an expression
4423 // of type "cv2 T2" as follows:
4424
Sebastian Redld92badf2010-06-30 18:13:39 +00004425 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004426 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004427 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4428 // reference-compatible with "cv2 T2," or
4429 //
4430 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004431 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004432 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004433 // When a parameter of reference type binds directly (8.5.3)
4434 // to an argument expression, the implicit conversion sequence
4435 // is the identity conversion, unless the argument expression
4436 // has a type that is a derived class of the parameter type,
4437 // in which case the implicit conversion sequence is a
4438 // derived-to-base Conversion (13.3.3.1).
4439 ICS.setStandard();
4440 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004441 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4442 : ObjCConversion? ICK_Compatible_Conversion
4443 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004444 ICS.Standard.Third = ICK_Identity;
4445 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4446 ICS.Standard.setToType(0, T2);
4447 ICS.Standard.setToType(1, T1);
4448 ICS.Standard.setToType(2, T1);
4449 ICS.Standard.ReferenceBinding = true;
4450 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004451 ICS.Standard.IsLvalueReference = !isRValRef;
4452 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4453 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004454 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004455 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004456 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004457 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004458
Sebastian Redld92badf2010-06-30 18:13:39 +00004459 // Nothing more to do: the inaccessibility/ambiguity check for
4460 // derived-to-base conversions is suppressed when we're
4461 // computing the implicit conversion sequence (C++
4462 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004464 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004465
Sebastian Redld92badf2010-06-30 18:13:39 +00004466 // -- has a class type (i.e., T2 is a class type), where T1 is
4467 // not reference-related to T2, and can be implicitly
4468 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4469 // is reference-compatible with "cv3 T3" 92) (this
4470 // conversion is selected by enumerating the applicable
4471 // conversion functions (13.3.1.6) and choosing the best
4472 // one through overload resolution (13.3)),
4473 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004474 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004475 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004476 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4477 Init, T2, /*AllowRvalues=*/false,
4478 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004479 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004480 }
4481 }
4482
Sebastian Redld92badf2010-06-30 18:13:39 +00004483 // -- Otherwise, the reference shall be an lvalue reference to a
4484 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004485 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004486 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004487 return ICS;
4488
Douglas Gregorf143cd52011-01-24 16:14:37 +00004489 // -- If the initializer expression
4490 //
4491 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004492 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004493 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004494 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004495 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4496 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004497 ICS.setStandard();
4498 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004500 : ObjCConversion? ICK_Compatible_Conversion
4501 : ICK_Identity;
4502 ICS.Standard.Third = ICK_Identity;
4503 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4504 ICS.Standard.setToType(0, T2);
4505 ICS.Standard.setToType(1, T1);
4506 ICS.Standard.setToType(2, T1);
4507 ICS.Standard.ReferenceBinding = true;
4508 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4509 // binding unless we're binding to a class prvalue.
4510 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4511 // allow the use of rvalue references in C++98/03 for the benefit of
4512 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004514 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004515 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004516 ICS.Standard.IsLvalueReference = !isRValRef;
4517 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004519 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004520 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004521 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004522 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Douglas Gregorf143cd52011-01-24 16:14:37 +00004526 // -- has a class type (i.e., T2 is a class type), where T1 is not
4527 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528 // an xvalue, class prvalue, or function lvalue of type
4529 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004530 // "cv3 T3",
4531 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004532 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004533 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004535 // class subobject).
4536 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004537 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004538 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4539 Init, T2, /*AllowRvalues=*/true,
4540 AllowExplicit)) {
4541 // In the second case, if the reference is an rvalue reference
4542 // and the second standard conversion sequence of the
4543 // user-defined conversion sequence includes an lvalue-to-rvalue
4544 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004546 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4547 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4548
Douglas Gregor95273c32011-01-21 16:36:05 +00004549 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
Richard Smith19172c42014-07-14 02:28:44 +00004552 // A temporary of function type cannot be created; don't even try.
4553 if (T1->isFunctionType())
4554 return ICS;
4555
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004556 // -- Otherwise, a temporary of type "cv1 T1" is created and
4557 // initialized from the initializer expression using the
4558 // rules for a non-reference copy initialization (8.5). The
4559 // reference is then bound to the temporary. If T1 is
4560 // reference-related to T2, cv1 must be the same
4561 // cv-qualification as, or greater cv-qualification than,
4562 // cv2; otherwise, the program is ill-formed.
4563 if (RefRelationship == Sema::Ref_Related) {
4564 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4565 // we would be reference-compatible or reference-compatible with
4566 // added qualification. But that wasn't the case, so the reference
4567 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004568 //
4569 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004570 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004571 Qualifiers T1Quals = T1.getQualifiers();
4572 Qualifiers T2Quals = T2.getQualifiers();
4573 T1Quals.removeObjCGCAttr();
4574 T1Quals.removeObjCLifetime();
4575 T2Quals.removeObjCGCAttr();
4576 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004577 // MS compiler ignores __unaligned qualifier for references; do the same.
4578 T1Quals.removeUnaligned();
4579 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004580 if (!T1Quals.compatiblyIncludes(T2Quals))
4581 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004582 }
4583
4584 // If at least one of the types is a class type, the types are not
4585 // related, and we aren't allowed any user conversions, the
4586 // reference binding fails. This case is important for breaking
4587 // recursion, since TryImplicitConversion below will attempt to
4588 // create a temporary through the use of a copy constructor.
4589 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4590 (T1->isRecordType() || T2->isRecordType()))
4591 return ICS;
4592
Douglas Gregorcba72b12011-01-21 05:18:22 +00004593 // If T1 is reference-related to T2 and the reference is an rvalue
4594 // reference, the initializer expression shall not be an lvalue.
4595 if (RefRelationship >= Sema::Ref_Related &&
4596 isRValRef && Init->Classify(S.Context).isLValue())
4597 return ICS;
4598
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004599 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004600 // When a parameter of reference type is not bound directly to
4601 // an argument expression, the conversion sequence is the one
4602 // required to convert the argument expression to the
4603 // underlying type of the reference according to
4604 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4605 // to copy-initializing a temporary of the underlying type with
4606 // the argument expression. Any difference in top-level
4607 // cv-qualification is subsumed by the initialization itself
4608 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004609 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4610 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004611 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004612 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004613 /*AllowObjCWritebackConversion=*/false,
4614 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004615
4616 // Of course, that's still a reference binding.
4617 if (ICS.isStandard()) {
4618 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004619 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004620 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004621 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004622 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004623 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004624 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004625 const ReferenceType *LValRefType =
4626 ICS.UserDefined.ConversionFunction->getReturnType()
4627 ->getAs<LValueReferenceType>();
4628
4629 // C++ [over.ics.ref]p3:
4630 // Except for an implicit object parameter, for which see 13.3.1, a
4631 // standard conversion sequence cannot be formed if it requires [...]
4632 // binding an rvalue reference to an lvalue other than a function
4633 // lvalue.
4634 // Note that the function case is not possible here.
4635 if (DeclType->isRValueReferenceType() && LValRefType) {
4636 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4637 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4638 // reference to an rvalue!
4639 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4640 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004641 }
Richard Smith19172c42014-07-14 02:28:44 +00004642
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004643 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004644 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004645 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4646 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004647 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4648 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004649 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004650
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004651 return ICS;
4652}
4653
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004654static ImplicitConversionSequence
4655TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4656 bool SuppressUserConversions,
4657 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004658 bool AllowObjCWritebackConversion,
4659 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004660
4661/// TryListConversion - Try to copy-initialize a value of type ToType from the
4662/// initializer list From.
4663static ImplicitConversionSequence
4664TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4665 bool SuppressUserConversions,
4666 bool InOverloadResolution,
4667 bool AllowObjCWritebackConversion) {
4668 // C++11 [over.ics.list]p1:
4669 // When an argument is an initializer list, it is not an expression and
4670 // special rules apply for converting it to a parameter type.
4671
4672 ImplicitConversionSequence Result;
4673 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4674
Sebastian Redl09edce02012-01-23 22:09:39 +00004675 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004676 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004677 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004678 return Result;
4679
Larisse Voufo19d08672015-01-27 18:47:05 +00004680 // Per DR1467:
4681 // If the parameter type is a class X and the initializer list has a single
4682 // element of type cv U, where U is X or a class derived from X, the
4683 // implicit conversion sequence is the one required to convert the element
4684 // to the parameter type.
4685 //
4686 // Otherwise, if the parameter type is a character array [... ]
4687 // and the initializer list has a single element that is an
4688 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4689 // implicit conversion sequence is the identity conversion.
4690 if (From->getNumInits() == 1) {
4691 if (ToType->isRecordType()) {
4692 QualType InitType = From->getInit(0)->getType();
4693 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004694 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004695 return TryCopyInitialization(S, From->getInit(0), ToType,
4696 SuppressUserConversions,
4697 InOverloadResolution,
4698 AllowObjCWritebackConversion);
4699 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004700 // FIXME: Check the other conditions here: array of character type,
4701 // initializer is a string literal.
4702 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004703 InitializedEntity Entity =
4704 InitializedEntity::InitializeParameter(S.Context, ToType,
4705 /*Consumed=*/false);
4706 if (S.CanPerformCopyInitialization(Entity, From)) {
4707 Result.setStandard();
4708 Result.Standard.setAsIdentityConversion();
4709 Result.Standard.setFromType(ToType);
4710 Result.Standard.setAllToTypes(ToType);
4711 return Result;
4712 }
4713 }
4714 }
4715
4716 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004717 // C++11 [over.ics.list]p2:
4718 // If the parameter type is std::initializer_list<X> or "array of X" and
4719 // all the elements can be implicitly converted to X, the implicit
4720 // conversion sequence is the worst conversion necessary to convert an
4721 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004722 //
4723 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004724 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004725 // list has exactly N elements or if it has fewer than N elements and X is
4726 // default-constructible, and if all the elements of the initializer list
4727 // can be implicitly converted to X, the implicit conversion sequence is
4728 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004729 //
4730 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004731 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004732 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004733 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004734 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004735 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004736 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004737 if (!X.isNull()) {
4738 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4739 Expr *Init = From->getInit(i);
4740 ImplicitConversionSequence ICS =
4741 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4742 InOverloadResolution,
4743 AllowObjCWritebackConversion);
4744 // If a single element isn't convertible, fail.
4745 if (ICS.isBad()) {
4746 Result = ICS;
4747 break;
4748 }
4749 // Otherwise, look for the worst conversion.
4750 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004751 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4752 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004753 ImplicitConversionSequence::Worse)
4754 Result = ICS;
4755 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004756
4757 // For an empty list, we won't have computed any conversion sequence.
4758 // Introduce the identity conversion sequence.
4759 if (From->getNumInits() == 0) {
4760 Result.setStandard();
4761 Result.Standard.setAsIdentityConversion();
4762 Result.Standard.setFromType(ToType);
4763 Result.Standard.setAllToTypes(ToType);
4764 }
4765
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004766 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004767 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004768 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004769
Larisse Voufo19d08672015-01-27 18:47:05 +00004770 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004771 // C++11 [over.ics.list]p3:
4772 // Otherwise, if the parameter is a non-aggregate class X and overload
4773 // resolution chooses a single best constructor [...] the implicit
4774 // conversion sequence is a user-defined conversion sequence. If multiple
4775 // constructors are viable but none is better than the others, the
4776 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004777 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4778 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004779 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4780 /*AllowExplicit=*/false,
4781 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004782 AllowObjCWritebackConversion,
4783 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004784 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004785
Larisse Voufo19d08672015-01-27 18:47:05 +00004786 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004787 // C++11 [over.ics.list]p4:
4788 // Otherwise, if the parameter has an aggregate type which can be
4789 // initialized from the initializer list [...] the implicit conversion
4790 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004791 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004792 // Type is an aggregate, argument is an init list. At this point it comes
4793 // down to checking whether the initialization works.
4794 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004795 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4796 // need to call into the initialization code here; overload resolution
4797 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004798 InitializedEntity Entity =
4799 InitializedEntity::InitializeParameter(S.Context, ToType,
4800 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004801 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004802 Result.setUserDefined();
4803 Result.UserDefined.Before.setAsIdentityConversion();
4804 // Initializer lists don't have a type.
4805 Result.UserDefined.Before.setFromType(QualType());
4806 Result.UserDefined.Before.setAllToTypes(QualType());
4807
4808 Result.UserDefined.After.setAsIdentityConversion();
4809 Result.UserDefined.After.setFromType(ToType);
4810 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004811 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004812 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004813 return Result;
4814 }
4815
Larisse Voufo19d08672015-01-27 18:47:05 +00004816 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004817 // C++11 [over.ics.list]p5:
4818 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004819 if (ToType->isReferenceType()) {
4820 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4821 // mention initializer lists in any way. So we go by what list-
4822 // initialization would do and try to extrapolate from that.
4823
4824 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4825
4826 // If the initializer list has a single element that is reference-related
4827 // to the parameter type, we initialize the reference from that.
4828 if (From->getNumInits() == 1) {
4829 Expr *Init = From->getInit(0);
4830
4831 QualType T2 = Init->getType();
4832
4833 // If the initializer is the address of an overloaded function, try
4834 // to resolve the overloaded function. If all goes well, T2 is the
4835 // type of the resulting function.
4836 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4837 DeclAccessPair Found;
4838 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4839 Init, ToType, false, Found))
4840 T2 = Fn->getType();
4841 }
4842
4843 // Compute some basic properties of the types and the initializer.
4844 bool dummy1 = false;
4845 bool dummy2 = false;
4846 bool dummy3 = false;
4847 Sema::ReferenceCompareResult RefRelationship
4848 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4849 dummy2, dummy3);
4850
Richard Smith4d2bbd72013-09-06 01:22:42 +00004851 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004852 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4853 SuppressUserConversions,
4854 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004855 }
Sebastian Redldf888642011-12-03 14:54:30 +00004856 }
4857
4858 // Otherwise, we bind the reference to a temporary created from the
4859 // initializer list.
4860 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4861 InOverloadResolution,
4862 AllowObjCWritebackConversion);
4863 if (Result.isFailure())
4864 return Result;
4865 assert(!Result.isEllipsis() &&
4866 "Sub-initialization cannot result in ellipsis conversion.");
4867
4868 // Can we even bind to a temporary?
4869 if (ToType->isRValueReferenceType() ||
4870 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4871 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4872 Result.UserDefined.After;
4873 SCS.ReferenceBinding = true;
4874 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4875 SCS.BindsToRvalue = true;
4876 SCS.BindsToFunctionLvalue = false;
4877 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4878 SCS.ObjCLifetimeConversionBinding = false;
4879 } else
4880 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4881 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004882 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004883 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004884
Larisse Voufo19d08672015-01-27 18:47:05 +00004885 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004886 // C++11 [over.ics.list]p6:
4887 // Otherwise, if the parameter type is not a class:
4888 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004889 // - if the initializer list has one element that is not itself an
4890 // initializer list, the implicit conversion sequence is the one
4891 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004892 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004893 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004894 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4895 SuppressUserConversions,
4896 InOverloadResolution,
4897 AllowObjCWritebackConversion);
4898 // - if the initializer list has no elements, the implicit conversion
4899 // sequence is the identity conversion.
4900 else if (NumInits == 0) {
4901 Result.setStandard();
4902 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004903 Result.Standard.setFromType(ToType);
4904 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004905 }
4906 return Result;
4907 }
4908
Larisse Voufo19d08672015-01-27 18:47:05 +00004909 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004910 // C++11 [over.ics.list]p7:
4911 // In all cases other than those enumerated above, no conversion is possible
4912 return Result;
4913}
4914
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004915/// TryCopyInitialization - Try to copy-initialize a value of type
4916/// ToType from the expression From. Return the implicit conversion
4917/// sequence required to pass this argument, which may be a bad
4918/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004919/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004920/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004921static ImplicitConversionSequence
4922TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004924 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004925 bool AllowObjCWritebackConversion,
4926 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004927 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4928 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4929 InOverloadResolution,AllowObjCWritebackConversion);
4930
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004931 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004932 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004933 /*FIXME:*/From->getLocStart(),
4934 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004935 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004936
John McCall5c32be02010-08-24 20:38:10 +00004937 return TryImplicitConversion(S, From, ToType,
4938 SuppressUserConversions,
4939 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004940 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004941 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004942 AllowObjCWritebackConversion,
4943 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004944}
4945
Anna Zaks1b068122011-07-28 19:46:48 +00004946static bool TryCopyInitialization(const CanQualType FromQTy,
4947 const CanQualType ToQTy,
4948 Sema &S,
4949 SourceLocation Loc,
4950 ExprValueKind FromVK) {
4951 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4952 ImplicitConversionSequence ICS =
4953 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4954
4955 return !ICS.isBad();
4956}
4957
Douglas Gregor436424c2008-11-18 23:14:02 +00004958/// TryObjectArgumentInitialization - Try to initialize the object
4959/// parameter of the given member function (@c Method) from the
4960/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004961static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004962TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004963 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004964 CXXMethodDecl *Method,
4965 CXXRecordDecl *ActingContext) {
4966 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004967 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4968 // const volatile object.
4969 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4970 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004971 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004972
4973 // Set up the conversion sequence as a "bad" conversion, to allow us
4974 // to exit early.
4975 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004976
4977 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004978 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004979 FromType = PT->getPointeeType();
4980
Douglas Gregor02824322011-01-26 19:30:28 +00004981 // When we had a pointer, it's implicitly dereferenced, so we
4982 // better have an lvalue.
4983 assert(FromClassification.isLValue());
4984 }
4985
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004986 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004987
Douglas Gregor02824322011-01-26 19:30:28 +00004988 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004990 // parameter is
4991 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004992 // - "lvalue reference to cv X" for functions declared without a
4993 // ref-qualifier or with the & ref-qualifier
4994 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004995 // ref-qualifier
4996 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004998 // cv-qualification on the member function declaration.
4999 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005001 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005002 // (C++ [over.match.funcs]p5). We perform a simplified version of
5003 // reference binding here, that allows class rvalues to bind to
5004 // non-constant references.
5005
Douglas Gregor02824322011-01-26 19:30:28 +00005006 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005007 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005009 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005010 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005011 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005012 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005013 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005014 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005015
5016 // Check that we have either the same type or a derived type. It
5017 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005018 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005019 ImplicitConversionKind SecondKind;
5020 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5021 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005022 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005023 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005024 else {
John McCall65eb8792010-02-25 01:37:24 +00005025 ICS.setBad(BadConversionSequence::unrelated_class,
5026 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005027 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005028 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005029
Douglas Gregor02824322011-01-26 19:30:28 +00005030 // Check the ref-qualifier.
5031 switch (Method->getRefQualifier()) {
5032 case RQ_None:
5033 // Do nothing; we don't care about lvalueness or rvalueness.
5034 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
Douglas Gregor02824322011-01-26 19:30:28 +00005036 case RQ_LValue:
5037 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5038 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005040 ImplicitParamType);
5041 return ICS;
5042 }
5043 break;
5044
5045 case RQ_RValue:
5046 if (!FromClassification.isRValue()) {
5047 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005049 ImplicitParamType);
5050 return ICS;
5051 }
5052 break;
5053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054
Douglas Gregor436424c2008-11-18 23:14:02 +00005055 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005056 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005057 ICS.Standard.setAsIdentityConversion();
5058 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005059 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005060 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005061 ICS.Standard.ReferenceBinding = true;
5062 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005064 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005065 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5066 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5067 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005068 return ICS;
5069}
5070
5071/// PerformObjectArgumentInitialization - Perform initialization of
5072/// the implicit object parameter for the given Method with the given
5073/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005074ExprResult
5075Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005077 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005078 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005079 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005080 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005081 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005082
Douglas Gregor02824322011-01-26 19:30:28 +00005083 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005084 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005085 FromRecordType = PT->getPointeeType();
5086 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005087 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005088 } else {
5089 FromRecordType = From->getType();
5090 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005091 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005092 }
5093
John McCall6e9f8f62009-12-03 04:06:58 +00005094 // Note that we always use the true parent context when performing
5095 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005096 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005097 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5098 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005099 if (ICS.isBad()) {
5100 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5101 Qualifiers FromQs = FromRecordType.getQualifiers();
5102 Qualifiers ToQs = DestType.getQualifiers();
5103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5104 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005105 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005106 diag::err_member_function_call_bad_cvr)
5107 << Method->getDeclName() << FromRecordType << (CVR - 1)
5108 << From->getSourceRange();
5109 Diag(Method->getLocation(), diag::note_previous_decl)
5110 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005111 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005112 }
5113 }
5114
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005115 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005116 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005117 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005118 }
Mike Stump11289f42009-09-09 15:08:12 +00005119
John Wiegley01296292011-04-08 18:41:53 +00005120 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5121 ExprResult FromRes =
5122 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5123 if (FromRes.isInvalid())
5124 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005125 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005126 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005127
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005128 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005129 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005130 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005131 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005132}
5133
Douglas Gregor5fb53972009-01-14 15:45:31 +00005134/// TryContextuallyConvertToBool - Attempt to contextually convert the
5135/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005136static ImplicitConversionSequence
5137TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005138 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005139 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005140 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005141 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005142 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005143 /*AllowObjCWritebackConversion=*/false,
5144 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005145}
5146
5147/// PerformContextuallyConvertToBool - Perform a contextual conversion
5148/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005149ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005150 if (checkPlaceholderForOverload(*this, From))
5151 return ExprError();
5152
John McCall5c32be02010-08-24 20:38:10 +00005153 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005154 if (!ICS.isBad())
5155 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Fariborz Jahanian76197412009-11-18 18:26:29 +00005157 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005158 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005159 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005160 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005161 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005162}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163
Richard Smithf8379a02012-01-18 23:55:52 +00005164/// Check that the specified conversion is permitted in a converted constant
5165/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5166/// is acceptable.
5167static bool CheckConvertedConstantConversions(Sema &S,
5168 StandardConversionSequence &SCS) {
5169 // Since we know that the target type is an integral or unscoped enumeration
5170 // type, most conversion kinds are impossible. All possible First and Third
5171 // conversions are fine.
5172 switch (SCS.Second) {
5173 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005174 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005175 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005176 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005177 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005178 return true;
5179
5180 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005181 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005182 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5183 // conversion, so we allow it in a converted constant expression.
5184 //
5185 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5186 // a lot of popular code. We should at least add a warning for this
5187 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005188 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5189 SCS.getToType(2)->isBooleanType();
5190
Richard Smith410cc892014-11-26 03:26:53 +00005191 case ICK_Pointer_Conversion:
5192 case ICK_Pointer_Member:
5193 // C++1z: null pointer conversions and null member pointer conversions are
5194 // only permitted if the source type is std::nullptr_t.
5195 return SCS.getFromType()->isNullPtrType();
5196
5197 case ICK_Floating_Promotion:
5198 case ICK_Complex_Promotion:
5199 case ICK_Floating_Conversion:
5200 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005201 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005202 case ICK_Compatible_Conversion:
5203 case ICK_Derived_To_Base:
5204 case ICK_Vector_Conversion:
5205 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005206 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005207 case ICK_Block_Pointer_Conversion:
5208 case ICK_TransparentUnionConversion:
5209 case ICK_Writeback_Conversion:
5210 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005211 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005212 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005213 return false;
5214
5215 case ICK_Lvalue_To_Rvalue:
5216 case ICK_Array_To_Pointer:
5217 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005218 llvm_unreachable("found a first conversion kind in Second");
5219
Richard Smithf8379a02012-01-18 23:55:52 +00005220 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005221 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005222
5223 case ICK_Num_Conversion_Kinds:
5224 break;
5225 }
5226
5227 llvm_unreachable("unknown conversion kind");
5228}
5229
5230/// CheckConvertedConstantExpression - Check that the expression From is a
5231/// converted constant expression of type T, perform the conversion and produce
5232/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005233static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5234 QualType T, APValue &Value,
5235 Sema::CCEKind CCE,
5236 bool RequireInt) {
5237 assert(S.getLangOpts().CPlusPlus11 &&
5238 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005239
Richard Smith410cc892014-11-26 03:26:53 +00005240 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005241 return ExprError();
5242
Richard Smith410cc892014-11-26 03:26:53 +00005243 // C++1z [expr.const]p3:
5244 // A converted constant expression of type T is an expression,
5245 // implicitly converted to type T, where the converted
5246 // expression is a constant expression and the implicit conversion
5247 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005248 // C++1z [stmt.if]p2:
5249 // If the if statement is of the form if constexpr, the value of the
5250 // condition shall be a contextually converted constant expression of type
5251 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005252 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005253 CCE == Sema::CCEK_ConstexprIf
5254 ? TryContextuallyConvertToBool(S, From)
5255 : TryCopyInitialization(S, From, T,
5256 /*SuppressUserConversions=*/false,
5257 /*InOverloadResolution=*/false,
5258 /*AllowObjcWritebackConversion=*/false,
5259 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005260 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005261 switch (ICS.getKind()) {
5262 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005263 SCS = &ICS.Standard;
5264 break;
5265 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005266 // We are converting to a non-class type, so the Before sequence
5267 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005268 SCS = &ICS.UserDefined.After;
5269 break;
5270 case ImplicitConversionSequence::AmbiguousConversion:
5271 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005272 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5273 return S.Diag(From->getLocStart(),
5274 diag::err_typecheck_converted_constant_expression)
5275 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005276 return ExprError();
5277
5278 case ImplicitConversionSequence::EllipsisConversion:
5279 llvm_unreachable("ellipsis conversion in converted constant expression");
5280 }
5281
Richard Smith410cc892014-11-26 03:26:53 +00005282 // Check that we would only use permitted conversions.
5283 if (!CheckConvertedConstantConversions(S, *SCS)) {
5284 return S.Diag(From->getLocStart(),
5285 diag::err_typecheck_converted_constant_expression_disallowed)
5286 << From->getType() << From->getSourceRange() << T;
5287 }
5288 // [...] and where the reference binding (if any) binds directly.
5289 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5290 return S.Diag(From->getLocStart(),
5291 diag::err_typecheck_converted_constant_expression_indirect)
5292 << From->getType() << From->getSourceRange() << T;
5293 }
5294
5295 ExprResult Result =
5296 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005297 if (Result.isInvalid())
5298 return Result;
5299
5300 // Check for a narrowing implicit conversion.
5301 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005302 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005303 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005304 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005305 case NK_Dependent_Narrowing:
5306 // Implicit conversion to a narrower type, but the expression is
5307 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005308 case NK_Variable_Narrowing:
5309 // Implicit conversion to a narrower type, and the value is not a constant
5310 // expression. We'll diagnose this in a moment.
5311 case NK_Not_Narrowing:
5312 break;
5313
5314 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005315 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005316 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005317 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005318 break;
5319
5320 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005321 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005322 << CCE << /*Constant*/0 << From->getType() << T;
5323 break;
5324 }
5325
Richard Smith52e624f2016-12-21 21:42:57 +00005326 if (Result.get()->isValueDependent()) {
5327 Value = APValue();
5328 return Result;
5329 }
5330
Richard Smithf8379a02012-01-18 23:55:52 +00005331 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005332 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005333 Expr::EvalResult Eval;
5334 Eval.Diag = &Notes;
5335
Richard Smith410cc892014-11-26 03:26:53 +00005336 if ((T->isReferenceType()
5337 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5338 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5339 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005340 // The expression can't be folded, so we can't keep it at this position in
5341 // the AST.
5342 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005343 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005344 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005345
5346 if (Notes.empty()) {
5347 // It's a constant expression.
5348 return Result;
5349 }
Richard Smithf8379a02012-01-18 23:55:52 +00005350 }
5351
5352 // It's not a constant expression. Produce an appropriate diagnostic.
5353 if (Notes.size() == 1 &&
5354 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005355 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005356 else {
Richard Smith410cc892014-11-26 03:26:53 +00005357 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005358 << CCE << From->getSourceRange();
5359 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005360 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005361 }
Richard Smith410cc892014-11-26 03:26:53 +00005362 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005363}
5364
Richard Smith410cc892014-11-26 03:26:53 +00005365ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5366 APValue &Value, CCEKind CCE) {
5367 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5368}
5369
5370ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5371 llvm::APSInt &Value,
5372 CCEKind CCE) {
5373 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5374
5375 APValue V;
5376 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005377 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005378 Value = V.getInt();
5379 return R;
5380}
5381
5382
John McCallfec112d2011-09-09 06:11:02 +00005383/// dropPointerConversions - If the given standard conversion sequence
5384/// involves any pointer conversions, remove them. This may change
5385/// the result type of the conversion sequence.
5386static void dropPointerConversion(StandardConversionSequence &SCS) {
5387 if (SCS.Second == ICK_Pointer_Conversion) {
5388 SCS.Second = ICK_Identity;
5389 SCS.Third = ICK_Identity;
5390 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5391 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005392}
John McCall5c32be02010-08-24 20:38:10 +00005393
John McCallfec112d2011-09-09 06:11:02 +00005394/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5395/// convert the expression From to an Objective-C pointer type.
5396static ImplicitConversionSequence
5397TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5398 // Do an implicit conversion to 'id'.
5399 QualType Ty = S.Context.getObjCIdType();
5400 ImplicitConversionSequence ICS
5401 = TryImplicitConversion(S, From, Ty,
5402 // FIXME: Are these flags correct?
5403 /*SuppressUserConversions=*/false,
5404 /*AllowExplicit=*/true,
5405 /*InOverloadResolution=*/false,
5406 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005407 /*AllowObjCWritebackConversion=*/false,
5408 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005409
5410 // Strip off any final conversions to 'id'.
5411 switch (ICS.getKind()) {
5412 case ImplicitConversionSequence::BadConversion:
5413 case ImplicitConversionSequence::AmbiguousConversion:
5414 case ImplicitConversionSequence::EllipsisConversion:
5415 break;
5416
5417 case ImplicitConversionSequence::UserDefinedConversion:
5418 dropPointerConversion(ICS.UserDefined.After);
5419 break;
5420
5421 case ImplicitConversionSequence::StandardConversion:
5422 dropPointerConversion(ICS.Standard);
5423 break;
5424 }
5425
5426 return ICS;
5427}
5428
5429/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5430/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005431/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005432ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005433 if (checkPlaceholderForOverload(*this, From))
5434 return ExprError();
5435
John McCall8b07ec22010-05-15 11:32:37 +00005436 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005437 ImplicitConversionSequence ICS =
5438 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005439 if (!ICS.isBad())
5440 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005441 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005442}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005443
Richard Smith8dd34252012-02-04 07:07:42 +00005444/// Determine whether the provided type is an integral type, or an enumeration
5445/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005446bool Sema::ICEConvertDiagnoser::match(QualType T) {
5447 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5448 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005449}
5450
Larisse Voufo236bec22013-06-10 06:50:24 +00005451static ExprResult
5452diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5453 Sema::ContextualImplicitConverter &Converter,
5454 QualType T, UnresolvedSetImpl &ViableConversions) {
5455
5456 if (Converter.Suppress)
5457 return ExprError();
5458
5459 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5460 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5461 CXXConversionDecl *Conv =
5462 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5463 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5464 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5465 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005466 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005467}
5468
5469static bool
5470diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5471 Sema::ContextualImplicitConverter &Converter,
5472 QualType T, bool HadMultipleCandidates,
5473 UnresolvedSetImpl &ExplicitConversions) {
5474 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5475 DeclAccessPair Found = ExplicitConversions[0];
5476 CXXConversionDecl *Conversion =
5477 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5478
5479 // The user probably meant to invoke the given explicit
5480 // conversion; use it.
5481 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5482 std::string TypeStr;
5483 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5484
5485 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5486 << FixItHint::CreateInsertion(From->getLocStart(),
5487 "static_cast<" + TypeStr + ">(")
5488 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005489 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005490 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5491
5492 // If we aren't in a SFINAE context, build a call to the
5493 // explicit conversion function.
5494 if (SemaRef.isSFINAEContext())
5495 return true;
5496
Craig Topperc3ec1492014-05-26 06:22:03 +00005497 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005498 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5499 HadMultipleCandidates);
5500 if (Result.isInvalid())
5501 return true;
5502 // Record usage of conversion in an implicit cast.
5503 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005504 CK_UserDefinedConversion, Result.get(),
5505 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005506 }
5507 return false;
5508}
5509
5510static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5511 Sema::ContextualImplicitConverter &Converter,
5512 QualType T, bool HadMultipleCandidates,
5513 DeclAccessPair &Found) {
5514 CXXConversionDecl *Conversion =
5515 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005516 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005517
5518 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5519 if (!Converter.SuppressConversion) {
5520 if (SemaRef.isSFINAEContext())
5521 return true;
5522
5523 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5524 << From->getSourceRange();
5525 }
5526
5527 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5528 HadMultipleCandidates);
5529 if (Result.isInvalid())
5530 return true;
5531 // Record usage of conversion in an implicit cast.
5532 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005533 CK_UserDefinedConversion, Result.get(),
5534 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005535 return false;
5536}
5537
5538static ExprResult finishContextualImplicitConversion(
5539 Sema &SemaRef, SourceLocation Loc, Expr *From,
5540 Sema::ContextualImplicitConverter &Converter) {
5541 if (!Converter.match(From->getType()) && !Converter.Suppress)
5542 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5543 << From->getSourceRange();
5544
5545 return SemaRef.DefaultLvalueConversion(From);
5546}
5547
5548static void
5549collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5550 UnresolvedSetImpl &ViableConversions,
5551 OverloadCandidateSet &CandidateSet) {
5552 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5553 DeclAccessPair FoundDecl = ViableConversions[I];
5554 NamedDecl *D = FoundDecl.getDecl();
5555 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5556 if (isa<UsingShadowDecl>(D))
5557 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5558
5559 CXXConversionDecl *Conv;
5560 FunctionTemplateDecl *ConvTemplate;
5561 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5562 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5563 else
5564 Conv = cast<CXXConversionDecl>(D);
5565
5566 if (ConvTemplate)
5567 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005568 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5569 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005570 else
5571 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005572 ToType, CandidateSet,
5573 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005574 }
5575}
5576
Richard Smithccc11812013-05-21 19:05:48 +00005577/// \brief Attempt to convert the given expression to a type which is accepted
5578/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005579///
Richard Smithccc11812013-05-21 19:05:48 +00005580/// This routine will attempt to convert an expression of class type to a
5581/// type accepted by the specified converter. In C++11 and before, the class
5582/// must have a single non-explicit conversion function converting to a matching
5583/// type. In C++1y, there can be multiple such conversion functions, but only
5584/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005585///
Douglas Gregor4799d032010-06-30 00:20:43 +00005586/// \param Loc The source location of the construct that requires the
5587/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005588///
James Dennett18348b62012-06-22 08:52:37 +00005589/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005590///
Richard Smithccc11812013-05-21 19:05:48 +00005591/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005592///
Douglas Gregor4799d032010-06-30 00:20:43 +00005593/// \returns The expression, converted to an integral or enumeration type if
5594/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005595ExprResult Sema::PerformContextualImplicitConversion(
5596 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005597 // We can't perform any more checking for type-dependent expressions.
5598 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005599 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600
Eli Friedman1da70392012-01-26 00:26:18 +00005601 // Process placeholders immediately.
5602 if (From->hasPlaceholderType()) {
5603 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005604 if (result.isInvalid())
5605 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005606 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005607 }
5608
Richard Smithccc11812013-05-21 19:05:48 +00005609 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005610 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005611 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005612 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005613
5614 // FIXME: Check for missing '()' if T is a function type?
5615
Richard Smithccc11812013-05-21 19:05:48 +00005616 // We can only perform contextual implicit conversions on objects of class
5617 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005618 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005619 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005620 if (!Converter.Suppress)
5621 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005622 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005624
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005625 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005626 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005627 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005628 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005629
5630 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005631 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005632
Craig Toppere14c0f82014-03-12 04:55:44 +00005633 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005634 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005635 }
Richard Smithccc11812013-05-21 19:05:48 +00005636 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005637
Richard Smithdb0ac552015-12-18 22:40:25 +00005638 if (Converter.Suppress ? !isCompleteType(Loc, T)
5639 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005640 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005642 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005643 UnresolvedSet<4>
5644 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005645 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005646 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005647 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648
Larisse Voufo236bec22013-06-10 06:50:24 +00005649 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005650 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005651
Larisse Voufo236bec22013-06-10 06:50:24 +00005652 // To check that there is only one target type, in C++1y:
5653 QualType ToType;
5654 bool HasUniqueTargetType = true;
5655
5656 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005657 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005658 NamedDecl *D = (*I)->getUnderlyingDecl();
5659 CXXConversionDecl *Conversion;
5660 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5661 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005662 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005663 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5664 else
5665 continue; // C++11 does not consider conversion operator templates(?).
5666 } else
5667 Conversion = cast<CXXConversionDecl>(D);
5668
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005669 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005670 "Conversion operator templates are considered potentially "
5671 "viable in C++1y");
5672
5673 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5674 if (Converter.match(CurToType) || ConvTemplate) {
5675
5676 if (Conversion->isExplicit()) {
5677 // FIXME: For C++1y, do we need this restriction?
5678 // cf. diagnoseNoViableConversion()
5679 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005680 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005681 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005682 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005683 if (ToType.isNull())
5684 ToType = CurToType.getUnqualifiedType();
5685 else if (HasUniqueTargetType &&
5686 (CurToType.getUnqualifiedType() != ToType))
5687 HasUniqueTargetType = false;
5688 }
5689 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005690 }
Richard Smith8dd34252012-02-04 07:07:42 +00005691 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005693
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005694 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005695 // C++1y [conv]p6:
5696 // ... An expression e of class type E appearing in such a context
5697 // is said to be contextually implicitly converted to a specified
5698 // type T and is well-formed if and only if e can be implicitly
5699 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005700 // for conversion functions whose return type is cv T or reference to
5701 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005702 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703
Larisse Voufo236bec22013-06-10 06:50:24 +00005704 // If no unique T is found:
5705 if (ToType.isNull()) {
5706 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5707 HadMultipleCandidates,
5708 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005709 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005710 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
Larisse Voufo236bec22013-06-10 06:50:24 +00005713 // If more than one unique Ts are found:
5714 if (!HasUniqueTargetType)
5715 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5716 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717
Larisse Voufo236bec22013-06-10 06:50:24 +00005718 // If one unique T is found:
5719 // First, build a candidate set from the previously recorded
5720 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005721 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005722 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5723 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Larisse Voufo236bec22013-06-10 06:50:24 +00005725 // Then, perform overload resolution over the candidate set.
5726 OverloadCandidateSet::iterator Best;
5727 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5728 case OR_Success: {
5729 // Apply this conversion.
5730 DeclAccessPair Found =
5731 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5732 if (recordConversion(*this, Loc, From, Converter, T,
5733 HadMultipleCandidates, Found))
5734 return ExprError();
5735 break;
5736 }
5737 case OR_Ambiguous:
5738 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5739 ViableConversions);
5740 case OR_No_Viable_Function:
5741 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5742 HadMultipleCandidates,
5743 ExplicitConversions))
5744 return ExprError();
5745 // fall through 'OR_Deleted' case.
5746 case OR_Deleted:
5747 // We'll complain below about a non-integral condition type.
5748 break;
5749 }
5750 } else {
5751 switch (ViableConversions.size()) {
5752 case 0: {
5753 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5754 HadMultipleCandidates,
5755 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005756 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Larisse Voufo236bec22013-06-10 06:50:24 +00005758 // We'll complain below about a non-integral condition type.
5759 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005760 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005761 case 1: {
5762 // Apply this conversion.
5763 DeclAccessPair Found = ViableConversions[0];
5764 if (recordConversion(*this, Loc, From, Converter, T,
5765 HadMultipleCandidates, Found))
5766 return ExprError();
5767 break;
5768 }
5769 default:
5770 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5771 ViableConversions);
5772 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Larisse Voufo236bec22013-06-10 06:50:24 +00005775 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005776}
5777
Richard Smith100b24a2014-04-17 01:52:14 +00005778/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5779/// an acceptable non-member overloaded operator for a call whose
5780/// arguments have types T1 (and, if non-empty, T2). This routine
5781/// implements the check in C++ [over.match.oper]p3b2 concerning
5782/// enumeration types.
5783static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5784 FunctionDecl *Fn,
5785 ArrayRef<Expr *> Args) {
5786 QualType T1 = Args[0]->getType();
5787 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5788
5789 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5790 return true;
5791
5792 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5793 return true;
5794
5795 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5796 if (Proto->getNumParams() < 1)
5797 return false;
5798
5799 if (T1->isEnumeralType()) {
5800 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5801 if (Context.hasSameUnqualifiedType(T1, ArgType))
5802 return true;
5803 }
5804
5805 if (Proto->getNumParams() < 2)
5806 return false;
5807
5808 if (!T2.isNull() && T2->isEnumeralType()) {
5809 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5810 if (Context.hasSameUnqualifiedType(T2, ArgType))
5811 return true;
5812 }
5813
5814 return false;
5815}
5816
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005817/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005818/// candidate functions, using the given function call arguments. If
5819/// @p SuppressUserConversions, then don't allow user-defined
5820/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005821///
James Dennett2a4d13c2012-06-15 07:13:21 +00005822/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005823/// based on an incomplete set of function arguments. This feature is used by
5824/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005825void
5826Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005827 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005828 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005829 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005830 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005831 bool PartialOverloading,
Renato Golindad96d62017-01-02 11:15:42 +00005832 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005833 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005834 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005835 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005836 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005837 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005838
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005839 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005840 if (!isa<CXXConstructorDecl>(Method)) {
5841 // If we get here, it's because we're calling a member function
5842 // that is named without a member access expression (e.g.,
5843 // "this->f") that was either written explicitly or created
5844 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005845 // function, e.g., X::f(). We use an empty type for the implied
5846 // object argument (C++ [over.call.func]p3), and the acting context
5847 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005848 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005849 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005850 Args, CandidateSet, SuppressUserConversions,
Renato Golindad96d62017-01-02 11:15:42 +00005851 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005852 return;
5853 }
5854 // We treat a constructor like a non-member function, since its object
5855 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005856 }
5857
Douglas Gregorff7028a2009-11-13 23:59:09 +00005858 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005859 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005860
Richard Smith100b24a2014-04-17 01:52:14 +00005861 // C++ [over.match.oper]p3:
5862 // if no operand has a class type, only those non-member functions in the
5863 // lookup set that have a first parameter of type T1 or "reference to
5864 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5865 // is a right operand) a second parameter of type T2 or "reference to
5866 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5867 // candidate functions.
5868 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5869 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5870 return;
5871
Richard Smith8b86f2d2013-11-04 01:48:18 +00005872 // C++11 [class.copy]p11: [DR1402]
5873 // A defaulted move constructor that is defined as deleted is ignored by
5874 // overload resolution.
5875 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5876 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5877 Constructor->isMoveConstructor())
5878 return;
5879
Douglas Gregor27381f32009-11-23 12:27:39 +00005880 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005881 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005882
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005883 // Add this candidate
Renato Golindad96d62017-01-02 11:15:42 +00005884 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005885 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005886 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005887 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005888 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005889 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005890 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005891
John McCall578a1f82014-12-14 01:46:53 +00005892 if (Constructor) {
5893 // C++ [class.copy]p3:
5894 // A member function template is never instantiated to perform the copy
5895 // of a class object to an object of its class type.
5896 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005897 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005898 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005899 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5900 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005901 Candidate.Viable = false;
5902 Candidate.FailureKind = ovl_fail_illegal_constructor;
5903 return;
5904 }
5905 }
5906
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005907 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005908
5909 // (C++ 13.3.2p2): A candidate function having fewer than m
5910 // parameters is viable only if it has an ellipsis in its parameter
5911 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005912 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005913 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005914 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005915 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005916 return;
5917 }
5918
5919 // (C++ 13.3.2p2): A candidate function having more than m parameters
5920 // is viable only if the (m+1)st parameter has a default argument
5921 // (8.3.6). For the purposes of overload resolution, the
5922 // parameter list is truncated on the right, so that there are
5923 // exactly m parameters.
5924 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005925 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005926 // Not enough arguments.
5927 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005928 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005929 return;
5930 }
5931
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005932 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005933 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005934 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005935 // Skip the check for callers that are implicit members, because in this
5936 // case we may not yet know what the member's target is; the target is
5937 // inferred for the member automatically, based on the bases and fields of
5938 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005939 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005940 Candidate.Viable = false;
5941 Candidate.FailureKind = ovl_fail_bad_target;
5942 return;
5943 }
5944
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005945 // Determine the implicit conversion sequences for each of the
5946 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005947 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Renato Golindad96d62017-01-02 11:15:42 +00005948 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005949 // (C++ 13.3.2p3): for F to be a viable function, there shall
5950 // exist for each argument an implicit conversion sequence
5951 // (13.3.3.1) that converts that argument to the corresponding
5952 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005953 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005954 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005955 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005956 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005957 /*InOverloadResolution=*/true,
5958 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005959 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005960 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005961 if (Candidate.Conversions[ArgIdx].isBad()) {
5962 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005963 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005964 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005965 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005966 } else {
5967 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5968 // argument for which there is no corresponding parameter is
5969 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005970 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005971 }
5972 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005973
Richard Smithf9c59b72017-01-08 21:45:44 +00005974 // C++ [over.best.ics]p4+: (proposed DR resolution)
5975 // If the target is the first parameter of an inherited constructor when
5976 // constructing an object of type C with an argument list that has exactly
5977 // one expression, an implicit conversion sequence cannot be formed if C is
5978 // reference-related to the type that the argument would have after the
5979 // application of the user-defined conversion (if any) and before the final
5980 // standard conversion sequence.
5981 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5982 if (Shadow && Args.size() == 1 && !isa<InitListExpr>(Args.front())) {
5983 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5984 QualType ConvertedArgumentType = Args.front()->getType();
5985 if (Candidate.Conversions[0].isUserDefined())
5986 ConvertedArgumentType =
5987 Candidate.Conversions[0].UserDefined.After.getFromType();
5988 if (CompareReferenceRelationship(Args.front()->getLocStart(),
5989 Context.getRecordType(Shadow->getParent()),
5990 ConvertedArgumentType, DerivedToBase,
5991 ObjCConversion,
5992 ObjCLifetimeConversion) >= Ref_Related) {
5993 Candidate.Viable = false;
5994 Candidate.FailureKind = ovl_fail_inhctor_slice;
5995 return;
5996 }
5997 }
5998
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005999 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6000 Candidate.Viable = false;
6001 Candidate.FailureKind = ovl_fail_enable_if;
6002 Candidate.DeductionFailure.Data = FailedAttr;
6003 return;
6004 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006005
6006 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6007 Candidate.Viable = false;
6008 Candidate.FailureKind = ovl_fail_ext_disabled;
6009 return;
6010 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006011}
6012
Manman Rend2a3cd72016-04-07 19:30:20 +00006013ObjCMethodDecl *
6014Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6015 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6016 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006017 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006018
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006019 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6020 bool Match = true;
6021 ObjCMethodDecl *Method = Methods[b];
6022 unsigned NumNamedArgs = Sel.getNumArgs();
6023 // Method might have more arguments than selector indicates. This is due
6024 // to addition of c-style arguments in method.
6025 if (Method->param_size() > NumNamedArgs)
6026 NumNamedArgs = Method->param_size();
6027 if (Args.size() < NumNamedArgs)
6028 continue;
6029
6030 for (unsigned i = 0; i < NumNamedArgs; i++) {
6031 // We can't do any type-checking on a type-dependent argument.
6032 if (Args[i]->isTypeDependent()) {
6033 Match = false;
6034 break;
6035 }
6036
6037 ParmVarDecl *param = Method->parameters()[i];
6038 Expr *argExpr = Args[i];
6039 assert(argExpr && "SelectBestMethod(): missing expression");
6040
6041 // Strip the unbridged-cast placeholder expression off unless it's
6042 // a consumed argument.
6043 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6044 !param->hasAttr<CFConsumedAttr>())
6045 argExpr = stripARCUnbridgedCast(argExpr);
6046
6047 // If the parameter is __unknown_anytype, move on to the next method.
6048 if (param->getType() == Context.UnknownAnyTy) {
6049 Match = false;
6050 break;
6051 }
George Burgess IV45461812015-10-11 20:13:20 +00006052
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006053 ImplicitConversionSequence ConversionState
6054 = TryCopyInitialization(*this, argExpr, param->getType(),
6055 /*SuppressUserConversions*/false,
6056 /*InOverloadResolution=*/true,
6057 /*AllowObjCWritebackConversion=*/
6058 getLangOpts().ObjCAutoRefCount,
6059 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006060 // This function looks for a reasonably-exact match, so we consider
6061 // incompatible pointer conversions to be a failure here.
6062 if (ConversionState.isBad() ||
6063 (ConversionState.isStandard() &&
6064 ConversionState.Standard.Second ==
6065 ICK_Incompatible_Pointer_Conversion)) {
6066 Match = false;
6067 break;
6068 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006069 }
6070 // Promote additional arguments to variadic methods.
6071 if (Match && Method->isVariadic()) {
6072 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6073 if (Args[i]->isTypeDependent()) {
6074 Match = false;
6075 break;
6076 }
6077 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6078 nullptr);
6079 if (Arg.isInvalid()) {
6080 Match = false;
6081 break;
6082 }
6083 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006084 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006085 // Check for extra arguments to non-variadic methods.
6086 if (Args.size() != NumNamedArgs)
6087 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006088 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6089 // Special case when selectors have no argument. In this case, select
6090 // one with the most general result type of 'id'.
6091 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6092 QualType ReturnT = Methods[b]->getReturnType();
6093 if (ReturnT->isObjCIdType())
6094 return Methods[b];
6095 }
6096 }
6097 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006098
6099 if (Match)
6100 return Method;
6101 }
6102 return nullptr;
6103}
6104
George Burgess IV2a6150d2015-10-16 01:17:38 +00006105// specific_attr_iterator iterates over enable_if attributes in reverse, and
6106// enable_if is order-sensitive. As a result, we need to reverse things
6107// sometimes. Size of 4 elements is arbitrary.
6108static SmallVector<EnableIfAttr *, 4>
6109getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6110 SmallVector<EnableIfAttr *, 4> Result;
6111 if (!Function->hasAttrs())
6112 return Result;
6113
6114 const auto &FuncAttrs = Function->getAttrs();
6115 for (Attr *Attr : FuncAttrs)
6116 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6117 Result.push_back(EnableIf);
6118
6119 std::reverse(Result.begin(), Result.end());
6120 return Result;
6121}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006122
6123EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6124 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006125 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6126 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006127 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006128
6129 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006130 SmallVector<Expr *, 16> ConvertedArgs;
6131 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006132
George Burgess IV458b3f32016-08-12 04:19:35 +00006133 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006134 // user can't refer to them in the enable_if condition.
6135 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6136
Nick Lewyckye283c552015-08-25 22:33:16 +00006137 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006138 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006139 ExprResult R;
6140 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006141 !cast<CXXMethodDecl>(Function)->isStatic() &&
6142 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006143 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006144 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6145 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006146 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006147 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6148 Context, Function->getParamDecl(I)),
6149 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006150 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006151
6152 if (R.isInvalid()) {
6153 InitializationFailed = true;
6154 break;
6155 }
6156
George Burgess IVe96abf72016-02-24 22:31:14 +00006157 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006158 }
6159
6160 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006161 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006162
Nick Lewyckye283c552015-08-25 22:33:16 +00006163 // Push default arguments if needed.
6164 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6165 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6166 ParmVarDecl *P = Function->getParamDecl(i);
6167 ExprResult R = PerformCopyInitialization(
6168 InitializedEntity::InitializeParameter(Context,
6169 Function->getParamDecl(i)),
6170 SourceLocation(),
6171 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6172 : P->getDefaultArg());
6173 if (R.isInvalid()) {
6174 InitializationFailed = true;
6175 break;
6176 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006177 ConvertedArgs.push_back(R.get());
6178 }
6179
6180 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006181 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006182 }
6183
George Burgess IV2a6150d2015-10-16 01:17:38 +00006184 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006185 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006186 // FIXME: This doesn't consider value-dependent cases, because doing so is
6187 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006188 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006189 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006190 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006191
6192 if (!Result.isInt() || !Result.getInt().getBoolValue())
6193 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006194 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006195 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006196}
6197
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006198/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006199/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006200void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006201 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006202 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006203 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006204 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006205 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006206 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006207 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6208 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006209 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006210 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006211 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006212 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006213 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006214 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006215 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006216 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006217 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006218 } else {
John McCalla0296f72010-03-19 07:35:19 +00006219 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006220 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6221 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006222 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006223 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006224 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006225 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006226 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006227 CandidateSet, SuppressUserConversions,
6228 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006229 else
John McCalla0296f72010-03-19 07:35:19 +00006230 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006231 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006232 CandidateSet, SuppressUserConversions,
6233 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006234 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006235 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006236}
6237
John McCallf0f1cf02009-11-17 07:50:12 +00006238/// AddMethodCandidate - Adds a named decl (which is some kind of
6239/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006240void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006241 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006242 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006243 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006244 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006245 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006246 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006247 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006248
6249 if (isa<UsingShadowDecl>(Decl))
6250 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006251
John McCallf0f1cf02009-11-17 07:50:12 +00006252 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6253 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6254 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006255 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006256 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006257 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006258 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006259 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006260 } else {
John McCalla0296f72010-03-19 07:35:19 +00006261 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006262 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006263 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006264 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006265 }
6266}
6267
Douglas Gregor436424c2008-11-18 23:14:02 +00006268/// AddMethodCandidate - Adds the given C++ member function to the set
6269/// of candidate functions, using the given function call arguments
6270/// and the object argument (@c Object). For example, in a call
6271/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6272/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6273/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006274/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006275void
John McCalla0296f72010-03-19 07:35:19 +00006276Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006277 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006278 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006279 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006280 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006281 bool SuppressUserConversions,
Renato Golindad96d62017-01-02 11:15:42 +00006282 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006283 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006284 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006285 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006286 assert(!isa<CXXConstructorDecl>(Method) &&
6287 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006288
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006289 if (!CandidateSet.isNewCandidate(Method))
6290 return;
6291
Richard Smith8b86f2d2013-11-04 01:48:18 +00006292 // C++11 [class.copy]p23: [DR1402]
6293 // A defaulted move assignment operator that is defined as deleted is
6294 // ignored by overload resolution.
6295 if (Method->isDefaulted() && Method->isDeleted() &&
6296 Method->isMoveAssignmentOperator())
6297 return;
6298
Douglas Gregor27381f32009-11-23 12:27:39 +00006299 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006300 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006301
Douglas Gregor436424c2008-11-18 23:14:02 +00006302 // Add this candidate
Renato Golindad96d62017-01-02 11:15:42 +00006303 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006304 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006305 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006306 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006307 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006308 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006309
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006310 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006311
6312 // (C++ 13.3.2p2): A candidate function having fewer than m
6313 // parameters is viable only if it has an ellipsis in its parameter
6314 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006315 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6316 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006317 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006318 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006319 return;
6320 }
6321
6322 // (C++ 13.3.2p2): A candidate function having more than m parameters
6323 // is viable only if the (m+1)st parameter has a default argument
6324 // (8.3.6). For the purposes of overload resolution, the
6325 // parameter list is truncated on the right, so that there are
6326 // exactly m parameters.
6327 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006328 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006329 // Not enough arguments.
6330 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006331 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006332 return;
6333 }
6334
6335 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006336
John McCall6e9f8f62009-12-03 04:06:58 +00006337 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006338 // The implicit object argument is ignored.
6339 Candidate.IgnoreObjectArgument = true;
6340 else {
6341 // Determine the implicit conversion sequence for the object
6342 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006343 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6344 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6345 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006346 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006347 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006348 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006349 return;
6350 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006351 }
6352
Eli Bendersky291a57e2014-09-25 23:59:08 +00006353 // (CUDA B.1): Check for invalid calls between targets.
6354 if (getLangOpts().CUDA)
6355 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006356 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006357 Candidate.Viable = false;
6358 Candidate.FailureKind = ovl_fail_bad_target;
6359 return;
6360 }
6361
Douglas Gregor436424c2008-11-18 23:14:02 +00006362 // Determine the implicit conversion sequences for each of the
6363 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006364 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Renato Golindad96d62017-01-02 11:15:42 +00006365 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006366 // (C++ 13.3.2p3): for F to be a viable function, there shall
6367 // exist for each argument an implicit conversion sequence
6368 // (13.3.3.1) that converts that argument to the corresponding
6369 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006370 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006371 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006372 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006373 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006374 /*InOverloadResolution=*/true,
6375 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006376 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006377 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006378 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006379 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006380 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006381 }
6382 } else {
6383 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6384 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006385 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006386 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006387 }
6388 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006389
6390 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6391 Candidate.Viable = false;
6392 Candidate.FailureKind = ovl_fail_enable_if;
6393 Candidate.DeductionFailure.Data = FailedAttr;
6394 return;
6395 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006396}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006397
Douglas Gregor97628d62009-08-21 00:16:32 +00006398/// \brief Add a C++ member function template as a candidate to the candidate
6399/// set, using template argument deduction to produce an appropriate member
6400/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006401void
Douglas Gregor97628d62009-08-21 00:16:32 +00006402Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006403 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006404 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006405 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006406 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006407 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006408 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006409 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006410 bool SuppressUserConversions,
6411 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006412 if (!CandidateSet.isNewCandidate(MethodTmpl))
6413 return;
6414
Douglas Gregor97628d62009-08-21 00:16:32 +00006415 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006416 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006417 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006418 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006419 // candidate functions in the usual way.113) A given name can refer to one
6420 // or more function templates and also to a set of overloaded non-template
6421 // functions. In such a case, the candidate functions generated from each
6422 // function template are combined with the set of non-template candidate
6423 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006424 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006425 FunctionDecl *Specialization = nullptr;
Renato Golindad96d62017-01-02 11:15:42 +00006426 if (TemplateDeductionResult Result
6427 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6428 Specialization, Info, PartialOverloading)) {
6429 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006430 Candidate.FoundDecl = FoundDecl;
6431 Candidate.Function = MethodTmpl->getTemplatedDecl();
6432 Candidate.Viable = false;
Renato Golindad96d62017-01-02 11:15:42 +00006433 Candidate.FailureKind = ovl_fail_bad_deduction;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006434 Candidate.IsSurrogate = false;
6435 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006436 Candidate.ExplicitCallArguments = Args.size();
Renato Golindad96d62017-01-02 11:15:42 +00006437 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6438 Info);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006439 return;
6440 }
Mike Stump11289f42009-09-09 15:08:12 +00006441
Douglas Gregor97628d62009-08-21 00:16:32 +00006442 // Add the function template specialization produced by template argument
6443 // deduction as a candidate.
6444 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006445 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006446 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006447 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006448 ActingContext, ObjectType, ObjectClassification, Args,
Renato Golindad96d62017-01-02 11:15:42 +00006449 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006450}
6451
Douglas Gregor05155d82009-08-21 23:19:43 +00006452/// \brief Add a C++ function template specialization as a candidate
6453/// in the candidate set, using template argument deduction to produce
6454/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006455void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006456Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006457 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006458 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006459 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006460 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006461 bool SuppressUserConversions,
6462 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006463 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6464 return;
6465
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006466 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006467 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006468 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006469 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006470 // candidate functions in the usual way.113) A given name can refer to one
6471 // or more function templates and also to a set of overloaded non-template
6472 // functions. In such a case, the candidate functions generated from each
6473 // function template are combined with the set of non-template candidate
6474 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006475 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006476 FunctionDecl *Specialization = nullptr;
Renato Golindad96d62017-01-02 11:15:42 +00006477 if (TemplateDeductionResult Result
6478 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6479 Specialization, Info, PartialOverloading)) {
6480 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006481 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006482 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6483 Candidate.Viable = false;
Renato Golindad96d62017-01-02 11:15:42 +00006484 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006485 Candidate.IsSurrogate = false;
6486 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006487 Candidate.ExplicitCallArguments = Args.size();
Renato Golindad96d62017-01-02 11:15:42 +00006488 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6489 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006490 return;
6491 }
Mike Stump11289f42009-09-09 15:08:12 +00006492
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006493 // Add the function template specialization produced by template argument
6494 // deduction as a candidate.
6495 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006496 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Renato Golindad96d62017-01-02 11:15:42 +00006497 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006498}
Mike Stump11289f42009-09-09 15:08:12 +00006499
Douglas Gregor4b60a152013-11-07 22:34:54 +00006500/// Determine whether this is an allowable conversion from the result
6501/// of an explicit conversion operator to the expected type, per C++
6502/// [over.match.conv]p1 and [over.match.ref]p1.
6503///
6504/// \param ConvType The return type of the conversion function.
6505///
6506/// \param ToType The type we are converting to.
6507///
6508/// \param AllowObjCPointerConversion Allow a conversion from one
6509/// Objective-C pointer to another.
6510///
6511/// \returns true if the conversion is allowable, false otherwise.
6512static bool isAllowableExplicitConversion(Sema &S,
6513 QualType ConvType, QualType ToType,
6514 bool AllowObjCPointerConversion) {
6515 QualType ToNonRefType = ToType.getNonReferenceType();
6516
6517 // Easy case: the types are the same.
6518 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6519 return true;
6520
6521 // Allow qualification conversions.
6522 bool ObjCLifetimeConversion;
6523 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6524 ObjCLifetimeConversion))
6525 return true;
6526
6527 // If we're not allowed to consider Objective-C pointer conversions,
6528 // we're done.
6529 if (!AllowObjCPointerConversion)
6530 return false;
6531
6532 // Is this an Objective-C pointer conversion?
6533 bool IncompatibleObjC = false;
6534 QualType ConvertedType;
6535 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6536 IncompatibleObjC);
6537}
6538
Douglas Gregora1f013e2008-11-07 22:36:19 +00006539/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006540/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006541/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006542/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006543/// (which may or may not be the same type as the type that the
6544/// conversion function produces).
6545void
6546Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006547 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006548 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006549 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006550 OverloadCandidateSet& CandidateSet,
6551 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006552 assert(!Conversion->getDescribedFunctionTemplate() &&
6553 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006554 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006555 if (!CandidateSet.isNewCandidate(Conversion))
6556 return;
6557
Richard Smith2a7d4812013-05-04 07:00:32 +00006558 // If the conversion function has an undeduced return type, trigger its
6559 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006560 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006561 if (DeduceReturnType(Conversion, From->getExprLoc()))
6562 return;
6563 ConvType = Conversion->getConversionType().getNonReferenceType();
6564 }
6565
Richard Smith089c3162013-09-21 21:55:46 +00006566 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6567 // operator is only a candidate if its return type is the target type or
6568 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006569 if (Conversion->isExplicit() &&
6570 !isAllowableExplicitConversion(*this, ConvType, ToType,
6571 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006572 return;
6573
Douglas Gregor27381f32009-11-23 12:27:39 +00006574 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006575 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006576
Douglas Gregora1f013e2008-11-07 22:36:19 +00006577 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006578 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006579 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006580 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006581 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006582 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006583 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006584 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006585 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006586 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006587 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006588
Douglas Gregor6affc782010-08-19 15:37:02 +00006589 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590 // For conversion functions, the function is considered to be a member of
6591 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006592 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006593 //
6594 // Determine the implicit conversion sequence for the implicit
6595 // object parameter.
6596 QualType ImplicitParamType = From->getType();
6597 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6598 ImplicitParamType = FromPtrType->getPointeeType();
6599 CXXRecordDecl *ConversionContext
6600 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601
Richard Smith0f59cb32015-12-18 21:45:41 +00006602 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6603 *this, CandidateSet.getLocation(), From->getType(),
6604 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605
John McCall0d1da222010-01-12 00:44:57 +00006606 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006607 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006608 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006609 return;
6610 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006611
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006612 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006613 // derived to base as such conversions are given Conversion Rank. They only
6614 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6615 QualType FromCanon
6616 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6617 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006618 if (FromCanon == ToCanon ||
6619 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006620 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006621 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006622 return;
6623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006624
Douglas Gregora1f013e2008-11-07 22:36:19 +00006625 // To determine what the conversion from the result of calling the
6626 // conversion function to the type we're eventually trying to
6627 // convert to (ToType), we need to synthesize a call to the
6628 // conversion function and attempt copy initialization from it. This
6629 // makes sure that we get the right semantics with respect to
6630 // lvalues/rvalues and the type. Fortunately, we can allocate this
6631 // call on the stack and we don't need its arguments to be
6632 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006633 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006634 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006635 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6636 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006637 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006638 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006639
Richard Smith48d24642011-07-13 22:53:21 +00006640 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006641 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006642 Candidate.Viable = false;
6643 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6644 return;
6645 }
6646
Richard Smith48d24642011-07-13 22:53:21 +00006647 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006648
Mike Stump11289f42009-09-09 15:08:12 +00006649 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006650 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6651 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006652 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006653 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006654 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006655 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006656 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006657 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006658 /*InOverloadResolution=*/false,
6659 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006660
John McCall0d1da222010-01-12 00:44:57 +00006661 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006662 case ImplicitConversionSequence::StandardConversion:
6663 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006665 // C++ [over.ics.user]p3:
6666 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006667 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006668 // shall have exact match rank.
6669 if (Conversion->getPrimaryTemplate() &&
6670 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6671 Candidate.Viable = false;
6672 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006673 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006675
Douglas Gregorcba72b12011-01-21 05:18:22 +00006676 // C++0x [dcl.init.ref]p5:
6677 // In the second case, if the reference is an rvalue reference and
6678 // the second standard conversion sequence of the user-defined
6679 // conversion sequence includes an lvalue-to-rvalue conversion, the
6680 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006682 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6683 Candidate.Viable = false;
6684 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006685 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006686 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006687 break;
6688
6689 case ImplicitConversionSequence::BadConversion:
6690 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006691 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006692 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006693
6694 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006695 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006696 "Can only end up with a standard conversion sequence or failure");
6697 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006698
Craig Topper5fc8fc22014-08-27 06:28:36 +00006699 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006700 Candidate.Viable = false;
6701 Candidate.FailureKind = ovl_fail_enable_if;
6702 Candidate.DeductionFailure.Data = FailedAttr;
6703 return;
6704 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006705}
6706
Douglas Gregor05155d82009-08-21 23:19:43 +00006707/// \brief Adds a conversion function template specialization
6708/// candidate to the overload set, using template argument deduction
6709/// to deduce the template arguments of the conversion function
6710/// template from the type that we are converting to (C++
6711/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006712void
Douglas Gregor05155d82009-08-21 23:19:43 +00006713Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006714 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006715 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006716 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006717 OverloadCandidateSet &CandidateSet,
6718 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006719 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6720 "Only conversion function templates permitted here");
6721
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006722 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6723 return;
6724
Craig Toppere6706e42012-09-19 02:26:47 +00006725 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006726 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006727 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006728 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006729 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006730 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006731 Candidate.FoundDecl = FoundDecl;
6732 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6733 Candidate.Viable = false;
6734 Candidate.FailureKind = ovl_fail_bad_deduction;
6735 Candidate.IsSurrogate = false;
6736 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006737 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006739 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006740 return;
6741 }
Mike Stump11289f42009-09-09 15:08:12 +00006742
Douglas Gregor05155d82009-08-21 23:19:43 +00006743 // Add the conversion function template specialization produced by
6744 // template argument deduction as a candidate.
6745 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006746 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006747 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006748}
6749
Douglas Gregorab7897a2008-11-19 22:57:39 +00006750/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6751/// converts the given @c Object to a function pointer via the
6752/// conversion function @c Conversion, and then attempts to call it
6753/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6754/// the type of function that we'll eventually be calling.
6755void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006756 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006757 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006758 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006759 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006760 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006761 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006762 if (!CandidateSet.isNewCandidate(Conversion))
6763 return;
6764
Douglas Gregor27381f32009-11-23 12:27:39 +00006765 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006766 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006767
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006768 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006769 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006770 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006771 Candidate.Surrogate = Conversion;
6772 Candidate.Viable = true;
6773 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006774 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006775 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006776
6777 // Determine the implicit conversion sequence for the implicit
6778 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006779 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6780 *this, CandidateSet.getLocation(), Object->getType(),
6781 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006782 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006783 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006784 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006785 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006786 return;
6787 }
6788
6789 // The first conversion is actually a user-defined conversion whose
6790 // first conversion is ObjectInit's standard conversion (which is
6791 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006792 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006793 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006794 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006795 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006796 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006797 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006798 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006799 = Candidate.Conversions[0].UserDefined.Before;
6800 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6801
Mike Stump11289f42009-09-09 15:08:12 +00006802 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006803 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006804
6805 // (C++ 13.3.2p2): A candidate function having fewer than m
6806 // parameters is viable only if it has an ellipsis in its parameter
6807 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006808 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006809 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006810 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006811 return;
6812 }
6813
6814 // Function types don't have any default arguments, so just check if
6815 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006816 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006817 // Not enough arguments.
6818 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006819 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006820 return;
6821 }
6822
6823 // Determine the implicit conversion sequences for each of the
6824 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006825 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006826 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006827 // (C++ 13.3.2p3): for F to be a viable function, there shall
6828 // exist for each argument an implicit conversion sequence
6829 // (13.3.3.1) that converts that argument to the corresponding
6830 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006831 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006832 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006833 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006834 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006835 /*InOverloadResolution=*/false,
6836 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006837 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006838 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006839 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006840 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006841 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006842 }
6843 } else {
6844 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6845 // argument for which there is no corresponding parameter is
6846 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006847 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006848 }
6849 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006850
Craig Topper5fc8fc22014-08-27 06:28:36 +00006851 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006852 Candidate.Viable = false;
6853 Candidate.FailureKind = ovl_fail_enable_if;
6854 Candidate.DeductionFailure.Data = FailedAttr;
6855 return;
6856 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006857}
6858
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006859/// \brief Add overload candidates for overloaded operators that are
6860/// member functions.
6861///
6862/// Add the overloaded operator candidates that are member functions
6863/// for the operator Op that was used in an operator expression such
6864/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6865/// CandidateSet will store the added overload candidates. (C++
6866/// [over.match.oper]).
6867void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6868 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006869 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006870 OverloadCandidateSet& CandidateSet,
6871 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006872 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6873
6874 // C++ [over.match.oper]p3:
6875 // For a unary operator @ with an operand of a type whose
6876 // cv-unqualified version is T1, and for a binary operator @ with
6877 // a left operand of a type whose cv-unqualified version is T1 and
6878 // a right operand of a type whose cv-unqualified version is T2,
6879 // three sets of candidate functions, designated member
6880 // candidates, non-member candidates and built-in candidates, are
6881 // constructed as follows:
6882 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006883
Richard Smith0feaf0c2013-04-20 12:41:22 +00006884 // -- If T1 is a complete class type or a class currently being
6885 // defined, the set of member candidates is the result of the
6886 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6887 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006888 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006889 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006890 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006891 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006892 // If the type is neither complete nor being defined, bail out now.
6893 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006894 return;
Mike Stump11289f42009-09-09 15:08:12 +00006895
John McCall27b18f82009-11-17 02:14:36 +00006896 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6897 LookupQualifiedName(Operators, T1Rec->getDecl());
6898 Operators.suppressDiagnostics();
6899
Mike Stump11289f42009-09-09 15:08:12 +00006900 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006901 OperEnd = Operators.end();
6902 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006903 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006904 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006905 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006906 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006907 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006908 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006909 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006910}
6911
Douglas Gregora11693b2008-11-12 17:17:38 +00006912/// AddBuiltinCandidate - Add a candidate for a built-in
6913/// operator. ResultTy and ParamTys are the result and parameter types
6914/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006915/// arguments being passed to the candidate. IsAssignmentOperator
6916/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006917/// operator. NumContextualBoolArguments is the number of arguments
6918/// (at the beginning of the argument list) that will be contextually
6919/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006920void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006921 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006922 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006923 bool IsAssignmentOperator,
6924 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006925 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006926 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006927
Douglas Gregora11693b2008-11-12 17:17:38 +00006928 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006929 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006930 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6931 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006932 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006933 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006934 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006935 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006936 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6937
6938 // Determine the implicit conversion sequences for each of the
6939 // arguments.
6940 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006941 Candidate.ExplicitCallArguments = Args.size();
6942 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006943 // C++ [over.match.oper]p4:
6944 // For the built-in assignment operators, conversions of the
6945 // left operand are restricted as follows:
6946 // -- no temporaries are introduced to hold the left operand, and
6947 // -- no user-defined conversions are applied to the left
6948 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006949 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006950 //
6951 // We block these conversions by turning off user-defined
6952 // conversions, since that is the only way that initialization of
6953 // a reference to a non-class type can occur from something that
6954 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006955 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006956 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006957 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006958 Candidate.Conversions[ArgIdx]
6959 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006960 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006961 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006962 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006963 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006964 /*InOverloadResolution=*/false,
6965 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006966 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006967 }
John McCall0d1da222010-01-12 00:44:57 +00006968 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006969 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006970 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006971 break;
6972 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006973 }
6974}
6975
Craig Toppercd7b0332013-07-01 06:29:40 +00006976namespace {
6977
Douglas Gregora11693b2008-11-12 17:17:38 +00006978/// BuiltinCandidateTypeSet - A set of types that will be used for the
6979/// candidate operator functions for built-in operators (C++
6980/// [over.built]). The types are separated into pointer types and
6981/// enumeration types.
6982class BuiltinCandidateTypeSet {
6983 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006984 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6985 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006986
6987 /// PointerTypes - The set of pointer types that will be used in the
6988 /// built-in candidates.
6989 TypeSet PointerTypes;
6990
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006991 /// MemberPointerTypes - The set of member pointer types that will be
6992 /// used in the built-in candidates.
6993 TypeSet MemberPointerTypes;
6994
Douglas Gregora11693b2008-11-12 17:17:38 +00006995 /// EnumerationTypes - The set of enumeration types that will be
6996 /// used in the built-in candidates.
6997 TypeSet EnumerationTypes;
6998
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007000 /// candidates.
7001 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007002
7003 /// \brief A flag indicating non-record types are viable candidates
7004 bool HasNonRecordTypes;
7005
7006 /// \brief A flag indicating whether either arithmetic or enumeration types
7007 /// were present in the candidate set.
7008 bool HasArithmeticOrEnumeralTypes;
7009
Douglas Gregor80af3132011-05-21 23:15:46 +00007010 /// \brief A flag indicating whether the nullptr type was present in the
7011 /// candidate set.
7012 bool HasNullPtrType;
7013
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007014 /// Sema - The semantic analysis instance where we are building the
7015 /// candidate type set.
7016 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007017
Douglas Gregora11693b2008-11-12 17:17:38 +00007018 /// Context - The AST context in which we will build the type sets.
7019 ASTContext &Context;
7020
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007021 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7022 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007023 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007024
7025public:
7026 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007027 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007028
Mike Stump11289f42009-09-09 15:08:12 +00007029 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007030 : HasNonRecordTypes(false),
7031 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007032 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007033 SemaRef(SemaRef),
7034 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007035
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007036 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007037 SourceLocation Loc,
7038 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007039 bool AllowExplicitConversions,
7040 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007041
7042 /// pointer_begin - First pointer type found;
7043 iterator pointer_begin() { return PointerTypes.begin(); }
7044
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007045 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007046 iterator pointer_end() { return PointerTypes.end(); }
7047
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007048 /// member_pointer_begin - First member pointer type found;
7049 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7050
7051 /// member_pointer_end - Past the last member pointer type found;
7052 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7053
Douglas Gregora11693b2008-11-12 17:17:38 +00007054 /// enumeration_begin - First enumeration type found;
7055 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7056
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007057 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007058 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007060 iterator vector_begin() { return VectorTypes.begin(); }
7061 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007062
7063 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7064 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007065 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007066};
7067
Craig Toppercd7b0332013-07-01 06:29:40 +00007068} // end anonymous namespace
7069
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007070/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007071/// the set of pointer types along with any more-qualified variants of
7072/// that type. For example, if @p Ty is "int const *", this routine
7073/// will add "int const *", "int const volatile *", "int const
7074/// restrict *", and "int const volatile restrict *" to the set of
7075/// pointer types. Returns true if the add of @p Ty itself succeeded,
7076/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007077///
7078/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007079bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007080BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7081 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007082
Douglas Gregora11693b2008-11-12 17:17:38 +00007083 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007084 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007085 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007087 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007088 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007089 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007090 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007091 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7092 PointeeTy = PTy->getPointeeType();
7093 buildObjCPtr = true;
7094 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007095 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007096 }
7097
Sebastian Redl4990a632009-11-18 20:39:26 +00007098 // Don't add qualified variants of arrays. For one, they're not allowed
7099 // (the qualifier would sink to the element type), and for another, the
7100 // only overload situation where it matters is subscript or pointer +- int,
7101 // and those shouldn't have qualifier variants anyway.
7102 if (PointeeTy->isArrayType())
7103 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007104
John McCall8ccfcb52009-09-24 19:53:00 +00007105 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007106 bool hasVolatile = VisibleQuals.hasVolatile();
7107 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007108
John McCall8ccfcb52009-09-24 19:53:00 +00007109 // Iterate through all strict supersets of BaseCVR.
7110 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7111 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007112 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007113 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007114
7115 // Skip over restrict if no restrict found anywhere in the types, or if
7116 // the type cannot be restrict-qualified.
7117 if ((CVR & Qualifiers::Restrict) &&
7118 (!hasRestrict ||
7119 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7120 continue;
7121
7122 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007123 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007124
7125 // Build qualified pointer type.
7126 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007127 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007128 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007129 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007130 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7131
7132 // Insert qualified pointer type.
7133 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007134 }
7135
7136 return true;
7137}
7138
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007139/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7140/// to the set of pointer types along with any more-qualified variants of
7141/// that type. For example, if @p Ty is "int const *", this routine
7142/// will add "int const *", "int const volatile *", "int const
7143/// restrict *", and "int const volatile restrict *" to the set of
7144/// pointer types. Returns true if the add of @p Ty itself succeeded,
7145/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007146///
7147/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007148bool
7149BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7150 QualType Ty) {
7151 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007152 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007153 return false;
7154
John McCall8ccfcb52009-09-24 19:53:00 +00007155 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7156 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007157
John McCall8ccfcb52009-09-24 19:53:00 +00007158 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007159 // Don't add qualified variants of arrays. For one, they're not allowed
7160 // (the qualifier would sink to the element type), and for another, the
7161 // only overload situation where it matters is subscript or pointer +- int,
7162 // and those shouldn't have qualifier variants anyway.
7163 if (PointeeTy->isArrayType())
7164 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007165 const Type *ClassTy = PointerTy->getClass();
7166
7167 // Iterate through all strict supersets of the pointee type's CVR
7168 // qualifiers.
7169 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7170 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7171 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007172
John McCall8ccfcb52009-09-24 19:53:00 +00007173 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007174 MemberPointerTypes.insert(
7175 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007176 }
7177
7178 return true;
7179}
7180
Douglas Gregora11693b2008-11-12 17:17:38 +00007181/// AddTypesConvertedFrom - Add each of the types to which the type @p
7182/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007183/// primarily interested in pointer types and enumeration types. We also
7184/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007185/// AllowUserConversions is true if we should look at the conversion
7186/// functions of a class type, and AllowExplicitConversions if we
7187/// should also include the explicit conversion functions of a class
7188/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007189void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007190BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007191 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007192 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007193 bool AllowExplicitConversions,
7194 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007195 // Only deal with canonical types.
7196 Ty = Context.getCanonicalType(Ty);
7197
7198 // Look through reference types; they aren't part of the type of an
7199 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007200 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007201 Ty = RefTy->getPointeeType();
7202
John McCall33ddac02011-01-19 10:06:00 +00007203 // If we're dealing with an array type, decay to the pointer.
7204 if (Ty->isArrayType())
7205 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7206
7207 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007208 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007209
Chandler Carruth00a38332010-12-13 01:44:01 +00007210 // Flag if we ever add a non-record type.
7211 const RecordType *TyRec = Ty->getAs<RecordType>();
7212 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7213
Chandler Carruth00a38332010-12-13 01:44:01 +00007214 // Flag if we encounter an arithmetic type.
7215 HasArithmeticOrEnumeralTypes =
7216 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7217
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007218 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7219 PointerTypes.insert(Ty);
7220 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007221 // Insert our type, and its more-qualified variants, into the set
7222 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007223 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007224 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007225 } else if (Ty->isMemberPointerType()) {
7226 // Member pointers are far easier, since the pointee can't be converted.
7227 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7228 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007229 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007230 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007231 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007232 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007233 // We treat vector types as arithmetic types in many contexts as an
7234 // extension.
7235 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007236 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007237 } else if (Ty->isNullPtrType()) {
7238 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007239 } else if (AllowUserConversions && TyRec) {
7240 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007241 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007242 return;
Mike Stump11289f42009-09-09 15:08:12 +00007243
Chandler Carruth00a38332010-12-13 01:44:01 +00007244 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007245 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007246 if (isa<UsingShadowDecl>(D))
7247 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007248
Chandler Carruth00a38332010-12-13 01:44:01 +00007249 // Skip conversion function templates; they don't tell us anything
7250 // about which builtin types we can convert to.
7251 if (isa<FunctionTemplateDecl>(D))
7252 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007253
Chandler Carruth00a38332010-12-13 01:44:01 +00007254 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7255 if (AllowExplicitConversions || !Conv->isExplicit()) {
7256 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7257 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007258 }
7259 }
7260 }
7261}
7262
Douglas Gregor84605ae2009-08-24 13:43:27 +00007263/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7264/// the volatile- and non-volatile-qualified assignment operators for the
7265/// given type to the candidate set.
7266static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7267 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007268 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007269 OverloadCandidateSet &CandidateSet) {
7270 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007271
Douglas Gregor84605ae2009-08-24 13:43:27 +00007272 // T& operator=(T&, T)
7273 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7274 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007275 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007276 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007277
Douglas Gregor84605ae2009-08-24 13:43:27 +00007278 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7279 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007280 ParamTypes[0]
7281 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007282 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007283 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007284 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007285 }
7286}
Mike Stump11289f42009-09-09 15:08:12 +00007287
Sebastian Redl1054fae2009-10-25 17:03:50 +00007288/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7289/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007290static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7291 Qualifiers VRQuals;
7292 const RecordType *TyRec;
7293 if (const MemberPointerType *RHSMPType =
7294 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007295 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007296 else
7297 TyRec = ArgExpr->getType()->getAs<RecordType>();
7298 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007299 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007300 VRQuals.addVolatile();
7301 VRQuals.addRestrict();
7302 return VRQuals;
7303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007304
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007305 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007306 if (!ClassDecl->hasDefinition())
7307 return VRQuals;
7308
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007309 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007310 if (isa<UsingShadowDecl>(D))
7311 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7312 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007313 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7314 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7315 CanTy = ResTypeRef->getPointeeType();
7316 // Need to go down the pointer/mempointer chain and add qualifiers
7317 // as see them.
7318 bool done = false;
7319 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007320 if (CanTy.isRestrictQualified())
7321 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007322 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7323 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007324 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007325 CanTy->getAs<MemberPointerType>())
7326 CanTy = ResTypeMPtr->getPointeeType();
7327 else
7328 done = true;
7329 if (CanTy.isVolatileQualified())
7330 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007331 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7332 return VRQuals;
7333 }
7334 }
7335 }
7336 return VRQuals;
7337}
John McCall52872982010-11-13 05:51:15 +00007338
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007339namespace {
John McCall52872982010-11-13 05:51:15 +00007340
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007341/// \brief Helper class to manage the addition of builtin operator overload
7342/// candidates. It provides shared state and utility methods used throughout
7343/// the process, as well as a helper method to add each group of builtin
7344/// operator overloads from the standard to a candidate set.
7345class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007346 // Common instance state available to all overload candidate addition methods.
7347 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007348 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007349 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007350 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007351 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007352 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007353
Chandler Carruthc6586e52010-12-12 10:35:00 +00007354 // Define some constants used to index and iterate over the arithemetic types
7355 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007356 // The "promoted arithmetic types" are the arithmetic
7357 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007358 static const unsigned FirstIntegralType = 4;
7359 static const unsigned LastIntegralType = 21;
7360 static const unsigned FirstPromotedIntegralType = 4,
7361 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007362 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007363 LastPromotedArithmeticType = 12;
7364 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007365
Chandler Carruthc6586e52010-12-12 10:35:00 +00007366 /// \brief Get the canonical type for a given arithmetic type index.
7367 CanQualType getArithmeticType(unsigned index) {
7368 assert(index < NumArithmeticTypes);
7369 static CanQualType ASTContext::* const
7370 ArithmeticTypes[NumArithmeticTypes] = {
7371 // Start of promoted types.
7372 &ASTContext::FloatTy,
7373 &ASTContext::DoubleTy,
7374 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007375 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007376
Chandler Carruthc6586e52010-12-12 10:35:00 +00007377 // Start of integral types.
7378 &ASTContext::IntTy,
7379 &ASTContext::LongTy,
7380 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007381 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007382 &ASTContext::UnsignedIntTy,
7383 &ASTContext::UnsignedLongTy,
7384 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007385 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007386 // End of promoted types.
7387
7388 &ASTContext::BoolTy,
7389 &ASTContext::CharTy,
7390 &ASTContext::WCharTy,
7391 &ASTContext::Char16Ty,
7392 &ASTContext::Char32Ty,
7393 &ASTContext::SignedCharTy,
7394 &ASTContext::ShortTy,
7395 &ASTContext::UnsignedCharTy,
7396 &ASTContext::UnsignedShortTy,
7397 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007398 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007399 };
7400 return S.Context.*ArithmeticTypes[index];
7401 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007402
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007403 /// \brief Gets the canonical type resulting from the usual arithemetic
7404 /// converions for the given arithmetic types.
7405 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7406 // Accelerator table for performing the usual arithmetic conversions.
7407 // The rules are basically:
7408 // - if either is floating-point, use the wider floating-point
7409 // - if same signedness, use the higher rank
7410 // - if same size, use unsigned of the higher rank
7411 // - use the larger type
7412 // These rules, together with the axiom that higher ranks are
7413 // never smaller, are sufficient to precompute all of these results
7414 // *except* when dealing with signed types of higher rank.
7415 // (we could precompute SLL x UI for all known platforms, but it's
7416 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007417 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007418 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007419 Dep=-1,
7420 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007421 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007422 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007423 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007424/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7425/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7426/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7427/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7428/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7429/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7430/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7431/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7432/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7433/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7434/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007435 };
7436
7437 assert(L < LastPromotedArithmeticType);
7438 assert(R < LastPromotedArithmeticType);
7439 int Idx = ConversionsTable[L][R];
7440
7441 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007442 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007443
7444 // Slow path: we need to compare widths.
7445 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007446 CanQualType LT = getArithmeticType(L),
7447 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007448 unsigned LW = S.Context.getIntWidth(LT),
7449 RW = S.Context.getIntWidth(RT);
7450
7451 // If they're different widths, use the signed type.
7452 if (LW > RW) return LT;
7453 else if (LW < RW) return RT;
7454
7455 // Otherwise, use the unsigned type of the signed type's rank.
7456 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7457 assert(L == SLL || R == SLL);
7458 return S.Context.UnsignedLongLongTy;
7459 }
7460
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007461 /// \brief Helper method to factor out the common pattern of adding overloads
7462 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007463 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007464 bool HasVolatile,
7465 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007466 QualType ParamTypes[2] = {
7467 S.Context.getLValueReferenceType(CandidateTy),
7468 S.Context.IntTy
7469 };
7470
7471 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007472 if (Args.size() == 1)
7473 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 else
Richard Smithe54c3072013-05-05 15:51:06 +00007475 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476
7477 // Use a heuristic to reduce number of builtin candidates in the set:
7478 // add volatile version only if there are conversions to a volatile type.
7479 if (HasVolatile) {
7480 ParamTypes[0] =
7481 S.Context.getLValueReferenceType(
7482 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007483 if (Args.size() == 1)
7484 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007485 else
Richard Smithe54c3072013-05-05 15:51:06 +00007486 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007487 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007488
7489 // Add restrict version only if there are conversions to a restrict type
7490 // and our candidate type is a non-restrict-qualified pointer.
7491 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7492 !CandidateTy.isRestrictQualified()) {
7493 ParamTypes[0]
7494 = S.Context.getLValueReferenceType(
7495 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007496 if (Args.size() == 1)
7497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007498 else
Richard Smithe54c3072013-05-05 15:51:06 +00007499 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007500
7501 if (HasVolatile) {
7502 ParamTypes[0]
7503 = S.Context.getLValueReferenceType(
7504 S.Context.getCVRQualifiedType(CandidateTy,
7505 (Qualifiers::Volatile |
7506 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007507 if (Args.size() == 1)
7508 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007509 else
Richard Smithe54c3072013-05-05 15:51:06 +00007510 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007511 }
7512 }
7513
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 }
7515
7516public:
7517 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007518 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007519 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007520 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007521 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007522 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007523 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007524 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007525 HasArithmeticOrEnumeralCandidateType(
7526 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007527 CandidateTypes(CandidateTypes),
7528 CandidateSet(CandidateSet) {
7529 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007530 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007531 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007532 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007533 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007534 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007535 assert(getArithmeticType(FirstPromotedArithmeticType)
7536 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007537 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007538 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007539 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007540 "Invalid last promoted arithmetic type");
7541 }
7542
7543 // C++ [over.built]p3:
7544 //
7545 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7546 // is either volatile or empty, there exist candidate operator
7547 // functions of the form
7548 //
7549 // VQ T& operator++(VQ T&);
7550 // T operator++(VQ T&, int);
7551 //
7552 // C++ [over.built]p4:
7553 //
7554 // For every pair (T, VQ), where T is an arithmetic type other
7555 // than bool, and VQ is either volatile or empty, there exist
7556 // candidate operator functions of the form
7557 //
7558 // VQ T& operator--(VQ T&);
7559 // T operator--(VQ T&, int);
7560 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007561 if (!HasArithmeticOrEnumeralCandidateType)
7562 return;
7563
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007564 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7565 Arith < NumArithmeticTypes; ++Arith) {
7566 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007567 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007568 VisibleTypeConversionsQuals.hasVolatile(),
7569 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007570 }
7571 }
7572
7573 // C++ [over.built]p5:
7574 //
7575 // For every pair (T, VQ), where T is a cv-qualified or
7576 // cv-unqualified object type, and VQ is either volatile or
7577 // empty, there exist candidate operator functions of the form
7578 //
7579 // T*VQ& operator++(T*VQ&);
7580 // T*VQ& operator--(T*VQ&);
7581 // T* operator++(T*VQ&, int);
7582 // T* operator--(T*VQ&, int);
7583 void addPlusPlusMinusMinusPointerOverloads() {
7584 for (BuiltinCandidateTypeSet::iterator
7585 Ptr = CandidateTypes[0].pointer_begin(),
7586 PtrEnd = CandidateTypes[0].pointer_end();
7587 Ptr != PtrEnd; ++Ptr) {
7588 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007589 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007590 continue;
7591
7592 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007593 (!(*Ptr).isVolatileQualified() &&
7594 VisibleTypeConversionsQuals.hasVolatile()),
7595 (!(*Ptr).isRestrictQualified() &&
7596 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007597 }
7598 }
7599
7600 // C++ [over.built]p6:
7601 // For every cv-qualified or cv-unqualified object type T, there
7602 // exist candidate operator functions of the form
7603 //
7604 // T& operator*(T*);
7605 //
7606 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007608 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007609 // T& operator*(T*);
7610 void addUnaryStarPointerOverloads() {
7611 for (BuiltinCandidateTypeSet::iterator
7612 Ptr = CandidateTypes[0].pointer_begin(),
7613 PtrEnd = CandidateTypes[0].pointer_end();
7614 Ptr != PtrEnd; ++Ptr) {
7615 QualType ParamTy = *Ptr;
7616 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007617 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7618 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007619
Douglas Gregor02824322011-01-26 19:30:28 +00007620 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7621 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7622 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007623
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007624 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007625 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007626 }
7627 }
7628
7629 // C++ [over.built]p9:
7630 // For every promoted arithmetic type T, there exist candidate
7631 // operator functions of the form
7632 //
7633 // T operator+(T);
7634 // T operator-(T);
7635 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007636 if (!HasArithmeticOrEnumeralCandidateType)
7637 return;
7638
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007639 for (unsigned Arith = FirstPromotedArithmeticType;
7640 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007641 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007642 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007643 }
7644
7645 // Extension: We also add these operators for vector types.
7646 for (BuiltinCandidateTypeSet::iterator
7647 Vec = CandidateTypes[0].vector_begin(),
7648 VecEnd = CandidateTypes[0].vector_end();
7649 Vec != VecEnd; ++Vec) {
7650 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007651 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007652 }
7653 }
7654
7655 // C++ [over.built]p8:
7656 // For every type T, there exist candidate operator functions of
7657 // the form
7658 //
7659 // T* operator+(T*);
7660 void addUnaryPlusPointerOverloads() {
7661 for (BuiltinCandidateTypeSet::iterator
7662 Ptr = CandidateTypes[0].pointer_begin(),
7663 PtrEnd = CandidateTypes[0].pointer_end();
7664 Ptr != PtrEnd; ++Ptr) {
7665 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007666 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 }
7668 }
7669
7670 // C++ [over.built]p10:
7671 // For every promoted integral type T, there exist candidate
7672 // operator functions of the form
7673 //
7674 // T operator~(T);
7675 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007676 if (!HasArithmeticOrEnumeralCandidateType)
7677 return;
7678
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007679 for (unsigned Int = FirstPromotedIntegralType;
7680 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007681 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007682 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683 }
7684
7685 // Extension: We also add this operator for vector types.
7686 for (BuiltinCandidateTypeSet::iterator
7687 Vec = CandidateTypes[0].vector_begin(),
7688 VecEnd = CandidateTypes[0].vector_end();
7689 Vec != VecEnd; ++Vec) {
7690 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007691 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007692 }
7693 }
7694
7695 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007696 // For every pointer to member type T or type std::nullptr_t, there
7697 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007698 //
7699 // bool operator==(T,T);
7700 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007701 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 /// Set of (canonical) types that we've already handled.
7703 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7704
Richard Smithe54c3072013-05-05 15:51:06 +00007705 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007706 for (BuiltinCandidateTypeSet::iterator
7707 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7708 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7709 MemPtr != MemPtrEnd;
7710 ++MemPtr) {
7711 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007712 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 continue;
7714
7715 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007716 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007718
7719 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7720 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7721 if (AddedTypes.insert(NullPtrTy).second) {
7722 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7723 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7724 CandidateSet);
7725 }
7726 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007727 }
7728 }
7729
7730 // C++ [over.built]p15:
7731 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007732 // For every T, where T is an enumeration type or a pointer type,
7733 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007734 //
7735 // bool operator<(T, T);
7736 // bool operator>(T, T);
7737 // bool operator<=(T, T);
7738 // bool operator>=(T, T);
7739 // bool operator==(T, T);
7740 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007741 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007742 // C++ [over.match.oper]p3:
7743 // [...]the built-in candidates include all of the candidate operator
7744 // functions defined in 13.6 that, compared to the given operator, [...]
7745 // do not have the same parameter-type-list as any non-template non-member
7746 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007747 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007748 // Note that in practice, this only affects enumeration types because there
7749 // aren't any built-in candidates of record type, and a user-defined operator
7750 // must have an operand of record or enumeration type. Also, the only other
7751 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007752 // cannot be overloaded for enumeration types, so this is the only place
7753 // where we must suppress candidates like this.
7754 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7755 UserDefinedBinaryOperators;
7756
Richard Smithe54c3072013-05-05 15:51:06 +00007757 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007758 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7759 CandidateTypes[ArgIdx].enumeration_end()) {
7760 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7761 CEnd = CandidateSet.end();
7762 C != CEnd; ++C) {
7763 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7764 continue;
7765
Eli Friedman14f082b2012-09-18 21:52:24 +00007766 if (C->Function->isFunctionTemplateSpecialization())
7767 continue;
7768
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007769 QualType FirstParamType =
7770 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7771 QualType SecondParamType =
7772 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7773
7774 // Skip if either parameter isn't of enumeral type.
7775 if (!FirstParamType->isEnumeralType() ||
7776 !SecondParamType->isEnumeralType())
7777 continue;
7778
7779 // Add this operator to the set of known user-defined operators.
7780 UserDefinedBinaryOperators.insert(
7781 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7782 S.Context.getCanonicalType(SecondParamType)));
7783 }
7784 }
7785 }
7786
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787 /// Set of (canonical) types that we've already handled.
7788 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7789
Richard Smithe54c3072013-05-05 15:51:06 +00007790 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007791 for (BuiltinCandidateTypeSet::iterator
7792 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7793 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7794 Ptr != PtrEnd; ++Ptr) {
7795 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007796 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007797 continue;
7798
7799 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007800 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007801 }
7802 for (BuiltinCandidateTypeSet::iterator
7803 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7804 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7805 Enum != EnumEnd; ++Enum) {
7806 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7807
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007808 // Don't add the same builtin candidate twice, or if a user defined
7809 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007810 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007811 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7812 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007813 continue;
7814
7815 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007816 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007817 }
7818 }
7819 }
7820
7821 // C++ [over.built]p13:
7822 //
7823 // For every cv-qualified or cv-unqualified object type T
7824 // there exist candidate operator functions of the form
7825 //
7826 // T* operator+(T*, ptrdiff_t);
7827 // T& operator[](T*, ptrdiff_t); [BELOW]
7828 // T* operator-(T*, ptrdiff_t);
7829 // T* operator+(ptrdiff_t, T*);
7830 // T& operator[](ptrdiff_t, T*); [BELOW]
7831 //
7832 // C++ [over.built]p14:
7833 //
7834 // For every T, where T is a pointer to object type, there
7835 // exist candidate operator functions of the form
7836 //
7837 // ptrdiff_t operator-(T, T);
7838 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7839 /// Set of (canonical) types that we've already handled.
7840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7841
7842 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007843 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007844 S.Context.getPointerDiffType(),
7845 S.Context.getPointerDiffType(),
7846 };
7847 for (BuiltinCandidateTypeSet::iterator
7848 Ptr = CandidateTypes[Arg].pointer_begin(),
7849 PtrEnd = CandidateTypes[Arg].pointer_end();
7850 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007851 QualType PointeeTy = (*Ptr)->getPointeeType();
7852 if (!PointeeTy->isObjectType())
7853 continue;
7854
Eric Christopher9207a522015-08-21 16:24:01 +00007855 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007856 if (Arg == 0 || Op == OO_Plus) {
7857 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7858 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007859 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007860 }
7861 if (Op == OO_Minus) {
7862 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007863 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007864 continue;
7865
7866 QualType ParamTypes[2] = { *Ptr, *Ptr };
7867 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007868 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007869 }
7870 }
7871 }
7872 }
7873
7874 // C++ [over.built]p12:
7875 //
7876 // For every pair of promoted arithmetic types L and R, there
7877 // exist candidate operator functions of the form
7878 //
7879 // LR operator*(L, R);
7880 // LR operator/(L, R);
7881 // LR operator+(L, R);
7882 // LR operator-(L, R);
7883 // bool operator<(L, R);
7884 // bool operator>(L, R);
7885 // bool operator<=(L, R);
7886 // bool operator>=(L, R);
7887 // bool operator==(L, R);
7888 // bool operator!=(L, R);
7889 //
7890 // where LR is the result of the usual arithmetic conversions
7891 // between types L and R.
7892 //
7893 // C++ [over.built]p24:
7894 //
7895 // For every pair of promoted arithmetic types L and R, there exist
7896 // candidate operator functions of the form
7897 //
7898 // LR operator?(bool, L, R);
7899 //
7900 // where LR is the result of the usual arithmetic conversions
7901 // between types L and R.
7902 // Our candidates ignore the first parameter.
7903 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007904 if (!HasArithmeticOrEnumeralCandidateType)
7905 return;
7906
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007907 for (unsigned Left = FirstPromotedArithmeticType;
7908 Left < LastPromotedArithmeticType; ++Left) {
7909 for (unsigned Right = FirstPromotedArithmeticType;
7910 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007911 QualType LandR[2] = { getArithmeticType(Left),
7912 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007913 QualType Result =
7914 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007915 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007916 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007917 }
7918 }
7919
7920 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7921 // conditional operator for vector types.
7922 for (BuiltinCandidateTypeSet::iterator
7923 Vec1 = CandidateTypes[0].vector_begin(),
7924 Vec1End = CandidateTypes[0].vector_end();
7925 Vec1 != Vec1End; ++Vec1) {
7926 for (BuiltinCandidateTypeSet::iterator
7927 Vec2 = CandidateTypes[1].vector_begin(),
7928 Vec2End = CandidateTypes[1].vector_end();
7929 Vec2 != Vec2End; ++Vec2) {
7930 QualType LandR[2] = { *Vec1, *Vec2 };
7931 QualType Result = S.Context.BoolTy;
7932 if (!isComparison) {
7933 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7934 Result = *Vec1;
7935 else
7936 Result = *Vec2;
7937 }
7938
Richard Smithe54c3072013-05-05 15:51:06 +00007939 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007940 }
7941 }
7942 }
7943
7944 // C++ [over.built]p17:
7945 //
7946 // For every pair of promoted integral types L and R, there
7947 // exist candidate operator functions of the form
7948 //
7949 // LR operator%(L, R);
7950 // LR operator&(L, R);
7951 // LR operator^(L, R);
7952 // LR operator|(L, R);
7953 // L operator<<(L, R);
7954 // L operator>>(L, R);
7955 //
7956 // where LR is the result of the usual arithmetic conversions
7957 // between types L and R.
7958 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007959 if (!HasArithmeticOrEnumeralCandidateType)
7960 return;
7961
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007962 for (unsigned Left = FirstPromotedIntegralType;
7963 Left < LastPromotedIntegralType; ++Left) {
7964 for (unsigned Right = FirstPromotedIntegralType;
7965 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007966 QualType LandR[2] = { getArithmeticType(Left),
7967 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007968 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7969 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007970 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007971 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007972 }
7973 }
7974 }
7975
7976 // C++ [over.built]p20:
7977 //
7978 // For every pair (T, VQ), where T is an enumeration or
7979 // pointer to member type and VQ is either volatile or
7980 // empty, there exist candidate operator functions of the form
7981 //
7982 // VQ T& operator=(VQ T&, T);
7983 void addAssignmentMemberPointerOrEnumeralOverloads() {
7984 /// Set of (canonical) types that we've already handled.
7985 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7986
7987 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7988 for (BuiltinCandidateTypeSet::iterator
7989 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7990 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7991 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007992 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993 continue;
7994
Richard Smithe54c3072013-05-05 15:51:06 +00007995 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007996 }
7997
7998 for (BuiltinCandidateTypeSet::iterator
7999 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8000 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8001 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008002 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008003 continue;
8004
Richard Smithe54c3072013-05-05 15:51:06 +00008005 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008006 }
8007 }
8008 }
8009
8010 // C++ [over.built]p19:
8011 //
8012 // For every pair (T, VQ), where T is any type and VQ is either
8013 // volatile or empty, there exist candidate operator functions
8014 // of the form
8015 //
8016 // T*VQ& operator=(T*VQ&, T*);
8017 //
8018 // C++ [over.built]p21:
8019 //
8020 // For every pair (T, VQ), where T is a cv-qualified or
8021 // cv-unqualified object type and VQ is either volatile or
8022 // empty, there exist candidate operator functions of the form
8023 //
8024 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8025 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8026 void addAssignmentPointerOverloads(bool isEqualOp) {
8027 /// Set of (canonical) types that we've already handled.
8028 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8029
8030 for (BuiltinCandidateTypeSet::iterator
8031 Ptr = CandidateTypes[0].pointer_begin(),
8032 PtrEnd = CandidateTypes[0].pointer_end();
8033 Ptr != PtrEnd; ++Ptr) {
8034 // If this is operator=, keep track of the builtin candidates we added.
8035 if (isEqualOp)
8036 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008037 else if (!(*Ptr)->getPointeeType()->isObjectType())
8038 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008039
8040 // non-volatile version
8041 QualType ParamTypes[2] = {
8042 S.Context.getLValueReferenceType(*Ptr),
8043 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8044 };
Richard Smithe54c3072013-05-05 15:51:06 +00008045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046 /*IsAssigmentOperator=*/ isEqualOp);
8047
Douglas Gregor5bee2582012-06-04 00:15:09 +00008048 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8049 VisibleTypeConversionsQuals.hasVolatile();
8050 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008051 // volatile version
8052 ParamTypes[0] =
8053 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008054 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008055 /*IsAssigmentOperator=*/isEqualOp);
8056 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008057
8058 if (!(*Ptr).isRestrictQualified() &&
8059 VisibleTypeConversionsQuals.hasRestrict()) {
8060 // restrict version
8061 ParamTypes[0]
8062 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008063 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008064 /*IsAssigmentOperator=*/isEqualOp);
8065
8066 if (NeedVolatile) {
8067 // volatile restrict version
8068 ParamTypes[0]
8069 = S.Context.getLValueReferenceType(
8070 S.Context.getCVRQualifiedType(*Ptr,
8071 (Qualifiers::Volatile |
8072 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008073 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008074 /*IsAssigmentOperator=*/isEqualOp);
8075 }
8076 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008077 }
8078
8079 if (isEqualOp) {
8080 for (BuiltinCandidateTypeSet::iterator
8081 Ptr = CandidateTypes[1].pointer_begin(),
8082 PtrEnd = CandidateTypes[1].pointer_end();
8083 Ptr != PtrEnd; ++Ptr) {
8084 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008085 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 continue;
8087
Chandler Carruth8e543b32010-12-12 08:17:55 +00008088 QualType ParamTypes[2] = {
8089 S.Context.getLValueReferenceType(*Ptr),
8090 *Ptr,
8091 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008092
8093 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008094 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008095 /*IsAssigmentOperator=*/true);
8096
Douglas Gregor5bee2582012-06-04 00:15:09 +00008097 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8098 VisibleTypeConversionsQuals.hasVolatile();
8099 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008100 // volatile version
8101 ParamTypes[0] =
8102 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8104 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008105 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008106
8107 if (!(*Ptr).isRestrictQualified() &&
8108 VisibleTypeConversionsQuals.hasRestrict()) {
8109 // restrict version
8110 ParamTypes[0]
8111 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8113 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008114
8115 if (NeedVolatile) {
8116 // volatile restrict version
8117 ParamTypes[0]
8118 = S.Context.getLValueReferenceType(
8119 S.Context.getCVRQualifiedType(*Ptr,
8120 (Qualifiers::Volatile |
8121 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8123 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008124 }
8125 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008126 }
8127 }
8128 }
8129
8130 // C++ [over.built]p18:
8131 //
8132 // For every triple (L, VQ, R), where L is an arithmetic type,
8133 // VQ is either volatile or empty, and R is a promoted
8134 // arithmetic type, there exist candidate operator functions of
8135 // the form
8136 //
8137 // VQ L& operator=(VQ L&, R);
8138 // VQ L& operator*=(VQ L&, R);
8139 // VQ L& operator/=(VQ L&, R);
8140 // VQ L& operator+=(VQ L&, R);
8141 // VQ L& operator-=(VQ L&, R);
8142 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008143 if (!HasArithmeticOrEnumeralCandidateType)
8144 return;
8145
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008146 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8147 for (unsigned Right = FirstPromotedArithmeticType;
8148 Right < LastPromotedArithmeticType; ++Right) {
8149 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008150 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008151
8152 // Add this built-in operator as a candidate (VQ is empty).
8153 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008154 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008155 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008156 /*IsAssigmentOperator=*/isEqualOp);
8157
8158 // Add this built-in operator as a candidate (VQ is 'volatile').
8159 if (VisibleTypeConversionsQuals.hasVolatile()) {
8160 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008161 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008162 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008164 /*IsAssigmentOperator=*/isEqualOp);
8165 }
8166 }
8167 }
8168
8169 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8170 for (BuiltinCandidateTypeSet::iterator
8171 Vec1 = CandidateTypes[0].vector_begin(),
8172 Vec1End = CandidateTypes[0].vector_end();
8173 Vec1 != Vec1End; ++Vec1) {
8174 for (BuiltinCandidateTypeSet::iterator
8175 Vec2 = CandidateTypes[1].vector_begin(),
8176 Vec2End = CandidateTypes[1].vector_end();
8177 Vec2 != Vec2End; ++Vec2) {
8178 QualType ParamTypes[2];
8179 ParamTypes[1] = *Vec2;
8180 // Add this built-in operator as a candidate (VQ is empty).
8181 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008183 /*IsAssigmentOperator=*/isEqualOp);
8184
8185 // Add this built-in operator as a candidate (VQ is 'volatile').
8186 if (VisibleTypeConversionsQuals.hasVolatile()) {
8187 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8188 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008189 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008190 /*IsAssigmentOperator=*/isEqualOp);
8191 }
8192 }
8193 }
8194 }
8195
8196 // C++ [over.built]p22:
8197 //
8198 // For every triple (L, VQ, R), where L is an integral type, VQ
8199 // is either volatile or empty, and R is a promoted integral
8200 // type, there exist candidate operator functions of the form
8201 //
8202 // VQ L& operator%=(VQ L&, R);
8203 // VQ L& operator<<=(VQ L&, R);
8204 // VQ L& operator>>=(VQ L&, R);
8205 // VQ L& operator&=(VQ L&, R);
8206 // VQ L& operator^=(VQ L&, R);
8207 // VQ L& operator|=(VQ L&, R);
8208 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008209 if (!HasArithmeticOrEnumeralCandidateType)
8210 return;
8211
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008212 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8213 for (unsigned Right = FirstPromotedIntegralType;
8214 Right < LastPromotedIntegralType; ++Right) {
8215 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008216 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008217
8218 // Add this built-in operator as a candidate (VQ is empty).
8219 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008220 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008221 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008222 if (VisibleTypeConversionsQuals.hasVolatile()) {
8223 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008224 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008225 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8226 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008227 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008228 }
8229 }
8230 }
8231 }
8232
8233 // C++ [over.operator]p23:
8234 //
8235 // There also exist candidate operator functions of the form
8236 //
8237 // bool operator!(bool);
8238 // bool operator&&(bool, bool);
8239 // bool operator||(bool, bool);
8240 void addExclaimOverload() {
8241 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008242 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008243 /*IsAssignmentOperator=*/false,
8244 /*NumContextualBoolArguments=*/1);
8245 }
8246 void addAmpAmpOrPipePipeOverload() {
8247 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008248 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008249 /*IsAssignmentOperator=*/false,
8250 /*NumContextualBoolArguments=*/2);
8251 }
8252
8253 // C++ [over.built]p13:
8254 //
8255 // For every cv-qualified or cv-unqualified object type T there
8256 // exist candidate operator functions of the form
8257 //
8258 // T* operator+(T*, ptrdiff_t); [ABOVE]
8259 // T& operator[](T*, ptrdiff_t);
8260 // T* operator-(T*, ptrdiff_t); [ABOVE]
8261 // T* operator+(ptrdiff_t, T*); [ABOVE]
8262 // T& operator[](ptrdiff_t, T*);
8263 void addSubscriptOverloads() {
8264 for (BuiltinCandidateTypeSet::iterator
8265 Ptr = CandidateTypes[0].pointer_begin(),
8266 PtrEnd = CandidateTypes[0].pointer_end();
8267 Ptr != PtrEnd; ++Ptr) {
8268 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8269 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008270 if (!PointeeType->isObjectType())
8271 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008272
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008273 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8274
8275 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008276 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008277 }
8278
8279 for (BuiltinCandidateTypeSet::iterator
8280 Ptr = CandidateTypes[1].pointer_begin(),
8281 PtrEnd = CandidateTypes[1].pointer_end();
8282 Ptr != PtrEnd; ++Ptr) {
8283 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8284 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008285 if (!PointeeType->isObjectType())
8286 continue;
8287
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008288 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8289
8290 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008291 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008292 }
8293 }
8294
8295 // C++ [over.built]p11:
8296 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8297 // C1 is the same type as C2 or is a derived class of C2, T is an object
8298 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8299 // there exist candidate operator functions of the form
8300 //
8301 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8302 //
8303 // where CV12 is the union of CV1 and CV2.
8304 void addArrowStarOverloads() {
8305 for (BuiltinCandidateTypeSet::iterator
8306 Ptr = CandidateTypes[0].pointer_begin(),
8307 PtrEnd = CandidateTypes[0].pointer_end();
8308 Ptr != PtrEnd; ++Ptr) {
8309 QualType C1Ty = (*Ptr);
8310 QualType C1;
8311 QualifierCollector Q1;
8312 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8313 if (!isa<RecordType>(C1))
8314 continue;
8315 // heuristic to reduce number of builtin candidates in the set.
8316 // Add volatile/restrict version only if there are conversions to a
8317 // volatile/restrict type.
8318 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8319 continue;
8320 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8321 continue;
8322 for (BuiltinCandidateTypeSet::iterator
8323 MemPtr = CandidateTypes[1].member_pointer_begin(),
8324 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8325 MemPtr != MemPtrEnd; ++MemPtr) {
8326 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8327 QualType C2 = QualType(mptr->getClass(), 0);
8328 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008329 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008330 break;
8331 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8332 // build CV12 T&
8333 QualType T = mptr->getPointeeType();
8334 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8335 T.isVolatileQualified())
8336 continue;
8337 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8338 T.isRestrictQualified())
8339 continue;
8340 T = Q1.apply(S.Context, T);
8341 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008342 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008343 }
8344 }
8345 }
8346
8347 // Note that we don't consider the first argument, since it has been
8348 // contextually converted to bool long ago. The candidates below are
8349 // therefore added as binary.
8350 //
8351 // C++ [over.built]p25:
8352 // For every type T, where T is a pointer, pointer-to-member, or scoped
8353 // enumeration type, there exist candidate operator functions of the form
8354 //
8355 // T operator?(bool, T, T);
8356 //
8357 void addConditionalOperatorOverloads() {
8358 /// Set of (canonical) types that we've already handled.
8359 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8360
8361 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8362 for (BuiltinCandidateTypeSet::iterator
8363 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8364 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8365 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008366 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008367 continue;
8368
8369 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008370 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008371 }
8372
8373 for (BuiltinCandidateTypeSet::iterator
8374 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8375 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8376 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008377 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008378 continue;
8379
8380 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008381 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008382 }
8383
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008384 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008385 for (BuiltinCandidateTypeSet::iterator
8386 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8387 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8388 Enum != EnumEnd; ++Enum) {
8389 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8390 continue;
8391
David Blaikie82e95a32014-11-19 07:49:47 +00008392 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008393 continue;
8394
8395 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008396 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008397 }
8398 }
8399 }
8400 }
8401};
8402
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008403} // end anonymous namespace
8404
8405/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8406/// operator overloads to the candidate set (C++ [over.built]), based
8407/// on the operator @p Op and the arguments given. For example, if the
8408/// operator is a binary '+', this routine might add "int
8409/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008410void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8411 SourceLocation OpLoc,
8412 ArrayRef<Expr *> Args,
8413 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008414 // Find all of the types that the arguments can convert to, but only
8415 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008416 // that make use of these types. Also record whether we encounter non-record
8417 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008418 Qualifiers VisibleTypeConversionsQuals;
8419 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008420 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008421 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008422
8423 bool HasNonRecordCandidateType = false;
8424 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008425 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008426 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008427 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008428 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8429 OpLoc,
8430 true,
8431 (Op == OO_Exclaim ||
8432 Op == OO_AmpAmp ||
8433 Op == OO_PipePipe),
8434 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008435 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8436 CandidateTypes[ArgIdx].hasNonRecordTypes();
8437 HasArithmeticOrEnumeralCandidateType =
8438 HasArithmeticOrEnumeralCandidateType ||
8439 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008440 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008441
Chandler Carruth00a38332010-12-13 01:44:01 +00008442 // Exit early when no non-record types have been added to the candidate set
8443 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008444 //
8445 // We can't exit early for !, ||, or &&, since there we have always have
8446 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008447 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008448 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008449 return;
8450
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008451 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008452 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008453 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008454 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008455 CandidateTypes, CandidateSet);
8456
8457 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008458 switch (Op) {
8459 case OO_None:
8460 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008461 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008462
Chandler Carruth5184de02010-12-12 08:51:33 +00008463 case OO_New:
8464 case OO_Delete:
8465 case OO_Array_New:
8466 case OO_Array_Delete:
8467 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008468 llvm_unreachable(
8469 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008470
8471 case OO_Comma:
8472 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008473 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008474 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008475 // -- For the operator ',', the unary operator '&', the
8476 // operator '->', or the operator 'co_await', the
8477 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008478 break;
8479
8480 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008481 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008482 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008483 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008484
8485 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008486 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008487 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008488 } else {
8489 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8490 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8491 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008492 break;
8493
Chandler Carruth5184de02010-12-12 08:51:33 +00008494 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008495 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008496 OpBuilder.addUnaryStarPointerOverloads();
8497 else
8498 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8499 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008500
Chandler Carruth5184de02010-12-12 08:51:33 +00008501 case OO_Slash:
8502 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008503 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008504
8505 case OO_PlusPlus:
8506 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008507 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8508 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008509 break;
8510
Douglas Gregor84605ae2009-08-24 13:43:27 +00008511 case OO_EqualEqual:
8512 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008513 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008514 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008515
Douglas Gregora11693b2008-11-12 17:17:38 +00008516 case OO_Less:
8517 case OO_Greater:
8518 case OO_LessEqual:
8519 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008520 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008521 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8522 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008523
Douglas Gregora11693b2008-11-12 17:17:38 +00008524 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008525 case OO_Caret:
8526 case OO_Pipe:
8527 case OO_LessLess:
8528 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008529 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008530 break;
8531
Chandler Carruth5184de02010-12-12 08:51:33 +00008532 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008533 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008534 // C++ [over.match.oper]p3:
8535 // -- For the operator ',', the unary operator '&', or the
8536 // operator '->', the built-in candidates set is empty.
8537 break;
8538
8539 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8540 break;
8541
8542 case OO_Tilde:
8543 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8544 break;
8545
Douglas Gregora11693b2008-11-12 17:17:38 +00008546 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008547 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008548 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008549
8550 case OO_PlusEqual:
8551 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008552 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008553 // Fall through.
8554
8555 case OO_StarEqual:
8556 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008557 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008558 break;
8559
8560 case OO_PercentEqual:
8561 case OO_LessLessEqual:
8562 case OO_GreaterGreaterEqual:
8563 case OO_AmpEqual:
8564 case OO_CaretEqual:
8565 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008566 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008567 break;
8568
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008569 case OO_Exclaim:
8570 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008571 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008572
Douglas Gregora11693b2008-11-12 17:17:38 +00008573 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008574 case OO_PipePipe:
8575 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008576 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008577
8578 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008579 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008580 break;
8581
8582 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008583 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008584 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008585
8586 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008587 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008588 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8589 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008590 }
8591}
8592
Douglas Gregore254f902009-02-04 00:32:51 +00008593/// \brief Add function candidates found via argument-dependent lookup
8594/// to the set of overloading candidates.
8595///
8596/// This routine performs argument-dependent name lookup based on the
8597/// given function name (which may also be an operator name) and adds
8598/// all of the overload candidates found by ADL to the overload
8599/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008600void
Douglas Gregore254f902009-02-04 00:32:51 +00008601Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008602 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008603 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008604 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008605 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008606 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008607 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008608
John McCall91f61fc2010-01-26 06:04:06 +00008609 // FIXME: This approach for uniquing ADL results (and removing
8610 // redundant candidates from the set) relies on pointer-equality,
8611 // which means we need to key off the canonical decl. However,
8612 // always going back to the canonical decl might not get us the
8613 // right set of default arguments. What default arguments are
8614 // we supposed to consider on ADL candidates, anyway?
8615
Douglas Gregorcabea402009-09-22 15:41:20 +00008616 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008617 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008618
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008619 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008620 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8621 CandEnd = CandidateSet.end();
8622 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008623 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008624 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008625 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008626 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008627 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008628
8629 // For each of the ADL candidates we found, add it to the overload
8630 // set.
John McCall8fe68082010-01-26 07:16:45 +00008631 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008632 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008633 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008634 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008635 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008636
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008637 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8638 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008639 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008640 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008641 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008642 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008643 }
Douglas Gregore254f902009-02-04 00:32:51 +00008644}
8645
George Burgess IV3dc166912016-05-10 01:59:34 +00008646namespace {
8647enum class Comparison { Equal, Better, Worse };
8648}
8649
8650/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8651/// overload resolution.
8652///
8653/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8654/// Cand1's first N enable_if attributes have precisely the same conditions as
8655/// Cand2's first N enable_if attributes (where N = the number of enable_if
8656/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8657///
8658/// Note that you can have a pair of candidates such that Cand1's enable_if
8659/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8660/// worse than Cand1's.
8661static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8662 const FunctionDecl *Cand2) {
8663 // Common case: One (or both) decls don't have enable_if attrs.
8664 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8665 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8666 if (!Cand1Attr || !Cand2Attr) {
8667 if (Cand1Attr == Cand2Attr)
8668 return Comparison::Equal;
8669 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8670 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008671
8672 // FIXME: The next several lines are just
8673 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8674 // instead of reverse order which is how they're stored in the AST.
8675 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8676 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8677
George Burgess IV3dc166912016-05-10 01:59:34 +00008678 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8679 // has fewer enable_if attributes than Cand2.
8680 if (Cand1Attrs.size() < Cand2Attrs.size())
8681 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008682
8683 auto Cand1I = Cand1Attrs.begin();
8684 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8685 for (auto &Cand2A : Cand2Attrs) {
8686 Cand1ID.clear();
8687 Cand2ID.clear();
8688
8689 auto &Cand1A = *Cand1I++;
8690 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8691 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8692 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008693 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008694 }
8695
George Burgess IV3dc166912016-05-10 01:59:34 +00008696 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008697}
8698
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008699/// isBetterOverloadCandidate - Determines whether the first overload
8700/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008701bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8702 const OverloadCandidate &Cand2,
8703 SourceLocation Loc,
8704 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008705 // Define viable functions to be better candidates than non-viable
8706 // functions.
8707 if (!Cand2.Viable)
8708 return Cand1.Viable;
8709 else if (!Cand1.Viable)
8710 return false;
8711
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008712 // C++ [over.match.best]p1:
8713 //
8714 // -- if F is a static member function, ICS1(F) is defined such
8715 // that ICS1(F) is neither better nor worse than ICS1(G) for
8716 // any function G, and, symmetrically, ICS1(G) is neither
8717 // better nor worse than ICS1(F).
8718 unsigned StartArg = 0;
8719 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8720 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008721
George Burgess IVfbad5b22016-09-07 20:03:19 +00008722 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8723 // We don't allow incompatible pointer conversions in C++.
8724 if (!S.getLangOpts().CPlusPlus)
8725 return ICS.isStandard() &&
8726 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8727
8728 // The only ill-formed conversion we allow in C++ is the string literal to
8729 // char* conversion, which is only considered ill-formed after C++11.
8730 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8731 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8732 };
8733
8734 // Define functions that don't require ill-formed conversions for a given
8735 // argument to be better candidates than functions that do.
Renato Golindad96d62017-01-02 11:15:42 +00008736 unsigned NumArgs = Cand1.NumConversions;
8737 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008738 bool HasBetterConversion = false;
8739 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8740 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8741 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8742 if (Cand1Bad != Cand2Bad) {
8743 if (Cand1Bad)
8744 return false;
8745 HasBetterConversion = true;
8746 }
8747 }
8748
8749 if (HasBetterConversion)
8750 return true;
8751
Douglas Gregord3cb3562009-07-07 23:38:56 +00008752 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008753 // A viable function F1 is defined to be a better function than another
8754 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008755 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008756 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008757 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008758 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008759 Cand2.Conversions[ArgIdx])) {
8760 case ImplicitConversionSequence::Better:
8761 // Cand1 has a better conversion sequence.
8762 HasBetterConversion = true;
8763 break;
8764
8765 case ImplicitConversionSequence::Worse:
8766 // Cand1 can't be better than Cand2.
8767 return false;
8768
8769 case ImplicitConversionSequence::Indistinguishable:
8770 // Do nothing.
8771 break;
8772 }
8773 }
8774
Mike Stump11289f42009-09-09 15:08:12 +00008775 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008776 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008777 if (HasBetterConversion)
8778 return true;
8779
Douglas Gregora1f013e2008-11-07 22:36:19 +00008780 // -- the context is an initialization by user-defined conversion
8781 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8782 // from the return type of F1 to the destination type (i.e.,
8783 // the type of the entity being initialized) is a better
8784 // conversion sequence than the standard conversion sequence
8785 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008786 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008787 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008788 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008789 // First check whether we prefer one of the conversion functions over the
8790 // other. This only distinguishes the results in non-standard, extension
8791 // cases such as the conversion from a lambda closure type to a function
8792 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008793 ImplicitConversionSequence::CompareKind Result =
8794 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8795 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008796 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008797 Cand1.FinalConversion,
8798 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008799
Richard Smithec2748a2014-05-17 04:36:39 +00008800 if (Result != ImplicitConversionSequence::Indistinguishable)
8801 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008802
8803 // FIXME: Compare kind of reference binding if conversion functions
8804 // convert to a reference type used in direct reference binding, per
8805 // C++14 [over.match.best]p1 section 2 bullet 3.
8806 }
8807
8808 // -- F1 is a non-template function and F2 is a function template
8809 // specialization, or, if not that,
8810 bool Cand1IsSpecialization = Cand1.Function &&
8811 Cand1.Function->getPrimaryTemplate();
8812 bool Cand2IsSpecialization = Cand2.Function &&
8813 Cand2.Function->getPrimaryTemplate();
8814 if (Cand1IsSpecialization != Cand2IsSpecialization)
8815 return Cand2IsSpecialization;
8816
8817 // -- F1 and F2 are function template specializations, and the function
8818 // template for F1 is more specialized than the template for F2
8819 // according to the partial ordering rules described in 14.5.5.2, or,
8820 // if not that,
8821 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8822 if (FunctionTemplateDecl *BetterTemplate
8823 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8824 Cand2.Function->getPrimaryTemplate(),
8825 Loc,
8826 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8827 : TPOC_Call,
8828 Cand1.ExplicitCallArguments,
8829 Cand2.ExplicitCallArguments))
8830 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008831 }
8832
Richard Smith5179eb72016-06-28 19:03:57 +00008833 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8834 // A derived-class constructor beats an (inherited) base class constructor.
8835 bool Cand1IsInherited =
8836 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8837 bool Cand2IsInherited =
8838 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8839 if (Cand1IsInherited != Cand2IsInherited)
8840 return Cand2IsInherited;
8841 else if (Cand1IsInherited) {
8842 assert(Cand2IsInherited);
8843 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8844 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8845 if (Cand1Class->isDerivedFrom(Cand2Class))
8846 return true;
8847 if (Cand2Class->isDerivedFrom(Cand1Class))
8848 return false;
8849 // Inherited from sibling base classes: still ambiguous.
8850 }
8851
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008852 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008853 if (Cand1.Function && Cand2.Function) {
8854 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8855 if (Cmp != Comparison::Equal)
8856 return Cmp == Comparison::Better;
8857 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008858
Justin Lebar25c4a812016-03-29 16:24:16 +00008859 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008860 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8861 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8862 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8863 }
8864
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008865 bool HasPS1 = Cand1.Function != nullptr &&
8866 functionHasPassObjectSizeParams(Cand1.Function);
8867 bool HasPS2 = Cand2.Function != nullptr &&
8868 functionHasPassObjectSizeParams(Cand2.Function);
8869 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008870}
8871
Richard Smith2dbe4042015-11-04 19:26:32 +00008872/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008873/// name lookup and overload resolution. This applies when the same internal/no
8874/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008875/// the same header). In such a case, we don't consider the declarations to
8876/// declare the same entity, but we also don't want lookups with both
8877/// declarations visible to be ambiguous in some cases (this happens when using
8878/// a modularized libstdc++).
8879bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8880 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008881 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8882 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8883 if (!VA || !VB)
8884 return false;
8885
8886 // The declarations must be declaring the same name as an internal linkage
8887 // entity in different modules.
8888 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8889 VB->getDeclContext()->getRedeclContext()) ||
8890 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8891 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8892 VA->isExternallyVisible() || VB->isExternallyVisible())
8893 return false;
8894
8895 // Check that the declarations appear to be equivalent.
8896 //
8897 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8898 // For constants and functions, we should check the initializer or body is
8899 // the same. For non-constant variables, we shouldn't allow it at all.
8900 if (Context.hasSameType(VA->getType(), VB->getType()))
8901 return true;
8902
8903 // Enum constants within unnamed enumerations will have different types, but
8904 // may still be similar enough to be interchangeable for our purposes.
8905 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8906 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8907 // Only handle anonymous enums. If the enumerations were named and
8908 // equivalent, they would have been merged to the same type.
8909 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8910 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8911 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8912 !Context.hasSameType(EnumA->getIntegerType(),
8913 EnumB->getIntegerType()))
8914 return false;
8915 // Allow this only if the value is the same for both enumerators.
8916 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8917 }
8918 }
8919
8920 // Nothing else is sufficiently similar.
8921 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008922}
8923
8924void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8925 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8926 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8927
8928 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8929 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8930 << !M << (M ? M->getFullModuleName() : "");
8931
8932 for (auto *E : Equiv) {
8933 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8934 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8935 << !M << (M ? M->getFullModuleName() : "");
8936 }
Richard Smith896c66e2015-10-21 07:13:52 +00008937}
8938
Mike Stump11289f42009-09-09 15:08:12 +00008939/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008940/// within an overload candidate set.
8941///
James Dennettffad8b72012-06-22 08:10:18 +00008942/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008943/// which overload resolution occurs.
8944///
James Dennettffad8b72012-06-22 08:10:18 +00008945/// \param Best If overload resolution was successful or found a deleted
8946/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008947///
8948/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008949OverloadingResult
8950OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008951 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008952 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008953 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8954 std::transform(begin(), end(), std::back_inserter(Candidates),
8955 [](OverloadCandidate &Cand) { return &Cand; });
8956
Justin Lebar66a2ab92016-08-10 00:40:43 +00008957 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8958 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008959 // compilation mode only one call variant is viable. We need to
8960 // exclude non-viable overload candidates from consideration based
8961 // only on their host/device attributes. Specifically, if one
8962 // candidate call is WrongSide and the other is SameSide, we ignore
8963 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008964 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008965 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8966 bool ContainsSameSideCandidate =
8967 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8968 return Cand->Function &&
8969 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8970 Sema::CFP_SameSide;
8971 });
8972 if (ContainsSameSideCandidate) {
8973 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8974 return Cand->Function &&
8975 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8976 Sema::CFP_WrongSide;
8977 };
George Burgess IV8684b032017-01-04 19:16:29 +00008978 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00008979 }
8980 }
8981
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008982 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008983 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008984 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008985 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008986 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008987 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008988 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008989
8990 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008991 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008992 return OR_No_Viable_Function;
8993
Richard Smith2dbe4042015-11-04 19:26:32 +00008994 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008995
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008996 // Make sure that this function is better than every other viable
8997 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008998 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008999 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009000 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009001 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009002 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009003 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9004 Cand->Function)) {
9005 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009006 continue;
9007 }
9008
John McCall5c32be02010-08-24 20:38:10 +00009009 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009010 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009011 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009012 }
Mike Stump11289f42009-09-09 15:08:12 +00009013
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009014 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009015 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009016 (Best->Function->isDeleted() ||
9017 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009018 return OR_Deleted;
9019
Richard Smith2dbe4042015-11-04 19:26:32 +00009020 if (!EquivalentCands.empty())
9021 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9022 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009023
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009024 return OR_Success;
9025}
9026
John McCall53262c92010-01-12 02:15:36 +00009027namespace {
9028
9029enum OverloadCandidateKind {
9030 oc_function,
9031 oc_method,
9032 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009033 oc_function_template,
9034 oc_method_template,
9035 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009036 oc_implicit_default_constructor,
9037 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009038 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009039 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009040 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009041 oc_inherited_constructor,
9042 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009043};
9044
George Burgess IVd66d37c2016-10-28 21:42:06 +00009045static OverloadCandidateKind
9046ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9047 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009048 bool isTemplate = false;
9049
9050 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9051 isTemplate = true;
9052 Description = S.getTemplateArgumentBindingsText(
9053 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9054 }
John McCallfd0b2f82010-01-06 09:43:14 +00009055
9056 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009057 if (!Ctor->isImplicit()) {
9058 if (isa<ConstructorUsingShadowDecl>(Found))
9059 return isTemplate ? oc_inherited_constructor_template
9060 : oc_inherited_constructor;
9061 else
9062 return isTemplate ? oc_constructor_template : oc_constructor;
9063 }
Sebastian Redl08905022011-02-05 19:23:19 +00009064
Alexis Hunt119c10e2011-05-25 23:16:36 +00009065 if (Ctor->isDefaultConstructor())
9066 return oc_implicit_default_constructor;
9067
9068 if (Ctor->isMoveConstructor())
9069 return oc_implicit_move_constructor;
9070
9071 assert(Ctor->isCopyConstructor() &&
9072 "unexpected sort of implicit constructor");
9073 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009074 }
9075
9076 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9077 // This actually gets spelled 'candidate function' for now, but
9078 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009079 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009080 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009081
Alexis Hunt119c10e2011-05-25 23:16:36 +00009082 if (Meth->isMoveAssignmentOperator())
9083 return oc_implicit_move_assignment;
9084
Douglas Gregor12695102012-02-10 08:36:38 +00009085 if (Meth->isCopyAssignmentOperator())
9086 return oc_implicit_copy_assignment;
9087
9088 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9089 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009090 }
9091
John McCalle1ac8d12010-01-13 00:25:19 +00009092 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009093}
9094
Richard Smith5179eb72016-06-28 19:03:57 +00009095void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9096 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9097 // set.
9098 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9099 S.Diag(FoundDecl->getLocation(),
9100 diag::note_ovl_candidate_inherited_constructor)
9101 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009102}
9103
John McCall53262c92010-01-12 02:15:36 +00009104} // end anonymous namespace
9105
George Burgess IV5f21c712015-10-12 19:57:04 +00009106static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9107 const FunctionDecl *FD) {
9108 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9109 bool AlwaysTrue;
9110 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9111 return false;
9112 if (!AlwaysTrue)
9113 return false;
9114 }
9115 return true;
9116}
9117
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009118/// \brief Returns true if we can take the address of the function.
9119///
9120/// \param Complain - If true, we'll emit a diagnostic
9121/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9122/// we in overload resolution?
9123/// \param Loc - The location of the statement we're complaining about. Ignored
9124/// if we're not complaining, or if we're in overload resolution.
9125static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9126 bool Complain,
9127 bool InOverloadResolution,
9128 SourceLocation Loc) {
9129 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9130 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009131 if (InOverloadResolution)
9132 S.Diag(FD->getLocStart(),
9133 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9134 else
9135 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9136 }
9137 return false;
9138 }
9139
George Burgess IV21081362016-07-24 23:12:40 +00009140 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9141 return P->hasAttr<PassObjectSizeAttr>();
9142 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009143 if (I == FD->param_end())
9144 return true;
9145
9146 if (Complain) {
9147 // Add one to ParamNo because it's user-facing
9148 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9149 if (InOverloadResolution)
9150 S.Diag(FD->getLocation(),
9151 diag::note_ovl_candidate_has_pass_object_size_params)
9152 << ParamNo;
9153 else
9154 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9155 << FD << ParamNo;
9156 }
9157 return false;
9158}
9159
9160static bool checkAddressOfCandidateIsAvailable(Sema &S,
9161 const FunctionDecl *FD) {
9162 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9163 /*InOverloadResolution=*/true,
9164 /*Loc=*/SourceLocation());
9165}
9166
9167bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9168 bool Complain,
9169 SourceLocation Loc) {
9170 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9171 /*InOverloadResolution=*/false,
9172 Loc);
9173}
9174
John McCall53262c92010-01-12 02:15:36 +00009175// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009176void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9177 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009178 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9179 return;
9180
John McCalle1ac8d12010-01-13 00:25:19 +00009181 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009182 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009183 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009184 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009185
9186 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009187 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009188 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009189}
9190
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009191// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009192// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009193void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9194 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009195 assert(OverloadedExpr->getType() == Context.OverloadTy);
9196
9197 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9198 OverloadExpr *OvlExpr = Ovl.Expression;
9199
9200 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9201 IEnd = OvlExpr->decls_end();
9202 I != IEnd; ++I) {
9203 if (FunctionTemplateDecl *FunTmpl =
9204 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009205 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009206 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009207 } else if (FunctionDecl *Fun
9208 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009209 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009210 }
9211 }
9212}
9213
John McCall0d1da222010-01-12 00:44:57 +00009214/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9215/// "lead" diagnostic; it will be given two arguments, the source and
9216/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009217void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9218 Sema &S,
9219 SourceLocation CaretLoc,
9220 const PartialDiagnostic &PDiag) const {
9221 S.Diag(CaretLoc, PDiag)
9222 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009223 // FIXME: The note limiting machinery is borrowed from
9224 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9225 // refactoring here.
9226 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9227 unsigned CandsShown = 0;
9228 AmbiguousConversionSequence::const_iterator I, E;
9229 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9230 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9231 break;
9232 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009233 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009234 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009235 if (I != E)
9236 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009237}
9238
Richard Smith17c00b42014-11-12 01:24:00 +00009239static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009240 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009241 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9242 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009243 assert(Cand->Function && "for now, candidate must be a function");
9244 FunctionDecl *Fn = Cand->Function;
9245
9246 // There's a conversion slot for the object argument if this is a
9247 // non-constructor method. Note that 'I' corresponds the
9248 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009249 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009250 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009251 if (I == 0)
9252 isObjectArgument = true;
9253 else
9254 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009255 }
9256
John McCalle1ac8d12010-01-13 00:25:19 +00009257 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009258 OverloadCandidateKind FnKind =
9259 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009260
John McCall6a61b522010-01-13 09:16:55 +00009261 Expr *FromExpr = Conv.Bad.FromExpr;
9262 QualType FromTy = Conv.Bad.getFromType();
9263 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009264
John McCallfb7ad0f2010-02-02 02:42:52 +00009265 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009266 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009267 Expr *E = FromExpr->IgnoreParens();
9268 if (isa<UnaryOperator>(E))
9269 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009270 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009271
9272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9273 << (unsigned) FnKind << FnDesc
9274 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9275 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009276 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009277 return;
9278 }
9279
John McCall6d174642010-01-23 08:10:49 +00009280 // Do some hand-waving analysis to see if the non-viability is due
9281 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009282 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9283 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9284 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9285 CToTy = RT->getPointeeType();
9286 else {
9287 // TODO: detect and diagnose the full richness of const mismatches.
9288 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009289 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9290 CFromTy = FromPT->getPointeeType();
9291 CToTy = ToPT->getPointeeType();
9292 }
John McCall47000992010-01-14 03:28:57 +00009293 }
9294
9295 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9296 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009297 Qualifiers FromQs = CFromTy.getQualifiers();
9298 Qualifiers ToQs = CToTy.getQualifiers();
9299
9300 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9302 << (unsigned) FnKind << FnDesc
9303 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9304 << FromTy
9305 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9306 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009307 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009308 return;
9309 }
9310
John McCall31168b02011-06-15 23:02:42 +00009311 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009313 << (unsigned) FnKind << FnDesc
9314 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9315 << FromTy
9316 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9317 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009318 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009319 return;
9320 }
9321
Douglas Gregoraec25842011-04-26 23:16:46 +00009322 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9323 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9324 << (unsigned) FnKind << FnDesc
9325 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9326 << FromTy
9327 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9328 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009329 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009330 return;
9331 }
9332
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009333 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9335 << (unsigned) FnKind << FnDesc
9336 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9337 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009338 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009339 return;
9340 }
9341
John McCall47000992010-01-14 03:28:57 +00009342 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9343 assert(CVR && "unexpected qualifiers mismatch");
9344
9345 if (isObjectArgument) {
9346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9347 << (unsigned) FnKind << FnDesc
9348 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9349 << FromTy << (CVR - 1);
9350 } else {
9351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9352 << (unsigned) FnKind << FnDesc
9353 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9354 << FromTy << (CVR - 1) << I+1;
9355 }
Richard Smith5179eb72016-06-28 19:03:57 +00009356 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009357 return;
9358 }
9359
Sebastian Redla72462c2011-09-24 17:48:32 +00009360 // Special diagnostic for failure to convert an initializer list, since
9361 // telling the user that it has type void is not useful.
9362 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9364 << (unsigned) FnKind << FnDesc
9365 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9366 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009367 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009368 return;
9369 }
9370
John McCall6d174642010-01-23 08:10:49 +00009371 // Diagnose references or pointers to incomplete types differently,
9372 // since it's far from impossible that the incompleteness triggered
9373 // the failure.
9374 QualType TempFromTy = FromTy.getNonReferenceType();
9375 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9376 TempFromTy = PTy->getPointeeType();
9377 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009378 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009379 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9380 << (unsigned) FnKind << FnDesc
9381 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009382 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9383 << (unsigned) (Cand->Fix.Kind);
9384
Richard Smith5179eb72016-06-28 19:03:57 +00009385 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009386 return;
9387 }
9388
Douglas Gregor56f2e342010-06-30 23:01:39 +00009389 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009390 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009391 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9392 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9393 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9394 FromPtrTy->getPointeeType()) &&
9395 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9396 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009397 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009398 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009399 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009400 }
9401 } else if (const ObjCObjectPointerType *FromPtrTy
9402 = FromTy->getAs<ObjCObjectPointerType>()) {
9403 if (const ObjCObjectPointerType *ToPtrTy
9404 = ToTy->getAs<ObjCObjectPointerType>())
9405 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9406 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9407 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9408 FromPtrTy->getPointeeType()) &&
9409 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009410 BaseToDerivedConversion = 2;
9411 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009412 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9413 !FromTy->isIncompleteType() &&
9414 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009415 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009416 BaseToDerivedConversion = 3;
9417 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9418 ToTy.getNonReferenceType().getCanonicalType() ==
9419 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009420 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9421 << (unsigned) FnKind << FnDesc
9422 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9423 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009424 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009425 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009426 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009428
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009429 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009430 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009431 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009432 << (unsigned) FnKind << FnDesc
9433 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009434 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009435 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009436 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009437 return;
9438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009439
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009440 if (isa<ObjCObjectPointerType>(CFromTy) &&
9441 isa<PointerType>(CToTy)) {
9442 Qualifiers FromQs = CFromTy.getQualifiers();
9443 Qualifiers ToQs = CToTy.getQualifiers();
9444 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9445 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9446 << (unsigned) FnKind << FnDesc
9447 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9448 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009449 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009450 return;
9451 }
9452 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009453
9454 if (TakingCandidateAddress &&
9455 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9456 return;
9457
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009458 // Emit the generic diagnostic and, optionally, add the hints to it.
9459 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9460 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009461 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009462 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9463 << (unsigned) (Cand->Fix.Kind);
9464
9465 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009466 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9467 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009468 FDiag << *HI;
9469 S.Diag(Fn->getLocation(), FDiag);
9470
Richard Smith5179eb72016-06-28 19:03:57 +00009471 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009472}
9473
Larisse Voufo98b20f12013-07-19 23:00:19 +00009474/// Additional arity mismatch diagnosis specific to a function overload
9475/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9476/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009477static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9478 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009479 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009480 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009481
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009482 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009483 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009484 // right number of arguments, because only overloaded operators have
9485 // the weird behavior of overloading member and non-member functions.
9486 // Just don't report anything.
9487 if (Fn->isInvalidDecl() &&
9488 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009489 return true;
9490
9491 if (NumArgs < MinParams) {
9492 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9493 (Cand->FailureKind == ovl_fail_bad_deduction &&
9494 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9495 } else {
9496 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9497 (Cand->FailureKind == ovl_fail_bad_deduction &&
9498 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9499 }
9500
9501 return false;
9502}
9503
9504/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009505static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9506 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009507 assert(isa<FunctionDecl>(D) &&
9508 "The templated declaration should at least be a function"
9509 " when diagnosing bad template argument deduction due to too many"
9510 " or too few arguments");
9511
9512 FunctionDecl *Fn = cast<FunctionDecl>(D);
9513
9514 // TODO: treat calls to a missing default constructor as a special case
9515 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9516 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009517
John McCall6a61b522010-01-13 09:16:55 +00009518 // at least / at most / exactly
9519 unsigned mode, modeCount;
9520 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009521 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9522 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009523 mode = 0; // "at least"
9524 else
9525 mode = 2; // "exactly"
9526 modeCount = MinParams;
9527 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009528 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009529 mode = 1; // "at most"
9530 else
9531 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009532 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009533 }
9534
9535 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009536 OverloadCandidateKind FnKind =
9537 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009538
Richard Smith10ff50d2012-05-11 05:16:41 +00009539 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9540 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009541 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9542 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009543 else
9544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009545 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9546 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009547 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009548}
9549
Larisse Voufo98b20f12013-07-19 23:00:19 +00009550/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009551static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9552 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009553 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009554 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009555}
Larisse Voufo47c08452013-07-19 22:53:23 +00009556
Richard Smith17c00b42014-11-12 01:24:00 +00009557static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009558 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9559 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009560 llvm_unreachable("Unsupported: Getting the described template declaration"
9561 " for bad deduction diagnosis");
9562}
9563
9564/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009565static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009566 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009567 unsigned NumArgs,
9568 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009569 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009570 NamedDecl *ParamD;
9571 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9572 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9573 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009574 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009575 case Sema::TDK_Success:
9576 llvm_unreachable("TDK_success while diagnosing bad deduction");
9577
9578 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009579 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009580 S.Diag(Templated->getLocation(),
9581 diag::note_ovl_candidate_incomplete_deduction)
9582 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009583 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009584 return;
9585 }
9586
John McCall42d7d192010-08-05 09:05:08 +00009587 case Sema::TDK_Underqualified: {
9588 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9589 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9590
Larisse Voufo98b20f12013-07-19 23:00:19 +00009591 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009592
9593 // Param will have been canonicalized, but it should just be a
9594 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009595 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009596 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009597 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009598 assert(S.Context.hasSameType(Param, NonCanonParam));
9599
9600 // Arg has also been canonicalized, but there's nothing we can do
9601 // about that. It also doesn't matter as much, because it won't
9602 // have any template parameters in it (because deduction isn't
9603 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009604 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009605
Larisse Voufo98b20f12013-07-19 23:00:19 +00009606 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9607 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009608 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009609 return;
9610 }
9611
9612 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009613 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009614 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009615 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009616 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009617 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9618 // Deduction might have failed because we deduced arguments of two
9619 // different types for a non-type template parameter.
9620 // FIXME: Use a different TDK value for this.
9621 QualType T1 =
9622 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9623 QualType T2 =
9624 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9625 if (!S.Context.hasSameType(T1, T2)) {
9626 S.Diag(Templated->getLocation(),
9627 diag::note_ovl_candidate_inconsistent_deduction_types)
9628 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9629 << *DeductionFailure.getSecondArg() << T2;
9630 MaybeEmitInheritedConstructorNote(S, Found);
9631 return;
9632 }
9633
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009634 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009635 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009636 which = 2;
9637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009638
Larisse Voufo98b20f12013-07-19 23:00:19 +00009639 S.Diag(Templated->getLocation(),
9640 diag::note_ovl_candidate_inconsistent_deduction)
9641 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9642 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009643 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009644 return;
9645 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009646
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009647 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009648 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009649 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009650 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009651 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009652 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009653 else {
9654 int index = 0;
9655 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9656 index = TTP->getIndex();
9657 else if (NonTypeTemplateParmDecl *NTTP
9658 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9659 index = NTTP->getIndex();
9660 else
9661 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009662 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009663 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009664 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009665 }
Richard Smith5179eb72016-06-28 19:03:57 +00009666 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009667 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009668
Douglas Gregor02eb4832010-05-08 18:13:28 +00009669 case Sema::TDK_TooManyArguments:
9670 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009671 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009672 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009673
9674 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009675 S.Diag(Templated->getLocation(),
9676 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009677 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009678 return;
9679
9680 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009681 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009682 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009683 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009684 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009685 TemplateArgString = " ";
9686 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009687 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009688 }
9689
Richard Smith6f8d2c62012-05-09 05:17:00 +00009690 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009691 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009692 if (PDiag && PDiag->second.getDiagID() ==
9693 diag::err_typename_nested_not_found_enable_if) {
9694 // FIXME: Use the source range of the condition, and the fully-qualified
9695 // name of the enable_if template. These are both present in PDiag.
9696 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9697 << "'enable_if'" << TemplateArgString;
9698 return;
9699 }
9700
Richard Smith9ca64612012-05-07 09:03:25 +00009701 // Format the SFINAE diagnostic into the argument string.
9702 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9703 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009704 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009705 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009706 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009707 SFINAEArgString = ": ";
9708 R = SourceRange(PDiag->first, PDiag->first);
9709 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9710 }
9711
Larisse Voufo98b20f12013-07-19 23:00:19 +00009712 S.Diag(Templated->getLocation(),
9713 diag::note_ovl_candidate_substitution_failure)
9714 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009715 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009716 return;
9717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009718
Richard Smithc92d2062017-01-05 23:02:44 +00009719 case Sema::TDK_DeducedMismatch:
9720 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009721 // Format the template argument list into the argument string.
9722 SmallString<128> TemplateArgString;
9723 if (TemplateArgumentList *Args =
9724 DeductionFailure.getTemplateArgumentList()) {
9725 TemplateArgString = " ";
9726 TemplateArgString += S.getTemplateArgumentBindingsText(
9727 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9728 }
9729
9730 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9731 << (*DeductionFailure.getCallArgIndex() + 1)
9732 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009733 << TemplateArgString
9734 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009735 break;
9736 }
9737
Richard Trieue3732352013-04-08 21:11:40 +00009738 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009739 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009740 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9741 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009742 if (FirstTA.getKind() == TemplateArgument::Template &&
9743 SecondTA.getKind() == TemplateArgument::Template) {
9744 TemplateName FirstTN = FirstTA.getAsTemplate();
9745 TemplateName SecondTN = SecondTA.getAsTemplate();
9746 if (FirstTN.getKind() == TemplateName::Template &&
9747 SecondTN.getKind() == TemplateName::Template) {
9748 if (FirstTN.getAsTemplateDecl()->getName() ==
9749 SecondTN.getAsTemplateDecl()->getName()) {
9750 // FIXME: This fixes a bad diagnostic where both templates are named
9751 // the same. This particular case is a bit difficult since:
9752 // 1) It is passed as a string to the diagnostic printer.
9753 // 2) The diagnostic printer only attempts to find a better
9754 // name for types, not decls.
9755 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009756 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009757 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9758 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9759 return;
9760 }
9761 }
9762 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009763
9764 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9765 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9766 return;
9767
Faisal Vali2b391ab2013-09-26 19:54:12 +00009768 // FIXME: For generic lambda parameters, check if the function is a lambda
9769 // call operator, and if so, emit a prettier and more informative
9770 // diagnostic that mentions 'auto' and lambda in addition to
9771 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009772 S.Diag(Templated->getLocation(),
9773 diag::note_ovl_candidate_non_deduced_mismatch)
9774 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009775 return;
Richard Trieue3732352013-04-08 21:11:40 +00009776 }
John McCall8b9ed552010-02-01 18:53:26 +00009777 // TODO: diagnose these individually, then kill off
9778 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009779 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009780 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009781 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009782 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009783 case Sema::TDK_CUDATargetMismatch:
9784 S.Diag(Templated->getLocation(),
9785 diag::note_cuda_ovl_candidate_target_mismatch);
9786 return;
John McCall8b9ed552010-02-01 18:53:26 +00009787 }
9788}
9789
Larisse Voufo98b20f12013-07-19 23:00:19 +00009790/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009791static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009792 unsigned NumArgs,
9793 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009794 unsigned TDK = Cand->DeductionFailure.Result;
9795 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9796 if (CheckArityMismatch(S, Cand, NumArgs))
9797 return;
9798 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009799 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009800 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009801}
9802
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009803/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009804static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009805 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9806 FunctionDecl *Callee = Cand->Function;
9807
9808 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9809 CalleeTarget = S.IdentifyCUDATarget(Callee);
9810
9811 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009812 OverloadCandidateKind FnKind =
9813 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009814
9815 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009816 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9817
9818 // This could be an implicit constructor for which we could not infer the
9819 // target due to a collsion. Diagnose that case.
9820 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9821 if (Meth != nullptr && Meth->isImplicit()) {
9822 CXXRecordDecl *ParentClass = Meth->getParent();
9823 Sema::CXXSpecialMember CSM;
9824
9825 switch (FnKind) {
9826 default:
9827 return;
9828 case oc_implicit_default_constructor:
9829 CSM = Sema::CXXDefaultConstructor;
9830 break;
9831 case oc_implicit_copy_constructor:
9832 CSM = Sema::CXXCopyConstructor;
9833 break;
9834 case oc_implicit_move_constructor:
9835 CSM = Sema::CXXMoveConstructor;
9836 break;
9837 case oc_implicit_copy_assignment:
9838 CSM = Sema::CXXCopyAssignment;
9839 break;
9840 case oc_implicit_move_assignment:
9841 CSM = Sema::CXXMoveAssignment;
9842 break;
9843 };
9844
9845 bool ConstRHS = false;
9846 if (Meth->getNumParams()) {
9847 if (const ReferenceType *RT =
9848 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9849 ConstRHS = RT->getPointeeType().isConstQualified();
9850 }
9851 }
9852
9853 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9854 /* ConstRHS */ ConstRHS,
9855 /* Diagnose */ true);
9856 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009857}
9858
Richard Smith17c00b42014-11-12 01:24:00 +00009859static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009860 FunctionDecl *Callee = Cand->Function;
9861 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9862
9863 S.Diag(Callee->getLocation(),
9864 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9865 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9866}
9867
Yaxun Liu5b746652016-12-18 05:18:55 +00009868static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
9869 FunctionDecl *Callee = Cand->Function;
9870
9871 S.Diag(Callee->getLocation(),
9872 diag::note_ovl_candidate_disabled_by_extension);
9873}
9874
John McCall8b9ed552010-02-01 18:53:26 +00009875/// Generates a 'note' diagnostic for an overload candidate. We've
9876/// already generated a primary error at the call site.
9877///
9878/// It really does need to be a single diagnostic with its caret
9879/// pointed at the candidate declaration. Yes, this creates some
9880/// major challenges of technical writing. Yes, this makes pointing
9881/// out problems with specific arguments quite awkward. It's still
9882/// better than generating twenty screens of text for every failed
9883/// overload.
9884///
9885/// It would be great to be able to express per-candidate problems
9886/// more richly for those diagnostic clients that cared, but we'd
9887/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009888static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009889 unsigned NumArgs,
9890 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009891 FunctionDecl *Fn = Cand->Function;
9892
John McCall12f97bc2010-01-08 04:41:39 +00009893 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009894 if (Cand->Viable && (Fn->isDeleted() ||
9895 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009896 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009897 OverloadCandidateKind FnKind =
9898 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009899
9900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009901 << FnKind << FnDesc
9902 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009903 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009904 return;
John McCall12f97bc2010-01-08 04:41:39 +00009905 }
9906
John McCalle1ac8d12010-01-13 00:25:19 +00009907 // We don't really have anything else to say about viable candidates.
9908 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009909 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009910 return;
9911 }
John McCall0d1da222010-01-12 00:44:57 +00009912
John McCall6a61b522010-01-13 09:16:55 +00009913 switch (Cand->FailureKind) {
9914 case ovl_fail_too_many_arguments:
9915 case ovl_fail_too_few_arguments:
9916 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009917
John McCall6a61b522010-01-13 09:16:55 +00009918 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009919 return DiagnoseBadDeduction(S, Cand, NumArgs,
9920 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009921
John McCall578a1f82014-12-14 01:46:53 +00009922 case ovl_fail_illegal_constructor: {
9923 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9924 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009925 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009926 return;
9927 }
9928
John McCallfe796dd2010-01-23 05:17:32 +00009929 case ovl_fail_trivial_conversion:
9930 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009931 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009932 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009933
John McCall65eb8792010-02-25 01:37:24 +00009934 case ovl_fail_bad_conversion: {
9935 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Renato Golindad96d62017-01-02 11:15:42 +00009936 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009937 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009938 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009939
John McCall6a61b522010-01-13 09:16:55 +00009940 // FIXME: this currently happens when we're called from SemaInit
9941 // when user-conversion overload fails. Figure out how to handle
9942 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009943 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009944 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009945
9946 case ovl_fail_bad_target:
9947 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009948
9949 case ovl_fail_enable_if:
9950 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009951
Yaxun Liu5b746652016-12-18 05:18:55 +00009952 case ovl_fail_ext_disabled:
9953 return DiagnoseOpenCLExtensionDisabled(S, Cand);
9954
Richard Smithf9c59b72017-01-08 21:45:44 +00009955 case ovl_fail_inhctor_slice:
9956 S.Diag(Fn->getLocation(),
9957 diag::note_ovl_candidate_inherited_constructor_slice);
9958 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9959 return;
9960
George Burgess IV7204ed92016-01-07 02:26:57 +00009961 case ovl_fail_addr_not_available: {
9962 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9963 (void)Available;
9964 assert(!Available);
9965 break;
9966 }
John McCall65eb8792010-02-25 01:37:24 +00009967 }
John McCalld3224162010-01-08 00:58:21 +00009968}
9969
Richard Smith17c00b42014-11-12 01:24:00 +00009970static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009971 // Desugar the type of the surrogate down to a function type,
9972 // retaining as many typedefs as possible while still showing
9973 // the function type (and, therefore, its parameter types).
9974 QualType FnType = Cand->Surrogate->getConversionType();
9975 bool isLValueReference = false;
9976 bool isRValueReference = false;
9977 bool isPointer = false;
9978 if (const LValueReferenceType *FnTypeRef =
9979 FnType->getAs<LValueReferenceType>()) {
9980 FnType = FnTypeRef->getPointeeType();
9981 isLValueReference = true;
9982 } else if (const RValueReferenceType *FnTypeRef =
9983 FnType->getAs<RValueReferenceType>()) {
9984 FnType = FnTypeRef->getPointeeType();
9985 isRValueReference = true;
9986 }
9987 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9988 FnType = FnTypePtr->getPointeeType();
9989 isPointer = true;
9990 }
9991 // Desugar down to a function type.
9992 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9993 // Reconstruct the pointer/reference as appropriate.
9994 if (isPointer) FnType = S.Context.getPointerType(FnType);
9995 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9996 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9997
9998 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9999 << FnType;
10000}
10001
Richard Smith17c00b42014-11-12 01:24:00 +000010002static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10003 SourceLocation OpLoc,
10004 OverloadCandidate *Cand) {
Renato Golindad96d62017-01-02 11:15:42 +000010005 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010006 std::string TypeStr("operator");
10007 TypeStr += Opc;
10008 TypeStr += "(";
10009 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Renato Golindad96d62017-01-02 11:15:42 +000010010 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +000010011 TypeStr += ")";
10012 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10013 } else {
10014 TypeStr += ", ";
10015 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10016 TypeStr += ")";
10017 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10018 }
10019}
10020
Richard Smith17c00b42014-11-12 01:24:00 +000010021static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10022 OverloadCandidate *Cand) {
Renato Golindad96d62017-01-02 11:15:42 +000010023 unsigned NoOperands = Cand->NumConversions;
10024 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
10025 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +000010026 if (ICS.isBad()) break; // all meaningless after first invalid
10027 if (!ICS.isAmbiguous()) continue;
10028
Richard Smithc2bebe92016-05-11 20:37:46 +000010029 ICS.DiagnoseAmbiguousConversion(
10030 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010031 }
10032}
10033
Larisse Voufo98b20f12013-07-19 23:00:19 +000010034static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010035 if (Cand->Function)
10036 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010037 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010038 return Cand->Surrogate->getLocation();
10039 return SourceLocation();
10040}
10041
Larisse Voufo98b20f12013-07-19 23:00:19 +000010042static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010043 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010044 case Sema::TDK_Success:
Renato Golindad96d62017-01-02 11:15:42 +000010045 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010046
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010047 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010048 case Sema::TDK_Incomplete:
10049 return 1;
10050
10051 case Sema::TDK_Underqualified:
10052 case Sema::TDK_Inconsistent:
10053 return 2;
10054
10055 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010056 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010057 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010058 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010059 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010060 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010061 return 3;
10062
10063 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010064 return 4;
10065
10066 case Sema::TDK_InvalidExplicitArguments:
10067 return 5;
10068
10069 case Sema::TDK_TooManyArguments:
10070 case Sema::TDK_TooFewArguments:
10071 return 6;
10072 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010073 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010074}
10075
Richard Smith17c00b42014-11-12 01:24:00 +000010076namespace {
John McCallad2587a2010-01-12 00:48:53 +000010077struct CompareOverloadCandidatesForDisplay {
10078 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010079 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010080 size_t NumArgs;
10081
Richard Smith0f59cb32015-12-18 21:45:41 +000010082 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010083 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010084
10085 bool operator()(const OverloadCandidate *L,
10086 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010087 // Fast-path this check.
10088 if (L == R) return false;
10089
John McCall12f97bc2010-01-08 04:41:39 +000010090 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010091 if (L->Viable) {
10092 if (!R->Viable) return true;
10093
10094 // TODO: introduce a tri-valued comparison for overload
10095 // candidates. Would be more worthwhile if we had a sort
10096 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010097 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10098 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010099 } else if (R->Viable)
10100 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010101
John McCall3712d9e2010-01-15 23:32:50 +000010102 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010103
John McCall3712d9e2010-01-15 23:32:50 +000010104 // Criteria by which we can sort non-viable candidates:
10105 if (!L->Viable) {
10106 // 1. Arity mismatches come after other candidates.
10107 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010108 L->FailureKind == ovl_fail_too_few_arguments) {
10109 if (R->FailureKind == ovl_fail_too_many_arguments ||
10110 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010111 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10112 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10113 if (LDist == RDist) {
10114 if (L->FailureKind == R->FailureKind)
10115 // Sort non-surrogates before surrogates.
10116 return !L->IsSurrogate && R->IsSurrogate;
10117 // Sort candidates requiring fewer parameters than there were
10118 // arguments given after candidates requiring more parameters
10119 // than there were arguments given.
10120 return L->FailureKind == ovl_fail_too_many_arguments;
10121 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010122 return LDist < RDist;
10123 }
John McCall3712d9e2010-01-15 23:32:50 +000010124 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010125 }
John McCall3712d9e2010-01-15 23:32:50 +000010126 if (R->FailureKind == ovl_fail_too_many_arguments ||
10127 R->FailureKind == ovl_fail_too_few_arguments)
10128 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010129
John McCallfe796dd2010-01-23 05:17:32 +000010130 // 2. Bad conversions come first and are ordered by the number
10131 // of bad conversions and quality of good conversions.
10132 if (L->FailureKind == ovl_fail_bad_conversion) {
10133 if (R->FailureKind != ovl_fail_bad_conversion)
10134 return true;
10135
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010136 // The conversion that can be fixed with a smaller number of changes,
10137 // comes first.
10138 unsigned numLFixes = L->Fix.NumConversionsFixed;
10139 unsigned numRFixes = R->Fix.NumConversionsFixed;
10140 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10141 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010142 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010143 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010144 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010145
John McCallfe796dd2010-01-23 05:17:32 +000010146 // If there's any ordering between the defined conversions...
10147 // FIXME: this might not be transitive.
Renato Golindad96d62017-01-02 11:15:42 +000010148 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010149
10150 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010151 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Renato Golindad96d62017-01-02 11:15:42 +000010152 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010153 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010154 L->Conversions[I],
10155 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010156 case ImplicitConversionSequence::Better:
10157 leftBetter++;
10158 break;
10159
10160 case ImplicitConversionSequence::Worse:
10161 leftBetter--;
10162 break;
10163
10164 case ImplicitConversionSequence::Indistinguishable:
10165 break;
10166 }
10167 }
10168 if (leftBetter > 0) return true;
10169 if (leftBetter < 0) return false;
10170
10171 } else if (R->FailureKind == ovl_fail_bad_conversion)
10172 return false;
10173
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010174 if (L->FailureKind == ovl_fail_bad_deduction) {
10175 if (R->FailureKind != ovl_fail_bad_deduction)
10176 return true;
10177
10178 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10179 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010180 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010181 } else if (R->FailureKind == ovl_fail_bad_deduction)
10182 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010183
John McCall3712d9e2010-01-15 23:32:50 +000010184 // TODO: others?
10185 }
10186
10187 // Sort everything else by location.
10188 SourceLocation LLoc = GetLocationForCandidate(L);
10189 SourceLocation RLoc = GetLocationForCandidate(R);
10190
10191 // Put candidates without locations (e.g. builtins) at the end.
10192 if (LLoc.isInvalid()) return false;
10193 if (RLoc.isInvalid()) return true;
10194
10195 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010196 }
10197};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010198}
John McCall12f97bc2010-01-08 04:41:39 +000010199
John McCallfe796dd2010-01-23 05:17:32 +000010200/// CompleteNonViableCandidate - Normally, overload resolution only
Renato Golindad96d62017-01-02 11:15:42 +000010201/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010202static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10203 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010204 assert(!Cand->Viable);
10205
10206 // Don't do anything on failures other than bad conversion.
10207 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10208
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010209 // We only want the FixIts if all the arguments can be corrected.
10210 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010211 // Use a implicit copy initialization to check conversion fixes.
10212 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010213
Renato Golindad96d62017-01-02 11:15:42 +000010214 // Skip forward to the first bad conversion.
10215 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10216 unsigned ConvCount = Cand->NumConversions;
10217 while (true) {
John McCallfe796dd2010-01-23 05:17:32 +000010218 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Renato Golindad96d62017-01-02 11:15:42 +000010219 ConvIdx++;
10220 if (Cand->Conversions[ConvIdx - 1].isBad()) {
10221 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010222 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010223 }
John McCallfe796dd2010-01-23 05:17:32 +000010224 }
10225
Renato Golindad96d62017-01-02 11:15:42 +000010226 if (ConvIdx == ConvCount)
10227 return;
10228
10229 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10230 "remaining conversion is initialized?");
10231
Douglas Gregoradc7a702010-04-16 17:45:54 +000010232 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010233 // operation somehow.
10234 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010235
Renato Golindad96d62017-01-02 11:15:42 +000010236 const FunctionProtoType* Proto;
10237 unsigned ArgIdx = ConvIdx;
John McCallfe796dd2010-01-23 05:17:32 +000010238
10239 if (Cand->IsSurrogate) {
10240 QualType ConvType
10241 = Cand->Surrogate->getConversionType().getNonReferenceType();
10242 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10243 ConvType = ConvPtrType->getPointeeType();
10244 Proto = ConvType->getAs<FunctionProtoType>();
Renato Golindad96d62017-01-02 11:15:42 +000010245 ArgIdx--;
John McCallfe796dd2010-01-23 05:17:32 +000010246 } else if (Cand->Function) {
10247 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10248 if (isa<CXXMethodDecl>(Cand->Function) &&
10249 !isa<CXXConstructorDecl>(Cand->Function))
Renato Golindad96d62017-01-02 11:15:42 +000010250 ArgIdx--;
John McCallfe796dd2010-01-23 05:17:32 +000010251 } else {
10252 // Builtin binary operator with a bad first conversion.
10253 assert(ConvCount <= 3);
Renato Golindad96d62017-01-02 11:15:42 +000010254 for (; ConvIdx != ConvCount; ++ConvIdx)
10255 Cand->Conversions[ConvIdx]
10256 = TryCopyInitialization(S, Args[ConvIdx],
10257 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10258 SuppressUserConversions,
10259 /*InOverloadResolution*/ true,
10260 /*AllowObjCWritebackConversion=*/
10261 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010262 return;
10263 }
10264
10265 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010266 unsigned NumParams = Proto->getNumParams();
Renato Golindad96d62017-01-02 11:15:42 +000010267 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10268 if (ArgIdx < NumParams) {
10269 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10270 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10271 /*InOverloadResolution=*/true,
10272 /*AllowObjCWritebackConversion=*/
10273 S.getLangOpts().ObjCAutoRefCount);
10274 // Store the FixIt in the candidate if it exists.
10275 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10276 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10277 }
10278 else
John McCallfe796dd2010-01-23 05:17:32 +000010279 Cand->Conversions[ConvIdx].setEllipsis();
10280 }
10281}
10282
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010283/// PrintOverloadCandidates - When overload resolution fails, prints
10284/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010285/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010286void OverloadCandidateSet::NoteCandidates(
10287 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10288 StringRef Opc, SourceLocation OpLoc,
10289 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010290 // Sort the candidates by viability and position. Sorting directly would
10291 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010292 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010293 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10294 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010295 if (!Filter(*Cand))
10296 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010297 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010298 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010299 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010300 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010301 if (Cand->Function || Cand->IsSurrogate)
10302 Cands.push_back(Cand);
10303 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10304 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010305 }
10306 }
10307
John McCallad2587a2010-01-12 00:48:53 +000010308 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010309 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010310
John McCall0d1da222010-01-12 00:44:57 +000010311 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010312
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010313 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010314 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010315 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010316 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10317 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010318
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010319 // Set an arbitrary limit on the number of candidate functions we'll spam
10320 // the user with. FIXME: This limit should depend on details of the
10321 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010322 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010323 break;
10324 }
10325 ++CandsShown;
10326
John McCalld3224162010-01-08 00:58:21 +000010327 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010328 NoteFunctionCandidate(S, Cand, Args.size(),
10329 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010330 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010331 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010332 else {
10333 assert(Cand->Viable &&
10334 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010335 // Generally we only see ambiguities including viable builtin
10336 // operators if overload resolution got screwed up by an
10337 // ambiguous user-defined conversion.
10338 //
10339 // FIXME: It's quite possible for different conversions to see
10340 // different ambiguities, though.
10341 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010342 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010343 ReportedAmbiguousConversions = true;
10344 }
John McCalld3224162010-01-08 00:58:21 +000010345
John McCall0d1da222010-01-12 00:44:57 +000010346 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010347 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010348 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010349 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010350
10351 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010352 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010353}
10354
Larisse Voufo98b20f12013-07-19 23:00:19 +000010355static SourceLocation
10356GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10357 return Cand->Specialization ? Cand->Specialization->getLocation()
10358 : SourceLocation();
10359}
10360
Richard Smith17c00b42014-11-12 01:24:00 +000010361namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010362struct CompareTemplateSpecCandidatesForDisplay {
10363 Sema &S;
10364 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10365
10366 bool operator()(const TemplateSpecCandidate *L,
10367 const TemplateSpecCandidate *R) {
10368 // Fast-path this check.
10369 if (L == R)
10370 return false;
10371
10372 // Assuming that both candidates are not matches...
10373
10374 // Sort by the ranking of deduction failures.
10375 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10376 return RankDeductionFailure(L->DeductionFailure) <
10377 RankDeductionFailure(R->DeductionFailure);
10378
10379 // Sort everything else by location.
10380 SourceLocation LLoc = GetLocationForCandidate(L);
10381 SourceLocation RLoc = GetLocationForCandidate(R);
10382
10383 // Put candidates without locations (e.g. builtins) at the end.
10384 if (LLoc.isInvalid())
10385 return false;
10386 if (RLoc.isInvalid())
10387 return true;
10388
10389 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10390 }
10391};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010392}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010393
10394/// Diagnose a template argument deduction failure.
10395/// We are treating these failures as overload failures due to bad
10396/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010397void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10398 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010399 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010400 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010401}
10402
10403void TemplateSpecCandidateSet::destroyCandidates() {
10404 for (iterator i = begin(), e = end(); i != e; ++i) {
10405 i->DeductionFailure.Destroy();
10406 }
10407}
10408
10409void TemplateSpecCandidateSet::clear() {
10410 destroyCandidates();
10411 Candidates.clear();
10412}
10413
10414/// NoteCandidates - When no template specialization match is found, prints
10415/// diagnostic messages containing the non-matching specializations that form
10416/// the candidate set.
10417/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10418/// OCD == OCD_AllCandidates and Cand->Viable == false.
10419void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10420 // Sort the candidates by position (assuming no candidate is a match).
10421 // Sorting directly would be prohibitive, so we make a set of pointers
10422 // and sort those.
10423 SmallVector<TemplateSpecCandidate *, 32> Cands;
10424 Cands.reserve(size());
10425 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10426 if (Cand->Specialization)
10427 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010428 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010429 // in general, want to list every possible builtin candidate.
10430 }
10431
10432 std::sort(Cands.begin(), Cands.end(),
10433 CompareTemplateSpecCandidatesForDisplay(S));
10434
10435 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10436 // for generalization purposes (?).
10437 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10438
10439 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10440 unsigned CandsShown = 0;
10441 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10442 TemplateSpecCandidate *Cand = *I;
10443
10444 // Set an arbitrary limit on the number of candidates we'll spam
10445 // the user with. FIXME: This limit should depend on details of the
10446 // candidate list.
10447 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10448 break;
10449 ++CandsShown;
10450
10451 assert(Cand->Specialization &&
10452 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010453 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010454 }
10455
10456 if (I != E)
10457 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10458}
10459
Douglas Gregorb491ed32011-02-19 21:32:49 +000010460// [PossiblyAFunctionType] --> [Return]
10461// NonFunctionType --> NonFunctionType
10462// R (A) --> R(A)
10463// R (*)(A) --> R (A)
10464// R (&)(A) --> R (A)
10465// R (S::*)(A) --> R (A)
10466QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10467 QualType Ret = PossiblyAFunctionType;
10468 if (const PointerType *ToTypePtr =
10469 PossiblyAFunctionType->getAs<PointerType>())
10470 Ret = ToTypePtr->getPointeeType();
10471 else if (const ReferenceType *ToTypeRef =
10472 PossiblyAFunctionType->getAs<ReferenceType>())
10473 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010474 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010475 PossiblyAFunctionType->getAs<MemberPointerType>())
10476 Ret = MemTypePtr->getPointeeType();
10477 Ret =
10478 Context.getCanonicalType(Ret).getUnqualifiedType();
10479 return Ret;
10480}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010481
Richard Smith9095e5b2016-11-01 01:31:23 +000010482static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10483 bool Complain = true) {
10484 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10485 S.DeduceReturnType(FD, Loc, Complain))
10486 return true;
10487
10488 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10489 if (S.getLangOpts().CPlusPlus1z &&
10490 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10491 !S.ResolveExceptionSpec(Loc, FPT))
10492 return true;
10493
10494 return false;
10495}
10496
Richard Smith17c00b42014-11-12 01:24:00 +000010497namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010498// A helper class to help with address of function resolution
10499// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010500class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010501 Sema& S;
10502 Expr* SourceExpr;
10503 const QualType& TargetType;
10504 QualType TargetFunctionType; // Extracted function type from target type
10505
10506 bool Complain;
10507 //DeclAccessPair& ResultFunctionAccessPair;
10508 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010509
Douglas Gregorb491ed32011-02-19 21:32:49 +000010510 bool TargetTypeIsNonStaticMemberFunction;
10511 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010512 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010513 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010514
Douglas Gregorb491ed32011-02-19 21:32:49 +000010515 OverloadExpr::FindResult OvlExprInfo;
10516 OverloadExpr *OvlExpr;
10517 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010518 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010519 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010520
Douglas Gregorb491ed32011-02-19 21:32:49 +000010521public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010522 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10523 const QualType &TargetType, bool Complain)
10524 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10525 Complain(Complain), Context(S.getASTContext()),
10526 TargetTypeIsNonStaticMemberFunction(
10527 !!TargetType->getAs<MemberPointerType>()),
10528 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010529 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010530 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010531 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10532 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010533 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010534 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010535
David Majnemera4f7c7a2013-08-01 06:13:59 +000010536 if (TargetFunctionType->isFunctionType()) {
10537 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10538 if (!UME->isImplicitAccess() &&
10539 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10540 StaticMemberFunctionFromBoundPointer = true;
10541 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10542 DeclAccessPair dap;
10543 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10544 OvlExpr, false, &dap)) {
10545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10546 if (!Method->isStatic()) {
10547 // If the target type is a non-function type and the function found
10548 // is a non-static member function, pretend as if that was the
10549 // target, it's the only possible type to end up with.
10550 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010551
David Majnemera4f7c7a2013-08-01 06:13:59 +000010552 // And skip adding the function if its not in the proper form.
10553 // We'll diagnose this due to an empty set of functions.
10554 if (!OvlExprInfo.HasFormOfMemberPointer)
10555 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010556 }
10557
David Majnemera4f7c7a2013-08-01 06:13:59 +000010558 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010559 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010560 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010561 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010562
10563 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010564 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010565
Douglas Gregorb491ed32011-02-19 21:32:49 +000010566 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10567 // C++ [over.over]p4:
10568 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010569 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010570 if (FoundNonTemplateFunction)
10571 EliminateAllTemplateMatches();
10572 else
10573 EliminateAllExceptMostSpecializedTemplate();
10574 }
10575 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010576
Justin Lebar25c4a812016-03-29 16:24:16 +000010577 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010578 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010579 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010580
10581 bool hasComplained() const { return HasComplained; }
10582
Douglas Gregorb491ed32011-02-19 21:32:49 +000010583private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010584 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10585 QualType Discard;
10586 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010587 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010588 }
10589
George Burgess IV6da4c202016-03-23 02:33:58 +000010590 /// \return true if A is considered a better overload candidate for the
10591 /// desired type than B.
10592 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10593 // If A doesn't have exactly the correct type, we don't want to classify it
10594 // as "better" than anything else. This way, the user is required to
10595 // disambiguate for us if there are multiple candidates and no exact match.
10596 return candidateHasExactlyCorrectType(A) &&
10597 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010598 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010599 }
10600
10601 /// \return true if we were able to eliminate all but one overload candidate,
10602 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010603 bool eliminiateSuboptimalOverloadCandidates() {
10604 // Same algorithm as overload resolution -- one pass to pick the "best",
10605 // another pass to be sure that nothing is better than the best.
10606 auto Best = Matches.begin();
10607 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10608 if (isBetterCandidate(I->second, Best->second))
10609 Best = I;
10610
10611 const FunctionDecl *BestFn = Best->second;
10612 auto IsBestOrInferiorToBest = [this, BestFn](
10613 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10614 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10615 };
10616
10617 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10618 // option, so we can potentially give the user a better error
10619 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10620 return false;
10621 Matches[0] = *Best;
10622 Matches.resize(1);
10623 return true;
10624 }
10625
Douglas Gregorb491ed32011-02-19 21:32:49 +000010626 bool isTargetTypeAFunction() const {
10627 return TargetFunctionType->isFunctionType();
10628 }
10629
10630 // [ToType] [Return]
10631
10632 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10633 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10634 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10635 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10636 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10637 }
10638
10639 // return true if any matching specializations were found
10640 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10641 const DeclAccessPair& CurAccessFunPair) {
10642 if (CXXMethodDecl *Method
10643 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10644 // Skip non-static function templates when converting to pointer, and
10645 // static when converting to member pointer.
10646 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10647 return false;
10648 }
10649 else if (TargetTypeIsNonStaticMemberFunction)
10650 return false;
10651
10652 // C++ [over.over]p2:
10653 // If the name is a function template, template argument deduction is
10654 // done (14.8.2.2), and if the argument deduction succeeds, the
10655 // resulting template argument list is used to generate a single
10656 // function template specialization, which is added to the set of
10657 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010658 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010659 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010660 if (Sema::TemplateDeductionResult Result
10661 = S.DeduceTemplateArguments(FunctionTemplate,
10662 &OvlExplicitTemplateArgs,
10663 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010664 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010665 // Make a note of the failed deduction for diagnostics.
10666 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010667 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010668 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010669 return false;
10670 }
10671
Douglas Gregor19a41f12013-04-17 08:45:07 +000010672 // Template argument deduction ensures that we have an exact match or
10673 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010674 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010675 assert(S.isSameOrCompatibleFunctionType(
10676 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010677 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010678
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010679 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010680 return false;
10681
Douglas Gregorb491ed32011-02-19 21:32:49 +000010682 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10683 return true;
10684 }
10685
10686 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10687 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010688 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010689 // Skip non-static functions when converting to pointer, and static
10690 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010691 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10692 return false;
10693 }
10694 else if (TargetTypeIsNonStaticMemberFunction)
10695 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010696
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010697 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010698 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010699 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010700 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010701 return false;
10702
Richard Smith2a7d4812013-05-04 07:00:32 +000010703 // If any candidate has a placeholder return type, trigger its deduction
10704 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010705 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10706 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010707 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010708 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010709 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010710
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010711 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010712 return false;
10713
George Burgess IV6da4c202016-03-23 02:33:58 +000010714 // If we're in C, we need to support types that aren't exactly identical.
10715 if (!S.getLangOpts().CPlusPlus ||
10716 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010717 Matches.push_back(std::make_pair(
10718 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010719 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010720 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010721 }
Mike Stump11289f42009-09-09 15:08:12 +000010722 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010723
10724 return false;
10725 }
10726
10727 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10728 bool Ret = false;
10729
10730 // If the overload expression doesn't have the form of a pointer to
10731 // member, don't try to convert it to a pointer-to-member type.
10732 if (IsInvalidFormOfPointerToMemberFunction())
10733 return false;
10734
10735 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10736 E = OvlExpr->decls_end();
10737 I != E; ++I) {
10738 // Look through any using declarations to find the underlying function.
10739 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10740
10741 // C++ [over.over]p3:
10742 // Non-member functions and static member functions match
10743 // targets of type "pointer-to-function" or "reference-to-function."
10744 // Nonstatic member functions match targets of
10745 // type "pointer-to-member-function."
10746 // Note that according to DR 247, the containing class does not matter.
10747 if (FunctionTemplateDecl *FunctionTemplate
10748 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10749 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10750 Ret = true;
10751 }
10752 // If we have explicit template arguments supplied, skip non-templates.
10753 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10754 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10755 Ret = true;
10756 }
10757 assert(Ret || Matches.empty());
10758 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010759 }
10760
Douglas Gregorb491ed32011-02-19 21:32:49 +000010761 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010762 // [...] and any given function template specialization F1 is
10763 // eliminated if the set contains a second function template
10764 // specialization whose function template is more specialized
10765 // than the function template of F1 according to the partial
10766 // ordering rules of 14.5.5.2.
10767
10768 // The algorithm specified above is quadratic. We instead use a
10769 // two-pass algorithm (similar to the one used to identify the
10770 // best viable function in an overload set) that identifies the
10771 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010772
10773 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10774 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10775 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010776
Larisse Voufo98b20f12013-07-19 23:00:19 +000010777 // TODO: It looks like FailedCandidates does not serve much purpose
10778 // here, since the no_viable diagnostic has index 0.
10779 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010780 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010781 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010782 S.PDiag(diag::err_addr_ovl_ambiguous)
10783 << Matches[0].second->getDeclName(),
10784 S.PDiag(diag::note_ovl_candidate)
10785 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010786 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010787
Douglas Gregorb491ed32011-02-19 21:32:49 +000010788 if (Result != MatchesCopy.end()) {
10789 // Make it the first and only element
10790 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10791 Matches[0].second = cast<FunctionDecl>(*Result);
10792 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010793 } else
10794 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010796
Douglas Gregorb491ed32011-02-19 21:32:49 +000010797 void EliminateAllTemplateMatches() {
10798 // [...] any function template specializations in the set are
10799 // eliminated if the set also contains a non-template function, [...]
10800 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010801 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010802 ++I;
10803 else {
10804 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010805 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010806 }
10807 }
10808 }
10809
Artem Belevich94a55e82015-09-22 17:22:59 +000010810 void EliminateSuboptimalCudaMatches() {
10811 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10812 }
10813
Douglas Gregorb491ed32011-02-19 21:32:49 +000010814public:
10815 void ComplainNoMatchesFound() const {
10816 assert(Matches.empty());
10817 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10818 << OvlExpr->getName() << TargetFunctionType
10819 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010820 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010821 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10822 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010823 else {
10824 // We have some deduction failure messages. Use them to diagnose
10825 // the function templates, and diagnose the non-template candidates
10826 // normally.
10827 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10828 IEnd = OvlExpr->decls_end();
10829 I != IEnd; ++I)
10830 if (FunctionDecl *Fun =
10831 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010832 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010833 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010834 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010835 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10836 }
10837 }
10838
Douglas Gregorb491ed32011-02-19 21:32:49 +000010839 bool IsInvalidFormOfPointerToMemberFunction() const {
10840 return TargetTypeIsNonStaticMemberFunction &&
10841 !OvlExprInfo.HasFormOfMemberPointer;
10842 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010843
Douglas Gregorb491ed32011-02-19 21:32:49 +000010844 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10845 // TODO: Should we condition this on whether any functions might
10846 // have matched, or is it more appropriate to do that in callers?
10847 // TODO: a fixit wouldn't hurt.
10848 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10849 << TargetType << OvlExpr->getSourceRange();
10850 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010851
10852 bool IsStaticMemberFunctionFromBoundPointer() const {
10853 return StaticMemberFunctionFromBoundPointer;
10854 }
10855
10856 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10857 S.Diag(OvlExpr->getLocStart(),
10858 diag::err_invalid_form_pointer_member_function)
10859 << OvlExpr->getSourceRange();
10860 }
10861
Douglas Gregorb491ed32011-02-19 21:32:49 +000010862 void ComplainOfInvalidConversion() const {
10863 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10864 << OvlExpr->getName() << TargetType;
10865 }
10866
10867 void ComplainMultipleMatchesFound() const {
10868 assert(Matches.size() > 1);
10869 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10870 << OvlExpr->getName()
10871 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010872 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10873 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010874 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010875
10876 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10877
Douglas Gregorb491ed32011-02-19 21:32:49 +000010878 int getNumMatches() const { return Matches.size(); }
10879
10880 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010881 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010882 return Matches[0].second;
10883 }
10884
10885 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010886 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010887 return &Matches[0].first;
10888 }
10889};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010890}
Richard Smith17c00b42014-11-12 01:24:00 +000010891
Douglas Gregorb491ed32011-02-19 21:32:49 +000010892/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10893/// an overloaded function (C++ [over.over]), where @p From is an
10894/// expression with overloaded function type and @p ToType is the type
10895/// we're trying to resolve to. For example:
10896///
10897/// @code
10898/// int f(double);
10899/// int f(int);
10900///
10901/// int (*pfd)(double) = f; // selects f(double)
10902/// @endcode
10903///
10904/// This routine returns the resulting FunctionDecl if it could be
10905/// resolved, and NULL otherwise. When @p Complain is true, this
10906/// routine will emit diagnostics if there is an error.
10907FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010908Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10909 QualType TargetType,
10910 bool Complain,
10911 DeclAccessPair &FoundResult,
10912 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010913 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010914
10915 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10916 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010917 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010918 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010919 bool ShouldComplain = Complain && !Resolver.hasComplained();
10920 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010921 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10922 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10923 else
10924 Resolver.ComplainNoMatchesFound();
10925 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010926 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010927 Resolver.ComplainMultipleMatchesFound();
10928 else if (NumMatches == 1) {
10929 Fn = Resolver.getMatchingFunctionDecl();
10930 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000010931 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10932 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010933 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010934 if (Complain) {
10935 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10936 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10937 else
10938 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10939 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010940 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010941
10942 if (pHadMultipleCandidates)
10943 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010944 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010945}
10946
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010947/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010948/// resolve that function to a single function that can have its address taken.
10949/// This will modify `Pair` iff it returns non-null.
10950///
10951/// This routine can only realistically succeed if all but one candidates in the
10952/// overload set for SrcExpr cannot have their addresses taken.
10953FunctionDecl *
10954Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10955 DeclAccessPair &Pair) {
10956 OverloadExpr::FindResult R = OverloadExpr::find(E);
10957 OverloadExpr *Ovl = R.Expression;
10958 FunctionDecl *Result = nullptr;
10959 DeclAccessPair DAP;
10960 // Don't use the AddressOfResolver because we're specifically looking for
10961 // cases where we have one overload candidate that lacks
10962 // enable_if/pass_object_size/...
10963 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10964 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10965 if (!FD)
10966 return nullptr;
10967
10968 if (!checkAddressOfFunctionIsAvailable(FD))
10969 continue;
10970
10971 // We have more than one result; quit.
10972 if (Result)
10973 return nullptr;
10974 DAP = I.getPair();
10975 Result = FD;
10976 }
10977
10978 if (Result)
10979 Pair = DAP;
10980 return Result;
10981}
10982
George Burgess IVbeca4a32016-06-08 00:34:22 +000010983/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10984/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10985/// will perform access checks, diagnose the use of the resultant decl, and, if
10986/// necessary, perform a function-to-pointer decay.
10987///
10988/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10989/// Otherwise, returns true. This may emit diagnostics and return true.
10990bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10991 ExprResult &SrcExpr) {
10992 Expr *E = SrcExpr.get();
10993 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10994
10995 DeclAccessPair DAP;
10996 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10997 if (!Found)
10998 return false;
10999
11000 // Emitting multiple diagnostics for a function that is both inaccessible and
11001 // unavailable is consistent with our behavior elsewhere. So, always check
11002 // for both.
11003 DiagnoseUseOfDecl(Found, E->getExprLoc());
11004 CheckAddressOfMemberAccess(E, DAP);
11005 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11006 if (Fixed->getType()->isFunctionType())
11007 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11008 else
11009 SrcExpr = Fixed;
11010 return true;
11011}
11012
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011013/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011014/// resolve that overloaded function expression down to a single function.
11015///
11016/// This routine can only resolve template-ids that refer to a single function
11017/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011018/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011019/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011020///
11021/// If no template-ids are found, no diagnostics are emitted and NULL is
11022/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011023FunctionDecl *
11024Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11025 bool Complain,
11026 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011027 // C++ [over.over]p1:
11028 // [...] [Note: any redundant set of parentheses surrounding the
11029 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011030 // C++ [over.over]p1:
11031 // [...] The overloaded function name can be preceded by the &
11032 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011033
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011034 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011035 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011036 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011037
11038 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011039 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011040 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011041
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011042 // Look through all of the overloaded functions, searching for one
11043 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011044 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011045 for (UnresolvedSetIterator I = ovl->decls_begin(),
11046 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011047 // C++0x [temp.arg.explicit]p3:
11048 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011049 // where deduction is not done, if a template argument list is
11050 // specified and it, along with any default template arguments,
11051 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011052 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011053 FunctionTemplateDecl *FunctionTemplate
11054 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011055
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011056 // C++ [over.over]p2:
11057 // If the name is a function template, template argument deduction is
11058 // done (14.8.2.2), and if the argument deduction succeeds, the
11059 // resulting template argument list is used to generate a single
11060 // function template specialization, which is added to the set of
11061 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011062 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011063 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011064 if (TemplateDeductionResult Result
11065 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011066 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011067 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011068 // Make a note of the failed deduction for diagnostics.
11069 // TODO: Actually use the failed-deduction info?
11070 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011071 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011072 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011073 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011074 }
11075
John McCall0009fcc2011-04-26 20:42:42 +000011076 assert(Specialization && "no specialization and no error?");
11077
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011078 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011079 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011080 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011081 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11082 << ovl->getName();
11083 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011084 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011085 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011086 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011087
John McCall0009fcc2011-04-26 20:42:42 +000011088 Matched = Specialization;
11089 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011091
Richard Smith9095e5b2016-11-01 01:31:23 +000011092 if (Matched &&
11093 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011094 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011095
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011096 return Matched;
11097}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011098
Douglas Gregor1beec452011-03-12 01:48:56 +000011099
11100
11101
John McCall50a2c2c2011-10-11 23:14:30 +000011102// Resolve and fix an overloaded expression that can be resolved
11103// because it identifies a single function template specialization.
11104//
Douglas Gregor1beec452011-03-12 01:48:56 +000011105// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011106//
11107// Return true if it was logically possible to so resolve the
11108// expression, regardless of whether or not it succeeded. Always
11109// returns true if 'complain' is set.
11110bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11111 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011112 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011113 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011114 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011115 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011116
John McCall50a2c2c2011-10-11 23:14:30 +000011117 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011118
John McCall0009fcc2011-04-26 20:42:42 +000011119 DeclAccessPair found;
11120 ExprResult SingleFunctionExpression;
11121 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11122 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011123 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011124 SrcExpr = ExprError();
11125 return true;
11126 }
John McCall0009fcc2011-04-26 20:42:42 +000011127
11128 // It is only correct to resolve to an instance method if we're
11129 // resolving a form that's permitted to be a pointer to member.
11130 // Otherwise we'll end up making a bound member expression, which
11131 // is illegal in all the contexts we resolve like this.
11132 if (!ovl.HasFormOfMemberPointer &&
11133 isa<CXXMethodDecl>(fn) &&
11134 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011135 if (!complain) return false;
11136
11137 Diag(ovl.Expression->getExprLoc(),
11138 diag::err_bound_member_function)
11139 << 0 << ovl.Expression->getSourceRange();
11140
11141 // TODO: I believe we only end up here if there's a mix of
11142 // static and non-static candidates (otherwise the expression
11143 // would have 'bound member' type, not 'overload' type).
11144 // Ideally we would note which candidate was chosen and why
11145 // the static candidates were rejected.
11146 SrcExpr = ExprError();
11147 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011148 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011149
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011150 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011151 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011152 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011153
11154 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011155 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011156 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011157 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011158 if (SingleFunctionExpression.isInvalid()) {
11159 SrcExpr = ExprError();
11160 return true;
11161 }
11162 }
John McCall0009fcc2011-04-26 20:42:42 +000011163 }
11164
11165 if (!SingleFunctionExpression.isUsable()) {
11166 if (complain) {
11167 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11168 << ovl.Expression->getName()
11169 << DestTypeForComplaining
11170 << OpRangeForComplaining
11171 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011172 NoteAllOverloadCandidates(SrcExpr.get());
11173
11174 SrcExpr = ExprError();
11175 return true;
11176 }
11177
11178 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011179 }
11180
John McCall50a2c2c2011-10-11 23:14:30 +000011181 SrcExpr = SingleFunctionExpression;
11182 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011183}
11184
Douglas Gregorcabea402009-09-22 15:41:20 +000011185/// \brief Add a single candidate to the overload set.
11186static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011187 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011188 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011189 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011190 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011191 bool PartialOverloading,
11192 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011193 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011194 if (isa<UsingShadowDecl>(Callee))
11195 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11196
Douglas Gregorcabea402009-09-22 15:41:20 +000011197 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011198 if (ExplicitTemplateArgs) {
11199 assert(!KnownValid && "Explicit template arguments?");
11200 return;
11201 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011202 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11203 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011204 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011205 return;
John McCalld14a8642009-11-21 08:51:07 +000011206 }
11207
11208 if (FunctionTemplateDecl *FuncTemplate
11209 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011210 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011211 ExplicitTemplateArgs, Args, CandidateSet,
11212 /*SuppressUsedConversions=*/false,
11213 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011214 return;
11215 }
11216
Richard Smith95ce4f62011-06-26 22:19:54 +000011217 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011218}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011219
Douglas Gregorcabea402009-09-22 15:41:20 +000011220/// \brief Add the overload candidates named by callee and/or found by argument
11221/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011222void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011223 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011224 OverloadCandidateSet &CandidateSet,
11225 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011226
11227#ifndef NDEBUG
11228 // Verify that ArgumentDependentLookup is consistent with the rules
11229 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011230 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011231 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11232 // and let Y be the lookup set produced by argument dependent
11233 // lookup (defined as follows). If X contains
11234 //
11235 // -- a declaration of a class member, or
11236 //
11237 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011238 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011239 //
11240 // -- a declaration that is neither a function or a function
11241 // template
11242 //
11243 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011244
John McCall57500772009-12-16 12:17:52 +000011245 if (ULE->requiresADL()) {
11246 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11247 E = ULE->decls_end(); I != E; ++I) {
11248 assert(!(*I)->getDeclContext()->isRecord());
11249 assert(isa<UsingShadowDecl>(*I) ||
11250 !(*I)->getDeclContext()->isFunctionOrMethod());
11251 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011252 }
11253 }
11254#endif
11255
John McCall57500772009-12-16 12:17:52 +000011256 // It would be nice to avoid this copy.
11257 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011258 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011259 if (ULE->hasExplicitTemplateArgs()) {
11260 ULE->copyTemplateArgumentsInto(TABuffer);
11261 ExplicitTemplateArgs = &TABuffer;
11262 }
11263
11264 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11265 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011266 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11267 CandidateSet, PartialOverloading,
11268 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011269
John McCall57500772009-12-16 12:17:52 +000011270 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011271 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011272 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011273 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011274}
John McCalld681c392009-12-16 08:11:27 +000011275
Richard Smith0603bbb2013-06-12 22:56:54 +000011276/// Determine whether a declaration with the specified name could be moved into
11277/// a different namespace.
11278static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11279 switch (Name.getCXXOverloadedOperator()) {
11280 case OO_New: case OO_Array_New:
11281 case OO_Delete: case OO_Array_Delete:
11282 return false;
11283
11284 default:
11285 return true;
11286 }
11287}
11288
Richard Smith998a5912011-06-05 22:42:48 +000011289/// Attempt to recover from an ill-formed use of a non-dependent name in a
11290/// template, where the non-dependent name was declared after the template
11291/// was defined. This is common in code written for a compilers which do not
11292/// correctly implement two-stage name lookup.
11293///
11294/// Returns true if a viable candidate was found and a diagnostic was issued.
11295static bool
11296DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11297 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011298 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011299 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011300 ArrayRef<Expr *> Args,
11301 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011302 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11303 return false;
11304
11305 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011306 if (DC->isTransparentContext())
11307 continue;
11308
Richard Smith998a5912011-06-05 22:42:48 +000011309 SemaRef.LookupQualifiedName(R, DC);
11310
11311 if (!R.empty()) {
11312 R.suppressDiagnostics();
11313
11314 if (isa<CXXRecordDecl>(DC)) {
11315 // Don't diagnose names we find in classes; we get much better
11316 // diagnostics for these from DiagnoseEmptyLookup.
11317 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011318 if (DoDiagnoseEmptyLookup)
11319 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011320 return false;
11321 }
11322
Richard Smith100b24a2014-04-17 01:52:14 +000011323 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011324 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11325 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011326 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011327 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011328
11329 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011330 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011331 // No viable functions. Don't bother the user with notes for functions
11332 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011333 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011334 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011335 }
Richard Smith998a5912011-06-05 22:42:48 +000011336
11337 // Find the namespaces where ADL would have looked, and suggest
11338 // declaring the function there instead.
11339 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11340 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011341 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011342 AssociatedNamespaces,
11343 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011344 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011345 if (canBeDeclaredInNamespace(R.getLookupName())) {
11346 DeclContext *Std = SemaRef.getStdNamespace();
11347 for (Sema::AssociatedNamespaceSet::iterator
11348 it = AssociatedNamespaces.begin(),
11349 end = AssociatedNamespaces.end(); it != end; ++it) {
11350 // Never suggest declaring a function within namespace 'std'.
11351 if (Std && Std->Encloses(*it))
11352 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011353
Richard Smith0603bbb2013-06-12 22:56:54 +000011354 // Never suggest declaring a function within a namespace with a
11355 // reserved name, like __gnu_cxx.
11356 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11357 if (NS &&
11358 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11359 continue;
11360
11361 SuggestedNamespaces.insert(*it);
11362 }
Richard Smith998a5912011-06-05 22:42:48 +000011363 }
11364
11365 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11366 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011367 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011368 SemaRef.Diag(Best->Function->getLocation(),
11369 diag::note_not_found_by_two_phase_lookup)
11370 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011371 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011372 SemaRef.Diag(Best->Function->getLocation(),
11373 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011374 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011375 } else {
11376 // FIXME: It would be useful to list the associated namespaces here,
11377 // but the diagnostics infrastructure doesn't provide a way to produce
11378 // a localized representation of a list of items.
11379 SemaRef.Diag(Best->Function->getLocation(),
11380 diag::note_not_found_by_two_phase_lookup)
11381 << R.getLookupName() << 2;
11382 }
11383
11384 // Try to recover by calling this function.
11385 return true;
11386 }
11387
11388 R.clear();
11389 }
11390
11391 return false;
11392}
11393
11394/// Attempt to recover from ill-formed use of a non-dependent operator in a
11395/// template, where the non-dependent operator was declared after the template
11396/// was defined.
11397///
11398/// Returns true if a viable candidate was found and a diagnostic was issued.
11399static bool
11400DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11401 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011402 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011403 DeclarationName OpName =
11404 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11405 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11406 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011407 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011408 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011409}
11410
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011411namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011412class BuildRecoveryCallExprRAII {
11413 Sema &SemaRef;
11414public:
11415 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11416 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11417 SemaRef.IsBuildingRecoveryCallExpr = true;
11418 }
11419
11420 ~BuildRecoveryCallExprRAII() {
11421 SemaRef.IsBuildingRecoveryCallExpr = false;
11422 }
11423};
11424
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011425}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011426
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011427static std::unique_ptr<CorrectionCandidateCallback>
11428MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11429 bool HasTemplateArgs, bool AllowTypoCorrection) {
11430 if (!AllowTypoCorrection)
11431 return llvm::make_unique<NoTypoCorrectionCCC>();
11432 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11433 HasTemplateArgs, ME);
11434}
11435
John McCalld681c392009-12-16 08:11:27 +000011436/// Attempts to recover from a call where no functions were found.
11437///
11438/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011439static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011440BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011441 UnresolvedLookupExpr *ULE,
11442 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011443 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011444 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011445 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011446 // Do not try to recover if it is already building a recovery call.
11447 // This stops infinite loops for template instantiations like
11448 //
11449 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11450 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11451 //
11452 if (SemaRef.IsBuildingRecoveryCallExpr)
11453 return ExprError();
11454 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011455
11456 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011457 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011458 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011459
John McCall57500772009-12-16 12:17:52 +000011460 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011461 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011462 if (ULE->hasExplicitTemplateArgs()) {
11463 ULE->copyTemplateArgumentsInto(TABuffer);
11464 ExplicitTemplateArgs = &TABuffer;
11465 }
11466
John McCalld681c392009-12-16 08:11:27 +000011467 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11468 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011469 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011470 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011471 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011472 ExplicitTemplateArgs, Args,
11473 &DoDiagnoseEmptyLookup) &&
11474 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11475 S, SS, R,
11476 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11477 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11478 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011479 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011480
John McCall57500772009-12-16 12:17:52 +000011481 assert(!R.empty() && "lookup results empty despite recovery");
11482
Richard Smith151c4562016-12-20 21:35:28 +000011483 // If recovery created an ambiguity, just bail out.
11484 if (R.isAmbiguous()) {
11485 R.suppressDiagnostics();
11486 return ExprError();
11487 }
11488
John McCall57500772009-12-16 12:17:52 +000011489 // Build an implicit member call if appropriate. Just drop the
11490 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011491 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011492 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011493 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11494 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011495 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011496 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011497 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011498 else
11499 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11500
11501 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011502 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011503
11504 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011505 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011506 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011507 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011508 MultiExprArg(Args.data(), Args.size()),
11509 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011510}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011511
Sam Panzer0f384432012-08-21 00:52:01 +000011512/// \brief Constructs and populates an OverloadedCandidateSet from
11513/// the given function.
11514/// \returns true when an the ExprResult output parameter has been set.
11515bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11516 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011517 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011518 SourceLocation RParenLoc,
11519 OverloadCandidateSet *CandidateSet,
11520 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011521#ifndef NDEBUG
11522 if (ULE->requiresADL()) {
11523 // To do ADL, we must have found an unqualified name.
11524 assert(!ULE->getQualifier() && "qualified name with ADL");
11525
11526 // We don't perform ADL for implicit declarations of builtins.
11527 // Verify that this was correctly set up.
11528 FunctionDecl *F;
11529 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11530 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11531 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011532 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011533
John McCall57500772009-12-16 12:17:52 +000011534 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011535 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011536 }
John McCall57500772009-12-16 12:17:52 +000011537#endif
11538
John McCall4124c492011-10-17 18:40:02 +000011539 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011540 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011541 *Result = ExprError();
11542 return true;
11543 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011544
John McCall57500772009-12-16 12:17:52 +000011545 // Add the functions denoted by the callee to the set of candidate
11546 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011547 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011548
Hans Wennborgb2747382015-06-12 21:23:23 +000011549 if (getLangOpts().MSVCCompat &&
11550 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011551 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11552
11553 OverloadCandidateSet::iterator Best;
11554 if (CandidateSet->empty() ||
11555 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11556 OR_No_Viable_Function) {
11557 // In Microsoft mode, if we are inside a template class member function then
11558 // create a type dependent CallExpr. The goal is to postpone name lookup
11559 // to instantiation time to be able to search into type dependent base
11560 // classes.
11561 CallExpr *CE = new (Context) CallExpr(
11562 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011563 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011564 CE->setValueDependent(true);
11565 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011566 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011567 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011568 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011569 }
John McCalld681c392009-12-16 08:11:27 +000011570
Hans Wennborg64937c62015-06-11 21:21:57 +000011571 if (CandidateSet->empty())
11572 return false;
11573
John McCall4124c492011-10-17 18:40:02 +000011574 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011575 return false;
11576}
John McCall4124c492011-10-17 18:40:02 +000011577
Sam Panzer0f384432012-08-21 00:52:01 +000011578/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11579/// the completed call expression. If overload resolution fails, emits
11580/// diagnostics and returns ExprError()
11581static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11582 UnresolvedLookupExpr *ULE,
11583 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011584 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011585 SourceLocation RParenLoc,
11586 Expr *ExecConfig,
11587 OverloadCandidateSet *CandidateSet,
11588 OverloadCandidateSet::iterator *Best,
11589 OverloadingResult OverloadResult,
11590 bool AllowTypoCorrection) {
11591 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011592 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011593 RParenLoc, /*EmptyLookup=*/true,
11594 AllowTypoCorrection);
11595
11596 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011597 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011598 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011599 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011600 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11601 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011602 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011603 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11604 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011605 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011606
Richard Smith998a5912011-06-05 22:42:48 +000011607 case OR_No_Viable_Function: {
11608 // Try to recover by looking for viable functions which the user might
11609 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011610 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011611 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011612 /*EmptyLookup=*/false,
11613 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011614 if (!Recovery.isInvalid())
11615 return Recovery;
11616
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011617 // If the user passes in a function that we can't take the address of, we
11618 // generally end up emitting really bad error messages. Here, we attempt to
11619 // emit better ones.
11620 for (const Expr *Arg : Args) {
11621 if (!Arg->getType()->isFunctionType())
11622 continue;
11623 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11624 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11625 if (FD &&
11626 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11627 Arg->getExprLoc()))
11628 return ExprError();
11629 }
11630 }
11631
11632 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11633 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011634 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011635 break;
Richard Smith998a5912011-06-05 22:42:48 +000011636 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011637
11638 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011639 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011640 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011641 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011642 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011643
Sam Panzer0f384432012-08-21 00:52:01 +000011644 case OR_Deleted: {
11645 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11646 << (*Best)->Function->isDeleted()
11647 << ULE->getName()
11648 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11649 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011650 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011651
Sam Panzer0f384432012-08-21 00:52:01 +000011652 // We emitted an error for the unvailable/deleted function call but keep
11653 // the call in the AST.
11654 FunctionDecl *FDecl = (*Best)->Function;
11655 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011656 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11657 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011658 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011659 }
11660
Douglas Gregorb412e172010-07-25 18:17:45 +000011661 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011662 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011663}
11664
George Burgess IV7204ed92016-01-07 02:26:57 +000011665static void markUnaddressableCandidatesUnviable(Sema &S,
11666 OverloadCandidateSet &CS) {
11667 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11668 if (I->Viable &&
11669 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11670 I->Viable = false;
11671 I->FailureKind = ovl_fail_addr_not_available;
11672 }
11673 }
11674}
11675
Sam Panzer0f384432012-08-21 00:52:01 +000011676/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11677/// (which eventually refers to the declaration Func) and the call
11678/// arguments Args/NumArgs, attempt to resolve the function call down
11679/// to a specific function. If overload resolution succeeds, returns
11680/// the call expression produced by overload resolution.
11681/// Otherwise, emits diagnostics and returns ExprError.
11682ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11683 UnresolvedLookupExpr *ULE,
11684 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011685 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011686 SourceLocation RParenLoc,
11687 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011688 bool AllowTypoCorrection,
11689 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011690 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11691 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011692 ExprResult result;
11693
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011694 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11695 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011696 return result;
11697
George Burgess IV7204ed92016-01-07 02:26:57 +000011698 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11699 // functions that aren't addressible are considered unviable.
11700 if (CalleesAddressIsTaken)
11701 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11702
Sam Panzer0f384432012-08-21 00:52:01 +000011703 OverloadCandidateSet::iterator Best;
11704 OverloadingResult OverloadResult =
11705 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11706
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011707 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011708 RParenLoc, ExecConfig, &CandidateSet,
11709 &Best, OverloadResult,
11710 AllowTypoCorrection);
11711}
11712
John McCall4c4c1df2010-01-26 03:27:55 +000011713static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011714 return Functions.size() > 1 ||
11715 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11716}
11717
Douglas Gregor084d8552009-03-13 23:49:33 +000011718/// \brief Create a unary operation that may resolve to an overloaded
11719/// operator.
11720///
11721/// \param OpLoc The location of the operator itself (e.g., '*').
11722///
Craig Toppera92ffb02015-12-10 08:51:49 +000011723/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011724///
James Dennett18348b62012-06-22 08:52:37 +000011725/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011726/// considered by overload resolution. The caller needs to build this
11727/// set based on the context using, e.g.,
11728/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11729/// set should not contain any member functions; those will be added
11730/// by CreateOverloadedUnaryOp().
11731///
James Dennett91738ff2012-06-22 10:32:46 +000011732/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011733ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011734Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011735 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011736 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011737 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11738 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11739 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011740 // TODO: provide better source location info.
11741 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011742
John McCall4124c492011-10-17 18:40:02 +000011743 if (checkPlaceholderForOverload(*this, Input))
11744 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011745
Craig Topperc3ec1492014-05-26 06:22:03 +000011746 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011747 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011748
Douglas Gregor084d8552009-03-13 23:49:33 +000011749 // For post-increment and post-decrement, add the implicit '0' as
11750 // the second argument, so that we know this is a post-increment or
11751 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011752 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011753 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011754 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11755 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011756 NumArgs = 2;
11757 }
11758
Richard Smithe54c3072013-05-05 15:51:06 +000011759 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11760
Douglas Gregor084d8552009-03-13 23:49:33 +000011761 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011762 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011763 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11764 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011765
Craig Topperc3ec1492014-05-26 06:22:03 +000011766 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011767 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011768 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011769 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011770 /*ADL*/ true, IsOverloaded(Fns),
11771 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011772 return new (Context)
11773 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11774 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011775 }
11776
11777 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011778 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011779
11780 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011781 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011782
11783 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011784 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011785
John McCall4c4c1df2010-01-26 03:27:55 +000011786 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011787 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011788 /*ExplicitTemplateArgs*/nullptr,
11789 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011790
Douglas Gregor084d8552009-03-13 23:49:33 +000011791 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011792 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011793
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011794 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11795
Douglas Gregor084d8552009-03-13 23:49:33 +000011796 // Perform overload resolution.
11797 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011798 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011799 case OR_Success: {
11800 // We found a built-in operator or an overloaded operator.
11801 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011802
Douglas Gregor084d8552009-03-13 23:49:33 +000011803 if (FnDecl) {
11804 // We matched an overloaded operator. Build a call to that
11805 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011806
Douglas Gregor084d8552009-03-13 23:49:33 +000011807 // Convert the arguments.
11808 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011809 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011810
John Wiegley01296292011-04-08 18:41:53 +000011811 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011812 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011813 Best->FoundDecl, Method);
11814 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011815 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011816 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011817 } else {
11818 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011819 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011820 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011821 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011822 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011823 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011824 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011825 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011826 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011827 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011828 }
11829
Douglas Gregor084d8552009-03-13 23:49:33 +000011830 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011831 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011832 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011833 if (FnExpr.isInvalid())
11834 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011835
Richard Smithc1564702013-11-15 02:58:23 +000011836 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011837 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011838 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11839 ResultTy = ResultTy.getNonLValueExprType(Context);
11840
Eli Friedman030eee42009-11-18 03:58:17 +000011841 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011842 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011843 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011844 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011845
Alp Toker314cc812014-01-25 16:55:45 +000011846 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011847 return ExprError();
11848
John McCallb268a282010-08-23 23:25:46 +000011849 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011850 } else {
11851 // We matched a built-in operator. Convert the arguments, then
11852 // break out so that we will build the appropriate built-in
11853 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011854 ExprResult InputRes =
11855 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11856 Best->Conversions[0], AA_Passing);
11857 if (InputRes.isInvalid())
11858 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011859 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011860 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011861 }
John Wiegley01296292011-04-08 18:41:53 +000011862 }
11863
11864 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011865 // This is an erroneous use of an operator which can be overloaded by
11866 // a non-member function. Check for non-member operators which were
11867 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011868 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011869 // FIXME: Recover by calling the found function.
11870 return ExprError();
11871
John Wiegley01296292011-04-08 18:41:53 +000011872 // No viable function; fall through to handling this as a
11873 // built-in operator, which will produce an error message for us.
11874 break;
11875
11876 case OR_Ambiguous:
11877 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11878 << UnaryOperator::getOpcodeStr(Opc)
11879 << Input->getType()
11880 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011881 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011882 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11883 return ExprError();
11884
11885 case OR_Deleted:
11886 Diag(OpLoc, diag::err_ovl_deleted_oper)
11887 << Best->Function->isDeleted()
11888 << UnaryOperator::getOpcodeStr(Opc)
11889 << getDeletedOrUnavailableSuffix(Best->Function)
11890 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011891 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011892 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011893 return ExprError();
11894 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011895
11896 // Either we found no viable overloaded operator or we matched a
11897 // built-in operator. In either case, fall through to trying to
11898 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011899 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011900}
11901
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011902/// \brief Create a binary operation that may resolve to an overloaded
11903/// operator.
11904///
11905/// \param OpLoc The location of the operator itself (e.g., '+').
11906///
Craig Toppera92ffb02015-12-10 08:51:49 +000011907/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011908///
James Dennett18348b62012-06-22 08:52:37 +000011909/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011910/// considered by overload resolution. The caller needs to build this
11911/// set based on the context using, e.g.,
11912/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11913/// set should not contain any member functions; those will be added
11914/// by CreateOverloadedBinOp().
11915///
11916/// \param LHS Left-hand argument.
11917/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011918ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011919Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011920 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011921 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011922 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011923 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011924 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011925
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011926 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11927 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11928
11929 // If either side is type-dependent, create an appropriate dependent
11930 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011931 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011932 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011933 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011934 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011935 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011936 return new (Context) BinaryOperator(
11937 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11938 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011939
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011940 return new (Context) CompoundAssignOperator(
11941 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11942 Context.DependentTy, Context.DependentTy, OpLoc,
11943 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011944 }
John McCall4c4c1df2010-01-26 03:27:55 +000011945
11946 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011947 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011948 // TODO: provide better source location info in DNLoc component.
11949 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011950 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011951 = UnresolvedLookupExpr::Create(Context, NamingClass,
11952 NestedNameSpecifierLoc(), OpNameInfo,
11953 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011954 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011955 return new (Context)
11956 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11957 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011958 }
11959
John McCall4124c492011-10-17 18:40:02 +000011960 // Always do placeholder-like conversions on the RHS.
11961 if (checkPlaceholderForOverload(*this, Args[1]))
11962 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011963
John McCall526ab472011-10-25 17:37:35 +000011964 // Do placeholder-like conversion on the LHS; note that we should
11965 // not get here with a PseudoObject LHS.
11966 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011967 if (checkPlaceholderForOverload(*this, Args[0]))
11968 return ExprError();
11969
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011970 // If this is the assignment operator, we only perform overload resolution
11971 // if the left-hand side is a class or enumeration type. This is actually
11972 // a hack. The standard requires that we do overload resolution between the
11973 // various built-in candidates, but as DR507 points out, this can lead to
11974 // problems. So we do it this way, which pretty much follows what GCC does.
11975 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011976 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011977 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011978
John McCalle26a8722010-12-04 08:14:53 +000011979 // If this is the .* operator, which is not overloadable, just
11980 // create a built-in binary operator.
11981 if (Opc == BO_PtrMemD)
11982 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11983
Douglas Gregor084d8552009-03-13 23:49:33 +000011984 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011985 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011986
11987 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011988 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011989
11990 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011991 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011992
Richard Smith0daabd72014-09-23 20:31:39 +000011993 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11994 // performed for an assignment operator (nor for operator[] nor operator->,
11995 // which don't get here).
11996 if (Opc != BO_Assign)
11997 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11998 /*ExplicitTemplateArgs*/ nullptr,
11999 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012000
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012001 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012002 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012003
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012004 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12005
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012006 // Perform overload resolution.
12007 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012008 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012009 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012010 // We found a built-in operator or an overloaded operator.
12011 FunctionDecl *FnDecl = Best->Function;
12012
12013 if (FnDecl) {
12014 // We matched an overloaded operator. Build a call to that
12015 // operator.
12016
12017 // Convert the arguments.
12018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012019 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012020 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012021
Chandler Carruth8e543b32010-12-12 08:17:55 +000012022 ExprResult Arg1 =
12023 PerformCopyInitialization(
12024 InitializedEntity::InitializeParameter(Context,
12025 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012026 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012027 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012028 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012029
John Wiegley01296292011-04-08 18:41:53 +000012030 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012031 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012032 Best->FoundDecl, Method);
12033 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012034 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012035 Args[0] = Arg0.getAs<Expr>();
12036 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012037 } else {
12038 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012039 ExprResult Arg0 = PerformCopyInitialization(
12040 InitializedEntity::InitializeParameter(Context,
12041 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012042 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012043 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012044 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012045
Chandler Carruth8e543b32010-12-12 08:17:55 +000012046 ExprResult Arg1 =
12047 PerformCopyInitialization(
12048 InitializedEntity::InitializeParameter(Context,
12049 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012050 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012051 if (Arg1.isInvalid())
12052 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012053 Args[0] = LHS = Arg0.getAs<Expr>();
12054 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012055 }
12056
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012057 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012058 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012059 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012060 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012061 if (FnExpr.isInvalid())
12062 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012063
Richard Smithc1564702013-11-15 02:58:23 +000012064 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012065 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012066 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12067 ResultTy = ResultTy.getNonLValueExprType(Context);
12068
John McCallb268a282010-08-23 23:25:46 +000012069 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012070 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012071 Args, ResultTy, VK, OpLoc,
12072 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012073
Alp Toker314cc812014-01-25 16:55:45 +000012074 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012075 FnDecl))
12076 return ExprError();
12077
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012078 ArrayRef<const Expr *> ArgsArray(Args, 2);
12079 // Cut off the implicit 'this'.
12080 if (isa<CXXMethodDecl>(FnDecl))
12081 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012082
12083 // Check for a self move.
12084 if (Op == OO_Equal)
12085 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12086
Douglas Gregorb4866e82015-06-19 18:13:19 +000012087 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012088 TheCall->getSourceRange(), VariadicDoesNotApply);
12089
John McCallb268a282010-08-23 23:25:46 +000012090 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012091 } else {
12092 // We matched a built-in operator. Convert the arguments, then
12093 // break out so that we will build the appropriate built-in
12094 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012095 ExprResult ArgsRes0 =
12096 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12097 Best->Conversions[0], AA_Passing);
12098 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012099 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012100 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012101
John Wiegley01296292011-04-08 18:41:53 +000012102 ExprResult ArgsRes1 =
12103 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12104 Best->Conversions[1], AA_Passing);
12105 if (ArgsRes1.isInvalid())
12106 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012107 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012108 break;
12109 }
12110 }
12111
Douglas Gregor66950a32009-09-30 21:46:01 +000012112 case OR_No_Viable_Function: {
12113 // C++ [over.match.oper]p9:
12114 // If the operator is the operator , [...] and there are no
12115 // viable functions, then the operator is assumed to be the
12116 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012117 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012118 break;
12119
Chandler Carruth8e543b32010-12-12 08:17:55 +000012120 // For class as left operand for assignment or compound assigment
12121 // operator do not fall through to handling in built-in, but report that
12122 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012123 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012124 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012125 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012126 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12127 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012128 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012129 if (Args[0]->getType()->isIncompleteType()) {
12130 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12131 << Args[0]->getType()
12132 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12133 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012134 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012135 // This is an erroneous use of an operator which can be overloaded by
12136 // a non-member function. Check for non-member operators which were
12137 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012138 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012139 // FIXME: Recover by calling the found function.
12140 return ExprError();
12141
Douglas Gregor66950a32009-09-30 21:46:01 +000012142 // No viable function; try to create a built-in operation, which will
12143 // produce an error. Then, show the non-viable candidates.
12144 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012146 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012147 "C++ binary operator overloading is missing candidates!");
12148 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012149 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012150 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012151 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012152 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012153
12154 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012155 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012156 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012157 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012158 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012159 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012160 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012161 return ExprError();
12162
12163 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012164 if (isImplicitlyDeleted(Best->Function)) {
12165 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12166 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012167 << Context.getRecordType(Method->getParent())
12168 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012169
Richard Smithde1a4872012-12-28 12:23:24 +000012170 // The user probably meant to call this special member. Just
12171 // explain why it's deleted.
12172 NoteDeletedFunction(Method);
12173 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012174 } else {
12175 Diag(OpLoc, diag::err_ovl_deleted_oper)
12176 << Best->Function->isDeleted()
12177 << BinaryOperator::getOpcodeStr(Opc)
12178 << getDeletedOrUnavailableSuffix(Best->Function)
12179 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12180 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012181 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012182 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012183 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012184 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012185
Douglas Gregor66950a32009-09-30 21:46:01 +000012186 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012187 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012188}
12189
John McCalldadc5752010-08-24 06:29:42 +000012190ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012191Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12192 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012193 Expr *Base, Expr *Idx) {
12194 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012195 DeclarationName OpName =
12196 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12197
12198 // If either side is type-dependent, create an appropriate dependent
12199 // expression.
12200 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12201
Craig Topperc3ec1492014-05-26 06:22:03 +000012202 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012203 // CHECKME: no 'operator' keyword?
12204 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12205 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012206 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012207 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012208 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012209 /*ADL*/ true, /*Overloaded*/ false,
12210 UnresolvedSetIterator(),
12211 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012212 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012213
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012214 return new (Context)
12215 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12216 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012217 }
12218
John McCall4124c492011-10-17 18:40:02 +000012219 // Handle placeholders on both operands.
12220 if (checkPlaceholderForOverload(*this, Args[0]))
12221 return ExprError();
12222 if (checkPlaceholderForOverload(*this, Args[1]))
12223 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012224
Sebastian Redladba46e2009-10-29 20:17:01 +000012225 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012226 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012227
12228 // Subscript can only be overloaded as a member function.
12229
12230 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012231 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012232
12233 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012234 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012235
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012236 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12237
Sebastian Redladba46e2009-10-29 20:17:01 +000012238 // Perform overload resolution.
12239 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012240 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012241 case OR_Success: {
12242 // We found a built-in operator or an overloaded operator.
12243 FunctionDecl *FnDecl = Best->Function;
12244
12245 if (FnDecl) {
12246 // We matched an overloaded operator. Build a call to that
12247 // operator.
12248
John McCalla0296f72010-03-19 07:35:19 +000012249 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012250
Sebastian Redladba46e2009-10-29 20:17:01 +000012251 // Convert the arguments.
12252 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012253 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012254 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012255 Best->FoundDecl, Method);
12256 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012257 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012258 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012259
Anders Carlssona68e51e2010-01-29 18:37:50 +000012260 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012261 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012262 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012263 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012264 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012265 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012266 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012267 if (InputInit.isInvalid())
12268 return ExprError();
12269
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012270 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012271
Sebastian Redladba46e2009-10-29 20:17:01 +000012272 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012273 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12274 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012275 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012276 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012277 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012278 OpLocInfo.getLoc(),
12279 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012280 if (FnExpr.isInvalid())
12281 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012282
Richard Smithc1564702013-11-15 02:58:23 +000012283 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012284 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012285 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12286 ResultTy = ResultTy.getNonLValueExprType(Context);
12287
John McCallb268a282010-08-23 23:25:46 +000012288 CXXOperatorCallExpr *TheCall =
12289 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012290 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012291 ResultTy, VK, RLoc,
12292 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012293
Alp Toker314cc812014-01-25 16:55:45 +000012294 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012295 return ExprError();
12296
John McCallb268a282010-08-23 23:25:46 +000012297 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012298 } else {
12299 // We matched a built-in operator. Convert the arguments, then
12300 // break out so that we will build the appropriate built-in
12301 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012302 ExprResult ArgsRes0 =
12303 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12304 Best->Conversions[0], AA_Passing);
12305 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012306 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012307 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012308
12309 ExprResult ArgsRes1 =
12310 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12311 Best->Conversions[1], AA_Passing);
12312 if (ArgsRes1.isInvalid())
12313 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012314 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012315
12316 break;
12317 }
12318 }
12319
12320 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012321 if (CandidateSet.empty())
12322 Diag(LLoc, diag::err_ovl_no_oper)
12323 << Args[0]->getType() << /*subscript*/ 0
12324 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12325 else
12326 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12327 << Args[0]->getType()
12328 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012329 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012330 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012331 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012332 }
12333
12334 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012335 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012336 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012337 << Args[0]->getType() << Args[1]->getType()
12338 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012339 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012340 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012341 return ExprError();
12342
12343 case OR_Deleted:
12344 Diag(LLoc, diag::err_ovl_deleted_oper)
12345 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012346 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012347 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012348 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012349 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012350 return ExprError();
12351 }
12352
12353 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012354 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012355}
12356
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012357/// BuildCallToMemberFunction - Build a call to a member
12358/// function. MemExpr is the expression that refers to the member
12359/// function (and includes the object parameter), Args/NumArgs are the
12360/// arguments to the function call (not including the object
12361/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012362/// expression refers to a non-static member function or an overloaded
12363/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012364ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012365Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012366 SourceLocation LParenLoc,
12367 MultiExprArg Args,
12368 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012369 assert(MemExprE->getType() == Context.BoundMemberTy ||
12370 MemExprE->getType() == Context.OverloadTy);
12371
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012372 // Dig out the member expression. This holds both the object
12373 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012374 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012375
John McCall0009fcc2011-04-26 20:42:42 +000012376 // Determine whether this is a call to a pointer-to-member function.
12377 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12378 assert(op->getType() == Context.BoundMemberTy);
12379 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12380
12381 QualType fnType =
12382 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12383
12384 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12385 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012386 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012387
12388 // Check that the object type isn't more qualified than the
12389 // member function we're calling.
12390 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12391
12392 QualType objectType = op->getLHS()->getType();
12393 if (op->getOpcode() == BO_PtrMemI)
12394 objectType = objectType->castAs<PointerType>()->getPointeeType();
12395 Qualifiers objectQuals = objectType.getQualifiers();
12396
12397 Qualifiers difference = objectQuals - funcQuals;
12398 difference.removeObjCGCAttr();
12399 difference.removeAddressSpace();
12400 if (difference) {
12401 std::string qualsString = difference.getAsString();
12402 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12403 << fnType.getUnqualifiedType()
12404 << qualsString
12405 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12406 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012407
John McCall0009fcc2011-04-26 20:42:42 +000012408 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012409 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012410 resultType, valueKind, RParenLoc);
12411
Alp Toker314cc812014-01-25 16:55:45 +000012412 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012413 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012414 return ExprError();
12415
Craig Topperc3ec1492014-05-26 06:22:03 +000012416 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012417 return ExprError();
12418
Richard Trieu9be9c682013-06-22 02:30:38 +000012419 if (CheckOtherCall(call, proto))
12420 return ExprError();
12421
John McCall0009fcc2011-04-26 20:42:42 +000012422 return MaybeBindToTemporary(call);
12423 }
12424
David Majnemerced8bdf2015-02-25 17:36:15 +000012425 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12426 return new (Context)
12427 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12428
John McCall4124c492011-10-17 18:40:02 +000012429 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012430 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012431 return ExprError();
12432
John McCall10eae182009-11-30 22:42:35 +000012433 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012434 CXXMethodDecl *Method = nullptr;
12435 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12436 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012437 if (isa<MemberExpr>(NakedMemExpr)) {
12438 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012439 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012440 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012441 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012442 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012443 } else {
12444 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012445 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012446
John McCall6e9f8f62009-12-03 04:06:58 +000012447 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012448 Expr::Classification ObjectClassification
12449 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12450 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012451
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012452 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012453 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12454 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012455
John McCall2d74de92009-12-01 22:10:20 +000012456 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012457 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012458 if (UnresExpr->hasExplicitTemplateArgs()) {
12459 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12460 TemplateArgs = &TemplateArgsBuffer;
12461 }
12462
John McCall10eae182009-11-30 22:42:35 +000012463 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12464 E = UnresExpr->decls_end(); I != E; ++I) {
12465
John McCall6e9f8f62009-12-03 04:06:58 +000012466 NamedDecl *Func = *I;
12467 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12468 if (isa<UsingShadowDecl>(Func))
12469 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12470
Douglas Gregor02824322011-01-26 19:30:28 +000012471
Francois Pichet64225792011-01-18 05:04:39 +000012472 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012473 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012474 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012475 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012476 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012477 // If explicit template arguments were provided, we can't call a
12478 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012479 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012480 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012481
John McCalla0296f72010-03-19 07:35:19 +000012482 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012483 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012484 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012485 } else {
John McCall10eae182009-11-30 22:42:35 +000012486 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012487 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012488 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012489 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012490 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012491 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012492 }
Mike Stump11289f42009-09-09 15:08:12 +000012493
John McCall10eae182009-11-30 22:42:35 +000012494 DeclarationName DeclName = UnresExpr->getMemberName();
12495
John McCall4124c492011-10-17 18:40:02 +000012496 UnbridgedCasts.restore();
12497
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012498 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012499 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012500 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012501 case OR_Success:
12502 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012503 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012504 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012505 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12506 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012507 // If FoundDecl is different from Method (such as if one is a template
12508 // and the other a specialization), make sure DiagnoseUseOfDecl is
12509 // called on both.
12510 // FIXME: This would be more comprehensively addressed by modifying
12511 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12512 // being used.
12513 if (Method != FoundDecl.getDecl() &&
12514 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12515 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012516 break;
12517
12518 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012519 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012520 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012521 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012522 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012523 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012524 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012525
12526 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012527 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012528 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012529 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012530 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012531 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012532
12533 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012534 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012535 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012536 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012537 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012538 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012539 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012540 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012541 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012542 }
12543
John McCall16df1e52010-03-30 21:47:33 +000012544 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012545
John McCall2d74de92009-12-01 22:10:20 +000012546 // If overload resolution picked a static member, build a
12547 // non-member call based on that function.
12548 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012549 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12550 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012551 }
12552
John McCall10eae182009-11-30 22:42:35 +000012553 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012554 }
12555
Alp Toker314cc812014-01-25 16:55:45 +000012556 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012557 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12558 ResultType = ResultType.getNonLValueExprType(Context);
12559
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012560 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012561 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012562 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012563 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012564
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012565 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012566 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012567 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012568 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012569
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012570 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012571 // We only need to do this if there was actually an overload; otherwise
12572 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012573 if (!Method->isStatic()) {
12574 ExprResult ObjectArg =
12575 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12576 FoundDecl, Method);
12577 if (ObjectArg.isInvalid())
12578 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012579 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012580 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012581
12582 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012583 const FunctionProtoType *Proto =
12584 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012585 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012586 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012587 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012588
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012589 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012590
Richard Smith55ce3522012-06-25 20:30:08 +000012591 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012592 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012593
George Burgess IVaea6ade2015-09-25 17:53:16 +000012594 // In the case the method to call was not selected by the overloading
12595 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012596 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012597 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012598 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012599 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012600 diag::err_ovl_no_viable_member_function_in_call)
12601 << Method << Method->getSourceRange();
12602 Diag(Method->getLocation(),
12603 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12604 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12605 return ExprError();
12606 }
12607 }
12608
Anders Carlsson47061ee2011-05-06 14:25:31 +000012609 if ((isa<CXXConstructorDecl>(CurContext) ||
12610 isa<CXXDestructorDecl>(CurContext)) &&
12611 TheCall->getMethodDecl()->isPure()) {
12612 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12613
Davide Italianoccb37382015-07-14 23:36:10 +000012614 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12615 MemExpr->performsVirtualDispatch(getLangOpts())) {
12616 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012617 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12618 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12619 << MD->getParent()->getDeclName();
12620
12621 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012622 if (getLangOpts().AppleKext)
12623 Diag(MemExpr->getLocStart(),
12624 diag::note_pure_qualified_call_kext)
12625 << MD->getParent()->getDeclName()
12626 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012627 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012628 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012629
12630 if (CXXDestructorDecl *DD =
12631 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12632 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012633 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012634 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12635 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12636 MemExpr->getMemberLoc());
12637 }
12638
John McCallb268a282010-08-23 23:25:46 +000012639 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012640}
12641
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012642/// BuildCallToObjectOfClassType - Build a call to an object of class
12643/// type (C++ [over.call.object]), which can end up invoking an
12644/// overloaded function call operator (@c operator()) or performing a
12645/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012646ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012647Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012648 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012649 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012650 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012651 if (checkPlaceholderForOverload(*this, Obj))
12652 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012653 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012654
12655 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012656 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012657 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012658
Nico Weberb58e51c2014-11-19 05:21:39 +000012659 assert(Object.get()->getType()->isRecordType() &&
12660 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012661 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012662
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012663 // C++ [over.call.object]p1:
12664 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012665 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012666 // candidate functions includes at least the function call
12667 // operators of T. The function call operators of T are obtained by
12668 // ordinary lookup of the name operator() in the context of
12669 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012670 OverloadCandidateSet CandidateSet(LParenLoc,
12671 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012672 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012673
John Wiegley01296292011-04-08 18:41:53 +000012674 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012675 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012676 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012677
John McCall27b18f82009-11-17 02:14:36 +000012678 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12679 LookupQualifiedName(R, Record->getDecl());
12680 R.suppressDiagnostics();
12681
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012682 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012683 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012684 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012685 Object.get()->Classify(Context),
12686 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012687 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012689
Douglas Gregorab7897a2008-11-19 22:57:39 +000012690 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012691 // In addition, for each (non-explicit in C++0x) conversion function
12692 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012693 //
12694 // operator conversion-type-id () cv-qualifier;
12695 //
12696 // where cv-qualifier is the same cv-qualification as, or a
12697 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012698 // denotes the type "pointer to function of (P1,...,Pn) returning
12699 // R", or the type "reference to pointer to function of
12700 // (P1,...,Pn) returning R", or the type "reference to function
12701 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012702 // is also considered as a candidate function. Similarly,
12703 // surrogate call functions are added to the set of candidate
12704 // functions for each conversion function declared in an
12705 // accessible base class provided the function is not hidden
12706 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012707 const auto &Conversions =
12708 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12709 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012710 NamedDecl *D = *I;
12711 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12712 if (isa<UsingShadowDecl>(D))
12713 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012714
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012715 // Skip over templated conversion functions; they aren't
12716 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012717 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012718 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012719
John McCall6e9f8f62009-12-03 04:06:58 +000012720 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012721 if (!Conv->isExplicit()) {
12722 // Strip the reference type (if any) and then the pointer type (if
12723 // any) to get down to what might be a function type.
12724 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12725 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12726 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012727
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012728 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12729 {
12730 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012731 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012732 }
12733 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012734 }
Mike Stump11289f42009-09-09 15:08:12 +000012735
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012736 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12737
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012738 // Perform overload resolution.
12739 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012740 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012741 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012742 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012743 // Overload resolution succeeded; we'll build the appropriate call
12744 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012745 break;
12746
12747 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012748 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012749 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012750 << Object.get()->getType() << /*call*/ 1
12751 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012752 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012753 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012754 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012755 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012756 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012757 break;
12758
12759 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012760 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012761 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012762 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012763 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012764 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012765
12766 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012767 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012768 diag::err_ovl_deleted_object_call)
12769 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012770 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012771 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012772 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012773 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012774 break;
Mike Stump11289f42009-09-09 15:08:12 +000012775 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012776
Douglas Gregorb412e172010-07-25 18:17:45 +000012777 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012778 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012779
John McCall4124c492011-10-17 18:40:02 +000012780 UnbridgedCasts.restore();
12781
Craig Topperc3ec1492014-05-26 06:22:03 +000012782 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012783 // Since there is no function declaration, this is one of the
12784 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012785 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012786 = cast<CXXConversionDecl>(
12787 Best->Conversions[0].UserDefined.ConversionFunction);
12788
Craig Topperc3ec1492014-05-26 06:22:03 +000012789 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12790 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012791 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12792 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012793 assert(Conv == Best->FoundDecl.getDecl() &&
12794 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012795 // We selected one of the surrogate functions that converts the
12796 // object parameter to a function pointer. Perform the conversion
12797 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012798
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012799 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012800 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012801 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12802 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012803 if (Call.isInvalid())
12804 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012805 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012806 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12807 CK_UserDefinedConversion, Call.get(),
12808 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012809
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012810 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012811 }
12812
Craig Topperc3ec1492014-05-26 06:22:03 +000012813 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012814
Douglas Gregorab7897a2008-11-19 22:57:39 +000012815 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12816 // that calls this method, using Object for the implicit object
12817 // parameter and passing along the remaining arguments.
12818 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012819
12820 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012821 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012822 return ExprError();
12823
Chandler Carruth8e543b32010-12-12 08:17:55 +000012824 const FunctionProtoType *Proto =
12825 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012826
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012827 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012828
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012829 DeclarationNameInfo OpLocInfo(
12830 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12831 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012832 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012833 HadMultipleCandidates,
12834 OpLocInfo.getLoc(),
12835 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012836 if (NewFn.isInvalid())
12837 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012838
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012839 // Build the full argument list for the method call (the implicit object
12840 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000012841 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012842 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000012843 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012844
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012845 // Once we've built TheCall, all of the expressions are properly
12846 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012847 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012848 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12849 ResultTy = ResultTy.getNonLValueExprType(Context);
12850
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012851 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000012852 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12853 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012854
Alp Toker314cc812014-01-25 16:55:45 +000012855 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012856 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012857
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012858 // We may have default arguments. If so, we need to allocate more
12859 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012860 if (Args.size() < NumParams)
12861 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012862
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012863 bool IsError = false;
12864
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012865 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012866 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012867 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012868 Best->FoundDecl, Method);
12869 if (ObjRes.isInvalid())
12870 IsError = true;
12871 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012872 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012873 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012874
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012875 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012876 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012877 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012878 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012879 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012880
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012881 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012882
John McCalldadc5752010-08-24 06:29:42 +000012883 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012884 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012885 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012886 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012887 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012888
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012889 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012890 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012891 } else {
John McCalldadc5752010-08-24 06:29:42 +000012892 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012893 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12894 if (DefArg.isInvalid()) {
12895 IsError = true;
12896 break;
12897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012898
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012899 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012900 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012901
12902 TheCall->setArg(i + 1, Arg);
12903 }
12904
12905 // If this is a variadic call, handle args passed through "...".
12906 if (Proto->isVariadic()) {
12907 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012908 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012909 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12910 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012911 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012912 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012913 }
12914 }
12915
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012916 if (IsError) return true;
12917
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012918 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012919
Richard Smith55ce3522012-06-25 20:30:08 +000012920 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012921 return true;
12922
John McCalle172be52010-08-24 06:09:16 +000012923 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012924}
12925
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012926/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012927/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012928/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012929ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012930Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12931 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012932 assert(Base->getType()->isRecordType() &&
12933 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012934
John McCall4124c492011-10-17 18:40:02 +000012935 if (checkPlaceholderForOverload(*this, Base))
12936 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012937
John McCallbc077cf2010-02-08 23:07:23 +000012938 SourceLocation Loc = Base->getExprLoc();
12939
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012940 // C++ [over.ref]p1:
12941 //
12942 // [...] An expression x->m is interpreted as (x.operator->())->m
12943 // for a class object x of type T if T::operator->() exists and if
12944 // the operator is selected as the best match function by the
12945 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012946 DeclarationName OpName =
12947 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012948 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012949 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012950
John McCallbc077cf2010-02-08 23:07:23 +000012951 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012952 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012953 return ExprError();
12954
John McCall27b18f82009-11-17 02:14:36 +000012955 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12956 LookupQualifiedName(R, BaseRecord->getDecl());
12957 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012958
12959 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012960 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012961 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012962 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012963 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012964
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012965 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12966
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012967 // Perform overload resolution.
12968 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012969 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012970 case OR_Success:
12971 // Overload resolution succeeded; we'll build the call below.
12972 break;
12973
12974 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012975 if (CandidateSet.empty()) {
12976 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012977 if (NoArrowOperatorFound) {
12978 // Report this specific error to the caller instead of emitting a
12979 // diagnostic, as requested.
12980 *NoArrowOperatorFound = true;
12981 return ExprError();
12982 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012983 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12984 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012985 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012986 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012987 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012988 }
12989 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012990 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012991 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012993 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012994
12995 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012996 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12997 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012998 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012999 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013000
13001 case OR_Deleted:
13002 Diag(OpLoc, diag::err_ovl_deleted_oper)
13003 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013004 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013005 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013006 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013007 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013008 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013009 }
13010
Craig Topperc3ec1492014-05-26 06:22:03 +000013011 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013012
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013013 // Convert the object parameter.
13014 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013015 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013016 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013017 Best->FoundDecl, Method);
13018 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013019 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013020 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013021
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013022 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013023 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013024 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013025 if (FnExpr.isInvalid())
13026 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013027
Alp Toker314cc812014-01-25 16:55:45 +000013028 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013029 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13030 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013031 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013032 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000013033 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013034
Alp Toker314cc812014-01-25 16:55:45 +000013035 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013036 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013037
13038 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013039}
13040
Richard Smithbcc22fc2012-03-09 08:00:36 +000013041/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13042/// a literal operator described by the provided lookup results.
13043ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13044 DeclarationNameInfo &SuffixInfo,
13045 ArrayRef<Expr*> Args,
13046 SourceLocation LitEndLoc,
13047 TemplateArgumentListInfo *TemplateArgs) {
13048 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013049
Richard Smith100b24a2014-04-17 01:52:14 +000013050 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13051 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013052 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13053 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013054
Richard Smithbcc22fc2012-03-09 08:00:36 +000013055 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13056
Richard Smithbcc22fc2012-03-09 08:00:36 +000013057 // Perform overload resolution. This will usually be trivial, but might need
13058 // to perform substitutions for a literal operator template.
13059 OverloadCandidateSet::iterator Best;
13060 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13061 case OR_Success:
13062 case OR_Deleted:
13063 break;
13064
13065 case OR_No_Viable_Function:
13066 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13067 << R.getLookupName();
13068 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13069 return ExprError();
13070
13071 case OR_Ambiguous:
13072 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13073 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13074 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013075 }
13076
Richard Smithbcc22fc2012-03-09 08:00:36 +000013077 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013078 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13079 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013080 SuffixInfo.getLoc(),
13081 SuffixInfo.getInfo());
13082 if (Fn.isInvalid())
13083 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013084
13085 // Check the argument types. This should almost always be a no-op, except
13086 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013087 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013088 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013089 ExprResult InputInit = PerformCopyInitialization(
13090 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13091 SourceLocation(), Args[ArgIdx]);
13092 if (InputInit.isInvalid())
13093 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013094 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013095 }
13096
Alp Toker314cc812014-01-25 16:55:45 +000013097 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013098 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13099 ResultTy = ResultTy.getNonLValueExprType(Context);
13100
Richard Smithc67fdd42012-03-07 08:35:16 +000013101 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013102 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013103 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013104 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13105
Alp Toker314cc812014-01-25 16:55:45 +000013106 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013107 return ExprError();
13108
Craig Topperc3ec1492014-05-26 06:22:03 +000013109 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013110 return ExprError();
13111
13112 return MaybeBindToTemporary(UDL);
13113}
13114
Sam Panzer0f384432012-08-21 00:52:01 +000013115/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13116/// given LookupResult is non-empty, it is assumed to describe a member which
13117/// will be invoked. Otherwise, the function will be found via argument
13118/// dependent lookup.
13119/// CallExpr is set to a valid expression and FRS_Success returned on success,
13120/// otherwise CallExpr is set to ExprError() and some non-success value
13121/// is returned.
13122Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013123Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13124 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013125 const DeclarationNameInfo &NameInfo,
13126 LookupResult &MemberLookup,
13127 OverloadCandidateSet *CandidateSet,
13128 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013129 Scope *S = nullptr;
13130
Sam Panzer0f384432012-08-21 00:52:01 +000013131 CandidateSet->clear();
13132 if (!MemberLookup.empty()) {
13133 ExprResult MemberRef =
13134 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13135 /*IsPtr=*/false, CXXScopeSpec(),
13136 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013137 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013138 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013139 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013140 if (MemberRef.isInvalid()) {
13141 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013142 return FRS_DiagnosticIssued;
13143 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013144 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013145 if (CallExpr->isInvalid()) {
13146 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013147 return FRS_DiagnosticIssued;
13148 }
13149 } else {
13150 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013151 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013152 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013153 NestedNameSpecifierLoc(), NameInfo,
13154 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013155 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013156
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013157 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013158 CandidateSet, CallExpr);
13159 if (CandidateSet->empty() || CandidateSetError) {
13160 *CallExpr = ExprError();
13161 return FRS_NoViableFunction;
13162 }
13163 OverloadCandidateSet::iterator Best;
13164 OverloadingResult OverloadResult =
13165 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13166
13167 if (OverloadResult == OR_No_Viable_Function) {
13168 *CallExpr = ExprError();
13169 return FRS_NoViableFunction;
13170 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013171 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013172 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013173 OverloadResult,
13174 /*AllowTypoCorrection=*/false);
13175 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13176 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013177 return FRS_DiagnosticIssued;
13178 }
13179 }
13180 return FRS_Success;
13181}
13182
13183
Douglas Gregorcd695e52008-11-10 20:40:00 +000013184/// FixOverloadedFunctionReference - E is an expression that refers to
13185/// a C++ overloaded function (possibly with some parentheses and
13186/// perhaps a '&' around it). We have resolved the overloaded function
13187/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013188/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013189Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013190 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013191 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013192 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13193 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013194 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013195 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013196
Douglas Gregor51c538b2009-11-20 19:42:02 +000013197 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013198 }
13199
Douglas Gregor51c538b2009-11-20 19:42:02 +000013200 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013201 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13202 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013203 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013204 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013205 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013206 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013207 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013208 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013209
13210 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013211 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013212 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013213 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013214 }
13215
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013216 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13217 if (!GSE->isResultDependent()) {
13218 Expr *SubExpr =
13219 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13220 if (SubExpr == GSE->getResultExpr())
13221 return GSE;
13222
13223 // Replace the resulting type information before rebuilding the generic
13224 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013225 ArrayRef<Expr *> A = GSE->getAssocExprs();
13226 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013227 unsigned ResultIdx = GSE->getResultIndex();
13228 AssocExprs[ResultIdx] = SubExpr;
13229
13230 return new (Context) GenericSelectionExpr(
13231 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13232 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13233 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13234 ResultIdx);
13235 }
13236 // Rather than fall through to the unreachable, return the original generic
13237 // selection expression.
13238 return GSE;
13239 }
13240
Douglas Gregor51c538b2009-11-20 19:42:02 +000013241 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013242 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013243 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013244 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13245 if (Method->isStatic()) {
13246 // Do nothing: static member functions aren't any different
13247 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013248 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013249 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013250 // UnresolvedLookupExpr holding an overloaded member function
13251 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013252 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13253 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013254 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013255 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013256
John McCalld14a8642009-11-21 08:51:07 +000013257 assert(isa<DeclRefExpr>(SubExpr)
13258 && "fixed to something other than a decl ref");
13259 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13260 && "fixed to a member ref with no nested name qualifier");
13261
13262 // We have taken the address of a pointer to member
13263 // function. Perform the computation here so that we get the
13264 // appropriate pointer to member type.
13265 QualType ClassType
13266 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13267 QualType MemPtrType
13268 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013269 // Under the MS ABI, lock down the inheritance model now.
13270 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13271 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013272
John McCall7decc9e2010-11-18 06:31:45 +000013273 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13274 VK_RValue, OK_Ordinary,
13275 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013276 }
13277 }
John McCall16df1e52010-03-30 21:47:33 +000013278 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13279 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013280 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013281 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013282
John McCalle3027922010-08-25 11:45:40 +000013283 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013284 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013285 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013286 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013287 }
John McCalld14a8642009-11-21 08:51:07 +000013288
Richard Smith84a0b6d2016-10-18 23:39:12 +000013289 // C++ [except.spec]p17:
13290 // An exception-specification is considered to be needed when:
13291 // - in an expression the function is the unique lookup result or the
13292 // selected member of a set of overloaded functions
13293 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13294 ResolveExceptionSpec(E->getExprLoc(), FPT);
13295
John McCalld14a8642009-11-21 08:51:07 +000013296 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013297 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013298 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013299 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013300 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13301 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013302 }
13303
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013304 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13305 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013306 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013307 Fn,
John McCall113bee02012-03-10 09:33:50 +000013308 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013309 ULE->getNameLoc(),
13310 Fn->getType(),
13311 VK_LValue,
13312 Found.getDecl(),
13313 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013314 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013315 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13316 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013317 }
13318
John McCall10eae182009-11-30 22:42:35 +000013319 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013320 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013321 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013322 if (MemExpr->hasExplicitTemplateArgs()) {
13323 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13324 TemplateArgs = &TemplateArgsBuffer;
13325 }
John McCall6b51f282009-11-23 01:53:49 +000013326
John McCall2d74de92009-12-01 22:10:20 +000013327 Expr *Base;
13328
John McCall7decc9e2010-11-18 06:31:45 +000013329 // If we're filling in a static method where we used to have an
13330 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013331 if (MemExpr->isImplicitAccess()) {
13332 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013333 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13334 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013335 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013336 Fn,
John McCall113bee02012-03-10 09:33:50 +000013337 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013338 MemExpr->getMemberLoc(),
13339 Fn->getType(),
13340 VK_LValue,
13341 Found.getDecl(),
13342 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013343 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013344 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13345 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013346 } else {
13347 SourceLocation Loc = MemExpr->getMemberLoc();
13348 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013349 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013350 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013351 Base = new (Context) CXXThisExpr(Loc,
13352 MemExpr->getBaseType(),
13353 /*isImplicit=*/true);
13354 }
John McCall2d74de92009-12-01 22:10:20 +000013355 } else
John McCallc3007a22010-10-26 07:05:15 +000013356 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013357
John McCall4adb38c2011-04-27 00:36:17 +000013358 ExprValueKind valueKind;
13359 QualType type;
13360 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13361 valueKind = VK_LValue;
13362 type = Fn->getType();
13363 } else {
13364 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013365 type = Context.BoundMemberTy;
13366 }
13367
13368 MemberExpr *ME = MemberExpr::Create(
13369 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13370 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13371 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13372 OK_Ordinary);
13373 ME->setHadMultipleCandidates(true);
13374 MarkMemberReferenced(ME);
13375 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013377
John McCallc3007a22010-10-26 07:05:15 +000013378 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013379}
13380
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013381ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013382 DeclAccessPair Found,
13383 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013384 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013385}