blob: f1b74ad5545aeebdff73eff28d5593e9a8333626 [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) {
42 return std::any_of(FD->param_begin(), FD->param_end(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44}
45
Nick Lewycky134af912013-02-07 05:08:22 +000046/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000047static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000048CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000050 SourceLocation Loc = SourceLocation(),
51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000052 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000053 return ExprError();
54 // If FoundDecl is different from Fn (such as if one is a template
55 // and the other a specialization), make sure DiagnoseUseOfDecl is
56 // called on both.
57 // FIXME: This would be more comprehensively addressed by modifying
58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59 // being used.
60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000061 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000062 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 VK_LValue, Loc, LocInfo);
64 if (HadMultipleCandidates)
65 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000066
67 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000068 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000070}
71
John McCall5c32be02010-08-24 20:38:10 +000072static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000074 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000075 bool CStyle,
76 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000077
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000078static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000083static OverloadingResult
84IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000087 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000089
90
91static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000092CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000093 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96static ImplicitConversionSequence::CompareKind
97CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000102CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000108ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICR_Promotion,
118 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000127 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000128 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000129 ICR_Conversion,
130 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000131 ICR_Complex_Real_Conversion,
132 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000133 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000134 ICR_Writeback_Conversion,
135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136 // it was omitted by the patch that added
137 // ICK_Zero_Event_Conversion
138 ICR_C_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 };
140 return Rank[(int)Kind];
141}
142
143/// GetImplicitConversionName - Return the name of this kind of
144/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000145static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "No conversion",
148 "Lvalue-to-rvalue",
149 "Array-to-pointer",
150 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000151 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "Qualification",
153 "Integral promotion",
154 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000155 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Integral conversion",
157 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Floating-integral conversion",
160 "Pointer conversion",
161 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000162 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000163 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000164 "Derived-to-base conversion",
165 "Vector conversion",
166 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000167 "Complex-real conversion",
168 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000169 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000170 "Writeback conversion",
171 "OpenCL Zero Event Conversion",
172 "C specific type conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000184 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000185 ReferenceBinding = false;
186 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000187 IsLvalueReference = true;
188 BindsToFunctionLvalue = false;
189 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000190 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000191 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000192 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000193}
194
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195/// getRank - Retrieve the rank of this standard conversion sequence
196/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197/// implicit conversions.
198ImplicitConversionRank StandardConversionSequence::getRank() const {
199 ImplicitConversionRank Rank = ICR_Exact_Match;
200 if (GetConversionRank(First) > Rank)
201 Rank = GetConversionRank(First);
202 if (GetConversionRank(Second) > Rank)
203 Rank = GetConversionRank(Second);
204 if (GetConversionRank(Third) > Rank)
205 Rank = GetConversionRank(Third);
206 return Rank;
207}
208
209/// isPointerConversionToBool - Determines whether this conversion is
210/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000211/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000213bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000214 // Note that FromType has not necessarily been transformed by the
215 // array-to-pointer or function-to-pointer implicit conversions, so
216 // check for their presence as well as checking whether FromType is
217 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000218 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000219 (getFromType()->isPointerType() ||
220 getFromType()->isObjCObjectPointerType() ||
221 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000222 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224 return true;
225
226 return false;
227}
228
Douglas Gregor5c407d92008-10-23 00:40:37 +0000229/// isPointerConversionToVoidPointer - Determines whether this
230/// conversion is a conversion of a pointer to a void pointer. This is
231/// used as part of the ranking of standard conversion sequences (C++
232/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000233bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000235isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000236 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000237 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238
239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer implicit conversion, so check for its presence
241 // and redo the conversion to get a pointer.
242 if (First == ICK_Array_To_Pointer)
243 FromType = Context.getArrayDecayedType(FromType);
244
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247 return ToPtrType->getPointeeType()->isVoidType();
248
249 return false;
250}
251
Richard Smith66e05fe2012-01-18 05:21:49 +0000252/// Skip any implicit casts which could be either part of a narrowing conversion
253/// or after one in an implicit conversion.
254static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256 switch (ICE->getCastKind()) {
257 case CK_NoOp:
258 case CK_IntegralCast:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000261 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000262 case CK_FloatingToIntegral:
263 case CK_FloatingToBoolean:
264 case CK_FloatingCast:
265 Converted = ICE->getSubExpr();
266 continue;
267
268 default:
269 return Converted;
270 }
271 }
272
273 return Converted;
274}
275
276/// Check if this standard conversion sequence represents a narrowing
277/// conversion, according to C++11 [dcl.init.list]p7.
278///
279/// \param Ctx The AST context.
280/// \param Converted The result of applying this standard conversion sequence.
281/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
282/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000283/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
284/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000285NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000286StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000288 APValue &ConstantValue,
289 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000291
292 // C++11 [dcl.init.list]p7:
293 // A narrowing conversion is an implicit conversion ...
294 QualType FromType = getToType(0);
295 QualType ToType = getToType(1);
296 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000297 // 'bool' is an integral type; dispatch to the right place to handle it.
298 case ICK_Boolean_Conversion:
299 if (FromType->isRealFloatingType())
300 goto FloatingIntegralConversion;
301 if (FromType->isIntegralOrUnscopedEnumerationType())
302 goto IntegralConversion;
303 // Boolean conversions can be from pointers and pointers to members
304 // [conv.bool], and those aren't considered narrowing conversions.
305 return NK_Not_Narrowing;
306
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000314 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000315 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
316 return NK_Type_Narrowing;
317 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
318 llvm::APSInt IntConstantValue;
319 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
320 if (Initializer &&
321 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
322 // Convert the integer to the floating type.
323 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
324 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
325 llvm::APFloat::rmNearestTiesToEven);
326 // And back.
327 llvm::APSInt ConvertedValue = IntConstantValue;
328 bool ignored;
329 Result.convertToInteger(ConvertedValue,
330 llvm::APFloat::rmTowardZero, &ignored);
331 // If the resulting value is different, this was a narrowing conversion.
332 if (IntConstantValue != ConvertedValue) {
333 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000334 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000335 return NK_Constant_Narrowing;
336 }
337 } else {
338 // Variables are always narrowings.
339 return NK_Variable_Narrowing;
340 }
341 }
342 return NK_Not_Narrowing;
343
344 // -- from long double to double or float, or from double to float, except
345 // where the source is a constant expression and the actual value after
346 // conversion is within the range of values that can be represented (even
347 // if it cannot be represented exactly), or
348 case ICK_Floating_Conversion:
349 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
350 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
351 // FromType is larger than ToType.
352 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
353 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
354 // Constant!
355 assert(ConstantValue.isFloat());
356 llvm::APFloat FloatVal = ConstantValue.getFloat();
357 // Convert the source value into the target type.
358 bool ignored;
359 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
360 Ctx.getFloatTypeSemantics(ToType),
361 llvm::APFloat::rmNearestTiesToEven, &ignored);
362 // If there was no overflow, the source value is within the range of
363 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000364 if (ConvertStatus & llvm::APFloat::opOverflow) {
365 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000367 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000368 } else {
369 return NK_Variable_Narrowing;
370 }
371 }
372 return NK_Not_Narrowing;
373
374 // -- from an integer type or unscoped enumeration type to an integer type
375 // that cannot represent all the values of the original type, except where
376 // the source is a constant expression and the actual value after
377 // conversion will fit into the target type and will produce the original
378 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000379 case ICK_Integral_Conversion:
380 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000381 assert(FromType->isIntegralOrUnscopedEnumerationType());
382 assert(ToType->isIntegralOrUnscopedEnumerationType());
383 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
384 const unsigned FromWidth = Ctx.getIntWidth(FromType);
385 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
386 const unsigned ToWidth = Ctx.getIntWidth(ToType);
387
388 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000389 (FromWidth == ToWidth && FromSigned != ToSigned) ||
390 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 // Not all values of FromType can be represented in ToType.
392 llvm::APSInt InitializerValue;
393 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000394 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
395 // Such conversions on variables are always narrowing.
396 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000397 }
398 bool Narrowing = false;
399 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000400 // Negative -> unsigned is narrowing. Otherwise, more bits is never
401 // narrowing.
402 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000403 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000404 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000405 // Add a bit to the InitializerValue so we don't have to worry about
406 // signed vs. unsigned comparisons.
407 InitializerValue = InitializerValue.extend(
408 InitializerValue.getBitWidth() + 1);
409 // Convert the initializer to and from the target width and signed-ness.
410 llvm::APSInt ConvertedValue = InitializerValue;
411 ConvertedValue = ConvertedValue.trunc(ToWidth);
412 ConvertedValue.setIsSigned(ToSigned);
413 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
414 ConvertedValue.setIsSigned(InitializerValue.isSigned());
415 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 if (ConvertedValue != InitializerValue)
417 Narrowing = true;
418 }
419 if (Narrowing) {
420 ConstantType = Initializer->getType();
421 ConstantValue = APValue(InitializerValue);
422 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000423 }
424 }
425 return NK_Not_Narrowing;
426 }
427
428 default:
429 // Other kinds of conversions are not narrowings.
430 return NK_Not_Narrowing;
431 }
432}
433
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000434/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000435/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000436LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438 bool PrintedSomething = false;
439 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 PrintedSomething = true;
442 }
443
444 if (Second != ICK_Identity) {
445 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000446 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449
450 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000453 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000454 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (Third != ICK_Identity) {
461 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000462 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000464 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 PrintedSomething = true;
466 }
467
468 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000469 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000470 }
471}
472
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000475void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000478 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000481 if (ConversionFunction)
482 OS << '\'' << *ConversionFunction << '\'';
483 else
484 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000486 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000487 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 }
489}
490
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000491/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000493void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000495 if (isStdInitializerListElement())
496 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 switch (ConversionKind) {
498 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 break;
502 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000503 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000504 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 break;
506 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 break;
John McCall0d1da222010-01-12 00:44:57 +0000509 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000510 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000511 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 break;
515 }
516
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000517 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518}
519
John McCall0d1da222010-01-12 00:44:57 +0000520void AmbiguousConversionSequence::construct() {
521 new (&conversions()) ConversionSet();
522}
523
524void AmbiguousConversionSequence::destruct() {
525 conversions().~ConversionSet();
526}
527
528void
529AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
530 FromTypePtr = O.FromTypePtr;
531 ToTypePtr = O.ToTypePtr;
532 new (&conversions()) ConversionSet(O.conversions());
533}
534
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000536 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 // template argument information.
538 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000539 TemplateArgument FirstArg;
540 TemplateArgument SecondArg;
541 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000542 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000543 // template parameter and template argument information.
544 struct DFIParamWithArguments : DFIArguments {
545 TemplateParameter Param;
546 };
Richard Smith9b534542015-12-31 02:02:54 +0000547 // Structure used by DeductionFailureInfo to store template argument
548 // information and the index of the problematic call argument.
549 struct DFIDeducedMismatchArgs : DFIArguments {
550 TemplateArgumentList *TemplateArgs;
551 unsigned CallArgIndex;
552 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000553}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000557DeductionFailureInfo
558clang::MakeDeductionFailureInfo(ASTContext &Context,
559 Sema::TemplateDeductionResult TDK,
560 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000563 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 switch (TDK) {
565 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000566 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000568 case Sema::TDK_TooManyArguments:
569 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000570 case Sema::TDK_MiscellaneousDeductionFailure:
571 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000575 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = Info.Param.getOpaqueValue();
577 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
Richard Smith9b534542015-12-31 02:02:54 +0000579 case Sema::TDK_DeducedMismatch: {
580 // FIXME: Should allocate from normal heap so that we can free this later.
581 auto *Saved = new (Context) DFIDeducedMismatchArgs;
582 Saved->FirstArg = Info.FirstArg;
583 Saved->SecondArg = Info.SecondArg;
584 Saved->TemplateArgs = Info.take();
585 Saved->CallArgIndex = Info.CallArgIndex;
586 Result.Data = Saved;
587 break;
588 }
589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000625 return Result;
626}
John McCall0d1da222010-01-12 00:44:57 +0000627
Larisse Voufo98b20f12013-07-19 23:00:19 +0000628void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000631 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 case Sema::TDK_InstantiationDepth:
633 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000636 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000637 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000641 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000642 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000643 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000644 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000645 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000647
648 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000649 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000650 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
652 Diag->~PartialDiagnosticAt();
653 HasDiagnostic = false;
654 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000655 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000658 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 break;
660 }
661}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Larisse Voufo98b20f12013-07-19 23:00:19 +0000663PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000666 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000667}
668
Larisse Voufo98b20f12013-07-19 23:00:19 +0000669TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
671 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000672 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000673 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000674 case Sema::TDK_TooManyArguments:
675 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000676 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000677 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000689
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Larisse Voufo98b20f12013-07-19 23:00:19 +0000698TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000700 case Sema::TDK_Success:
701 case Sema::TDK_Invalid:
702 case Sema::TDK_InstantiationDepth:
703 case Sema::TDK_TooManyArguments:
704 case Sema::TDK_TooFewArguments:
705 case Sema::TDK_Incomplete:
706 case Sema::TDK_InvalidExplicitArguments:
707 case Sema::TDK_Inconsistent:
708 case Sema::TDK_Underqualified:
709 case Sema::TDK_NonDeducedMismatch:
710 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000712
Richard Smith9b534542015-12-31 02:02:54 +0000713 case Sema::TDK_DeducedMismatch:
714 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
715
Richard Smith44ecdbd2013-01-31 05:19:49 +0000716 case Sema::TDK_SubstitutionFailure:
717 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000718
Richard Smith44ecdbd2013-01-31 05:19:49 +0000719 // Unhandled
720 case Sema::TDK_MiscellaneousDeductionFailure:
721 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000722 }
723
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000725}
726
Larisse Voufo98b20f12013-07-19 23:00:19 +0000727const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
729 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000730 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 case Sema::TDK_InstantiationDepth:
732 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000733 case Sema::TDK_TooManyArguments:
734 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000735 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000736 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000737 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000738 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000740 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000741 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000742 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000743 case Sema::TDK_NonDeducedMismatch:
744 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745
Douglas Gregor461761d2010-05-08 18:20:53 +0000746 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 break;
749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000750
Craig Topperc3ec1492014-05-26 06:22:03 +0000751 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000753
Larisse Voufo98b20f12013-07-19 23:00:19 +0000754const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
756 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000757 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000758 case Sema::TDK_InstantiationDepth:
759 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000760 case Sema::TDK_TooManyArguments:
761 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000762 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000763 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000764 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000765 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000768 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000769 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_NonDeducedMismatch:
771 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772
Douglas Gregor461761d2010-05-08 18:20:53 +0000773 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000774 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775 break;
776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Craig Topperc3ec1492014-05-26 06:22:03 +0000778 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779}
780
Larisse Voufo98b20f12013-07-19 23:00:19 +0000781Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000782 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
783 Sema::TDK_FailedOverloadResolution)
784 return static_cast<Expr*>(Data);
785
Craig Topperc3ec1492014-05-26 06:22:03 +0000786 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000787}
788
Richard Smith9b534542015-12-31 02:02:54 +0000789llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
790 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
791 Sema::TDK_DeducedMismatch)
792 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
793
794 return llvm::None;
795}
796
Benjamin Kramer97e59492012-10-09 15:52:25 +0000797void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000798 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000799 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
800 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000801 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
802 i->DeductionFailure.Destroy();
803 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000804}
805
806void OverloadCandidateSet::clear() {
807 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000808 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000809 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000810 Functions.clear();
811}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
John McCall4124c492011-10-17 18:40:02 +0000813namespace {
814 class UnbridgedCastsSet {
815 struct Entry {
816 Expr **Addr;
817 Expr *Saved;
818 };
819 SmallVector<Entry, 2> Entries;
820
821 public:
822 void save(Sema &S, Expr *&E) {
823 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
824 Entry entry = { &E, E };
825 Entries.push_back(entry);
826 E = S.stripARCUnbridgedCast(E);
827 }
828
829 void restore() {
830 for (SmallVectorImpl<Entry>::iterator
831 i = Entries.begin(), e = Entries.end(); i != e; ++i)
832 *i->Addr = i->Saved;
833 }
834 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000835}
John McCall4124c492011-10-17 18:40:02 +0000836
837/// checkPlaceholderForOverload - Do any interesting placeholder-like
838/// preprocessing on the given expression.
839///
840/// \param unbridgedCasts a collection to which to add unbridged casts;
841/// without this, they will be immediately diagnosed as errors
842///
843/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000844static bool
845checkPlaceholderForOverload(Sema &S, Expr *&E,
846 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000847 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
848 // We can't handle overloaded expressions here because overload
849 // resolution might reasonably tweak them.
850 if (placeholder->getKind() == BuiltinType::Overload) return false;
851
852 // If the context potentially accepts unbridged ARC casts, strip
853 // the unbridged cast and add it to the collection for later restoration.
854 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
855 unbridgedCasts) {
856 unbridgedCasts->save(S, E);
857 return false;
858 }
859
860 // Go ahead and check everything else.
861 ExprResult result = S.CheckPlaceholderExpr(E);
862 if (result.isInvalid())
863 return true;
864
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000865 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000866 return false;
867 }
868
869 // Nothing to do.
870 return false;
871}
872
873/// checkArgPlaceholdersForOverload - Check a set of call operands for
874/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000875static bool checkArgPlaceholdersForOverload(Sema &S,
876 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000877 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000878 for (unsigned i = 0, e = Args.size(); i != e; ++i)
879 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000880 return true;
881
882 return false;
883}
884
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000885// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000886// overload of the declarations in Old. This routine returns false if
887// New and Old cannot be overloaded, e.g., if New has the same
888// signature as some function in Old (C++ 1.3.10) or if the Old
889// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000890// it does return false, MatchedDecl will point to the decl that New
891// cannot be overloaded with. This decl may be a UsingShadowDecl on
892// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000893//
894// Example: Given the following input:
895//
896// void f(int, float); // #1
897// void f(int, int); // #2
898// int f(int, int); // #3
899//
900// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000901// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000902//
John McCall3d988d92009-12-02 08:47:38 +0000903// When we process #2, Old contains only the FunctionDecl for #1. By
904// comparing the parameter types, we see that #1 and #2 are overloaded
905// (since they have different signatures), so this routine returns
906// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000907//
John McCall3d988d92009-12-02 08:47:38 +0000908// When we process #3, Old is an overload set containing #1 and #2. We
909// compare the signatures of #3 to #1 (they're overloaded, so we do
910// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
911// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912// signature), IsOverload returns false and MatchedDecl will be set to
913// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000914//
915// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
916// into a class by a using declaration. The rules for whether to hide
917// shadow declarations ignore some properties which otherwise figure
918// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000919Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000920Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
921 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000922 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000923 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000924 NamedDecl *OldD = *I;
925
926 bool OldIsUsingDecl = false;
927 if (isa<UsingShadowDecl>(OldD)) {
928 OldIsUsingDecl = true;
929
930 // We can always introduce two using declarations into the same
931 // context, even if they have identical signatures.
932 if (NewIsUsingDecl) continue;
933
934 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
935 }
936
Richard Smithf091e122015-09-15 01:28:55 +0000937 // A using-declaration does not conflict with another declaration
938 // if one of them is hidden.
939 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
940 continue;
941
John McCalle9cccd82010-06-16 08:42:20 +0000942 // If either declaration was introduced by a using declaration,
943 // we'll need to use slightly different rules for matching.
944 // Essentially, these rules are the normal rules, except that
945 // function templates hide function templates with different
946 // return types or template parameter lists.
947 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000948 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
949 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000950
Alp Tokera2794f92014-01-22 07:29:52 +0000951 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000952 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
953 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
954 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
955 continue;
956 }
957
Alp Tokera2794f92014-01-22 07:29:52 +0000958 if (!isa<FunctionTemplateDecl>(OldD) &&
959 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000960 continue;
961
John McCalldaa3d6b2009-12-09 03:35:25 +0000962 Match = *I;
963 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000964 }
John McCalla8987a2942010-11-10 03:01:53 +0000965 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000966 // We can overload with these, which can show up when doing
967 // redeclaration checks for UsingDecls.
968 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000969 } else if (isa<TagDecl>(OldD)) {
970 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000971 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
972 // Optimistically assume that an unresolved using decl will
973 // overload; if it doesn't, we'll have to diagnose during
974 // template instantiation.
975 } else {
John McCall1f82f242009-11-18 22:49:29 +0000976 // (C++ 13p1):
977 // Only function declarations can be overloaded; object and type
978 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000979 Match = *I;
980 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000981 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000982 }
John McCall1f82f242009-11-18 22:49:29 +0000983
John McCalldaa3d6b2009-12-09 03:35:25 +0000984 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000985}
986
Richard Smithac974a32013-06-30 09:48:50 +0000987bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
988 bool UseUsingDeclRules) {
989 // C++ [basic.start.main]p2: This function shall not be overloaded.
990 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000991 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000992
David Majnemerc729b0b2013-09-16 22:44:20 +0000993 // MSVCRT user defined entry points cannot be overloaded.
994 if (New->isMSVCRTEntryPoint())
995 return false;
996
John McCall1f82f242009-11-18 22:49:29 +0000997 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
998 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
999
1000 // C++ [temp.fct]p2:
1001 // A function template can be overloaded with other function templates
1002 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001003 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001004 return true;
1005
1006 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001007 QualType OldQType = Context.getCanonicalType(Old->getType());
1008 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001009
1010 // Compare the signatures (C++ 1.3.10) of the two functions to
1011 // determine whether they are overloads. If we find any mismatch
1012 // in the signature, they are overloads.
1013
1014 // If either of these functions is a K&R-style function (no
1015 // prototype), then we consider them to have matching signatures.
1016 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1017 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1018 return false;
1019
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001020 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1021 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001022
1023 // The signature of a function includes the types of its
1024 // parameters (C++ 1.3.10), which includes the presence or absence
1025 // of the ellipsis; see C++ DR 357).
1026 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001027 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001028 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001029 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001030 return true;
1031
1032 // C++ [temp.over.link]p4:
1033 // The signature of a function template consists of its function
1034 // signature, its return type and its template parameter list. The names
1035 // of the template parameters are significant only for establishing the
1036 // relationship between the template parameters and the rest of the
1037 // signature.
1038 //
1039 // We check the return type and template parameter lists for function
1040 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001041 //
1042 // However, we don't consider either of these when deciding whether
1043 // a member introduced by a shadow declaration is hidden.
1044 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001045 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1046 OldTemplate->getTemplateParameters(),
1047 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001048 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001049 return true;
1050
1051 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001052 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001053 //
1054 // As part of this, also check whether one of the member functions
1055 // is static, in which case they are not overloads (C++
1056 // 13.1p2). While not part of the definition of the signature,
1057 // this check is important to determine whether these functions
1058 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001059 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1060 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001061 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001062 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1063 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1064 if (!UseUsingDeclRules &&
1065 (OldMethod->getRefQualifier() == RQ_None ||
1066 NewMethod->getRefQualifier() == RQ_None)) {
1067 // C++0x [over.load]p2:
1068 // - Member function declarations with the same name and the same
1069 // parameter-type-list as well as member function template
1070 // declarations with the same name, the same parameter-type-list, and
1071 // the same template parameter lists cannot be overloaded if any of
1072 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001073 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001074 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001075 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001076 }
1077 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079
Richard Smith574f4f62013-01-14 05:37:29 +00001080 // We may not have applied the implicit const for a constexpr member
1081 // function yet (because we haven't yet resolved whether this is a static
1082 // or non-static member function). Add it now, on the assumption that this
1083 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001084 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001085 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001086 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001087 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001088 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001089
1090 // We do not allow overloading based off of '__restrict'.
1091 OldQuals &= ~Qualifiers::Restrict;
1092 NewQuals &= ~Qualifiers::Restrict;
1093 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001094 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001097 // Though pass_object_size is placed on parameters and takes an argument, we
1098 // consider it to be a function-level modifier for the sake of function
1099 // identity. Either the function has one or more parameters with
1100 // pass_object_size or it doesn't.
1101 if (functionHasPassObjectSizeParams(New) !=
1102 functionHasPassObjectSizeParams(Old))
1103 return true;
1104
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001105 // enable_if attributes are an order-sensitive part of the signature.
1106 for (specific_attr_iterator<EnableIfAttr>
1107 NewI = New->specific_attr_begin<EnableIfAttr>(),
1108 NewE = New->specific_attr_end<EnableIfAttr>(),
1109 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1110 OldE = Old->specific_attr_end<EnableIfAttr>();
1111 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1112 if (NewI == NewE || OldI == OldE)
1113 return true;
1114 llvm::FoldingSetNodeID NewID, OldID;
1115 NewI->getCond()->Profile(NewID, Context, true);
1116 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001117 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001118 return true;
1119 }
1120
Artem Belevich94a55e82015-09-22 17:22:59 +00001121 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1122 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1123 OldTarget = IdentifyCUDATarget(Old);
1124 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1125 return false;
1126
1127 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1128
1129 // Don't allow mixing of HD with other kinds. This guarantees that
1130 // we have only one viable function with this signature on any
1131 // side of CUDA compilation .
1132 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1133 return false;
1134
1135 // Allow overloading of functions with same signature, but
1136 // different CUDA target attributes.
1137 return NewTarget != OldTarget;
1138 }
1139
John McCall1f82f242009-11-18 22:49:29 +00001140 // The signatures match; this is not an overload.
1141 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142}
1143
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001144/// \brief Checks availability of the function depending on the current
1145/// function context. Inside an unavailable function, unavailability is ignored.
1146///
1147/// \returns true if \arg FD is unavailable and current context is inside
1148/// an available function, false otherwise.
1149bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1150 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1151}
1152
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001153/// \brief Tries a user-defined conversion from From to ToType.
1154///
1155/// Produces an implicit conversion sequence for when a standard conversion
1156/// is not an option. See TryImplicitConversion for more information.
1157static ImplicitConversionSequence
1158TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1159 bool SuppressUserConversions,
1160 bool AllowExplicit,
1161 bool InOverloadResolution,
1162 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001163 bool AllowObjCWritebackConversion,
1164 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001165 ImplicitConversionSequence ICS;
1166
1167 if (SuppressUserConversions) {
1168 // We're not in the case above, so there is no conversion that
1169 // we can perform.
1170 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1171 return ICS;
1172 }
1173
1174 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001175 OverloadCandidateSet Conversions(From->getExprLoc(),
1176 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001177 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1178 Conversions, AllowExplicit,
1179 AllowObjCConversionOnExplicit)) {
1180 case OR_Success:
1181 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001182 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001183 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001184 // C++ [over.ics.user]p4:
1185 // A conversion of an expression of class type to the same class
1186 // type is given Exact Match rank, and a conversion of an
1187 // expression of class type to a base class of that type is
1188 // given Conversion rank, in spite of the fact that a copy
1189 // constructor (i.e., a user-defined conversion function) is
1190 // called for those cases.
1191 if (CXXConstructorDecl *Constructor
1192 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1193 QualType FromCanon
1194 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1195 QualType ToCanon
1196 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1197 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001198 (FromCanon == ToCanon ||
1199 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001200 // Turn this into a "standard" conversion sequence, so that it
1201 // gets ranked with standard conversion sequences.
1202 ICS.setStandard();
1203 ICS.Standard.setAsIdentityConversion();
1204 ICS.Standard.setFromType(From->getType());
1205 ICS.Standard.setAllToTypes(ToType);
1206 ICS.Standard.CopyConstructor = Constructor;
1207 if (ToCanon != FromCanon)
1208 ICS.Standard.Second = ICK_Derived_To_Base;
1209 }
1210 }
Richard Smith48372b62015-01-27 03:30:40 +00001211 break;
1212
1213 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001214 ICS.setAmbiguous();
1215 ICS.Ambiguous.setFromType(From->getType());
1216 ICS.Ambiguous.setToType(ToType);
1217 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1218 Cand != Conversions.end(); ++Cand)
1219 if (Cand->Viable)
1220 ICS.Ambiguous.addConversion(Cand->Function);
1221 break;
Richard Smith48372b62015-01-27 03:30:40 +00001222
1223 // Fall through.
1224 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001226 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001227 }
1228
1229 return ICS;
1230}
1231
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001232/// TryImplicitConversion - Attempt to perform an implicit conversion
1233/// from the given expression (Expr) to the given type (ToType). This
1234/// function returns an implicit conversion sequence that can be used
1235/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236///
1237/// void f(float f);
1238/// void g(int i) { f(i); }
1239///
1240/// this routine would produce an implicit conversion sequence to
1241/// describe the initialization of f from i, which will be a standard
1242/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1243/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1244//
1245/// Note that this routine only determines how the conversion can be
1246/// performed; it does not actually perform the conversion. As such,
1247/// it will not produce any diagnostics if no conversion is available,
1248/// but will instead return an implicit conversion sequence of kind
1249/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001250///
1251/// If @p SuppressUserConversions, then user-defined conversions are
1252/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001253/// If @p AllowExplicit, then explicit user-defined conversions are
1254/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001255///
1256/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1257/// writeback conversion, which allows __autoreleasing id* parameters to
1258/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001259static ImplicitConversionSequence
1260TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1261 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001263 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001264 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001265 bool AllowObjCWritebackConversion,
1266 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001268 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001269 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001270 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001271 return ICS;
1272 }
1273
David Blaikiebbafb8a2012-03-11 07:00:24 +00001274 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001276 return ICS;
1277 }
1278
Douglas Gregor836a7e82010-08-11 02:15:33 +00001279 // C++ [over.ics.user]p4:
1280 // A conversion of an expression of class type to the same class
1281 // type is given Exact Match rank, and a conversion of an
1282 // expression of class type to a base class of that type is
1283 // given Conversion rank, in spite of the fact that a copy/move
1284 // constructor (i.e., a user-defined conversion function) is
1285 // called for those cases.
1286 QualType FromType = From->getType();
1287 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001288 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001289 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001290 ICS.setStandard();
1291 ICS.Standard.setAsIdentityConversion();
1292 ICS.Standard.setFromType(FromType);
1293 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001294
Douglas Gregor5ab11652010-04-17 22:01:05 +00001295 // We don't actually check at this point whether there is a valid
1296 // copy/move constructor, since overloading just assumes that it
1297 // exists. When we actually perform initialization, we'll find the
1298 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001299 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001300
Douglas Gregor5ab11652010-04-17 22:01:05 +00001301 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001302 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001303 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
Douglas Gregor836a7e82010-08-11 02:15:33 +00001305 return ICS;
1306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001307
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001308 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1309 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001310 AllowObjCWritebackConversion,
1311 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001312}
1313
John McCall31168b02011-06-15 23:02:42 +00001314ImplicitConversionSequence
1315Sema::TryImplicitConversion(Expr *From, QualType ToType,
1316 bool SuppressUserConversions,
1317 bool AllowExplicit,
1318 bool InOverloadResolution,
1319 bool CStyle,
1320 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001321 return ::TryImplicitConversion(*this, From, ToType,
1322 SuppressUserConversions, AllowExplicit,
1323 InOverloadResolution, CStyle,
1324 AllowObjCWritebackConversion,
1325 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001326}
1327
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001328/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001329/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001330/// converted expression. Flavor is the kind of conversion we're
1331/// performing, used in the error message. If @p AllowExplicit,
1332/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001333ExprResult
1334Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001335 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001336 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001337 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001338}
1339
John Wiegley01296292011-04-08 18:41:53 +00001340ExprResult
1341Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001342 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001343 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001344 if (checkPlaceholderForOverload(*this, From))
1345 return ExprError();
1346
John McCall31168b02011-06-15 23:02:42 +00001347 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1348 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001349 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001350 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001351 if (getLangOpts().ObjC1)
1352 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1353 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001354 ICS = ::TryImplicitConversion(*this, From, ToType,
1355 /*SuppressUserConversions=*/false,
1356 AllowExplicit,
1357 /*InOverloadResolution=*/false,
1358 /*CStyle=*/false,
1359 AllowObjCWritebackConversion,
1360 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001361 return PerformImplicitConversion(From, ToType, ICS, Action);
1362}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
1364/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001365/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001366bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1367 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001368 if (Context.hasSameUnqualifiedType(FromType, ToType))
1369 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370
John McCall991eb4b2010-12-21 00:44:39 +00001371 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1372 // where F adds one of the following at most once:
1373 // - a pointer
1374 // - a member pointer
1375 // - a block pointer
1376 CanQualType CanTo = Context.getCanonicalType(ToType);
1377 CanQualType CanFrom = Context.getCanonicalType(FromType);
1378 Type::TypeClass TyClass = CanTo->getTypeClass();
1379 if (TyClass != CanFrom->getTypeClass()) return false;
1380 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1381 if (TyClass == Type::Pointer) {
1382 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1383 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1384 } else if (TyClass == Type::BlockPointer) {
1385 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1386 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1387 } else if (TyClass == Type::MemberPointer) {
1388 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1389 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1390 } else {
1391 return false;
1392 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001393
John McCall991eb4b2010-12-21 00:44:39 +00001394 TyClass = CanTo->getTypeClass();
1395 if (TyClass != CanFrom->getTypeClass()) return false;
1396 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1397 return false;
1398 }
1399
1400 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1401 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1402 if (!EInfo.getNoReturn()) return false;
1403
1404 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1405 assert(QualType(FromFn, 0).isCanonical());
1406 if (QualType(FromFn, 0) != CanTo) return false;
1407
1408 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001409 return true;
1410}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001411
Douglas Gregor46188682010-05-18 22:42:18 +00001412/// \brief Determine whether the conversion from FromType to ToType is a valid
1413/// vector conversion.
1414///
1415/// \param ICK Will be set to the vector conversion kind, if this is a vector
1416/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001417static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001419 // We need at least one of these types to be a vector type to have a vector
1420 // conversion.
1421 if (!ToType->isVectorType() && !FromType->isVectorType())
1422 return false;
1423
1424 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001425 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001426 return false;
1427
1428 // There are no conversions between extended vector types, only identity.
1429 if (ToType->isExtVectorType()) {
1430 // There are no conversions between extended vector types other than the
1431 // identity conversion.
1432 if (FromType->isExtVectorType())
1433 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor46188682010-05-18 22:42:18 +00001435 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001436 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001437 ICK = ICK_Vector_Splat;
1438 return true;
1439 }
1440 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001441
1442 // We can perform the conversion between vector types in the following cases:
1443 // 1)vector types are equivalent AltiVec and GCC vector types
1444 // 2)lax vector conversions are permitted and the vector types are of the
1445 // same size
1446 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001447 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1448 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001449 ICK = ICK_Vector_Conversion;
1450 return true;
1451 }
Douglas Gregor46188682010-05-18 22:42:18 +00001452 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001453
Douglas Gregor46188682010-05-18 22:42:18 +00001454 return false;
1455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001457static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1458 bool InOverloadResolution,
1459 StandardConversionSequence &SCS,
1460 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001461
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462/// IsStandardConversion - Determines whether there is a standard
1463/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1464/// expression From to the type ToType. Standard conversion sequences
1465/// only consider non-class types; for conversions that involve class
1466/// types, use TryImplicitConversion. If a conversion exists, SCS will
1467/// contain the standard conversion sequence required to perform this
1468/// conversion and this routine will return true. Otherwise, this
1469/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001470static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1471 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001472 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001473 bool CStyle,
1474 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001475 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001477 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001478 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001479 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001480 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001481 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001482
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001483 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001484 // abort early. When overloading in C, however, we do permit them.
1485 if (S.getLangOpts().CPlusPlus &&
1486 (FromType->isRecordType() || ToType->isRecordType()))
1487 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001488
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001489 // The first conversion can be an lvalue-to-rvalue conversion,
1490 // array-to-pointer conversion, or function-to-pointer conversion
1491 // (C++ 4p1).
1492
John McCall5c32be02010-08-24 20:38:10 +00001493 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001494 DeclAccessPair AccessPair;
1495 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001497 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001498 // We were able to resolve the address of the overloaded function,
1499 // so we can convert to the type of that function.
1500 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001501 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001502
1503 // we can sometimes resolve &foo<int> regardless of ToType, so check
1504 // if the type matches (identity) or we are converting to bool
1505 if (!S.Context.hasSameUnqualifiedType(
1506 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1507 QualType resultTy;
1508 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001509 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001510 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1511 // otherwise, only a boolean conversion is standard
1512 if (!ToType->isBooleanType())
1513 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515
Chandler Carruthffce2452011-03-29 08:08:18 +00001516 // Check if the "from" expression is taking the address of an overloaded
1517 // function and recompute the FromType accordingly. Take advantage of the
1518 // fact that non-static member functions *must* have such an address-of
1519 // expression.
1520 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1521 if (Method && !Method->isStatic()) {
1522 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1523 "Non-unary operator on non-static member address");
1524 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1525 == UO_AddrOf &&
1526 "Non-address-of operator on non-static member address");
1527 const Type *ClassType
1528 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1529 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001530 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1531 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1532 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001533 "Non-address-of operator for overloaded function expression");
1534 FromType = S.Context.getPointerType(FromType);
1535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001536
Douglas Gregor980fb162010-04-29 18:24:40 +00001537 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001538 assert(S.Context.hasSameType(
1539 FromType,
1540 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001541 } else {
1542 return false;
1543 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001544 }
John McCall154a2fd2011-08-30 00:57:29 +00001545 // Lvalue-to-rvalue conversion (C++11 4.1):
1546 // A glvalue (3.10) of a non-function, non-array type T can
1547 // be converted to a prvalue.
1548 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001549 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001550 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001551 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553
Douglas Gregorc79862f2012-04-12 17:51:55 +00001554 // C11 6.3.2.1p2:
1555 // ... if the lvalue has atomic type, the value has the non-atomic version
1556 // of the type of the lvalue ...
1557 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1558 FromType = Atomic->getValueType();
1559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560 // If T is a non-class type, the type of the rvalue is the
1561 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001562 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1563 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 } else if (FromType->isArrayType()) {
1566 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001567 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568
1569 // An lvalue or rvalue of type "array of N T" or "array of unknown
1570 // bound of T" can be converted to an rvalue of type "pointer to
1571 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001572 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573
John McCall5c32be02010-08-24 20:38:10 +00001574 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001575 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001576 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577
1578 // For the purpose of ranking in overload resolution
1579 // (13.3.3.1.1), this conversion is considered an
1580 // array-to-pointer conversion followed by a qualification
1581 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001582 SCS.Second = ICK_Identity;
1583 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001584 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001585 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 }
John McCall086a4642010-11-24 05:12:34 +00001588 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001592 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1593 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1594 if (!S.checkAddressOfFunctionIsAvailable(FD))
1595 return false;
1596
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001597 // An lvalue of function type T can be converted to an rvalue of
1598 // type "pointer to T." The result is a pointer to the
1599 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001600 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001601 } else {
1602 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001603 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001604 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001605 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001606
1607 // The second conversion can be an integral promotion, floating
1608 // point promotion, integral conversion, floating point conversion,
1609 // floating-integral conversion, pointer conversion,
1610 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001611 // For overloading in C, this can also be a "compatible-type"
1612 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001613 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001614 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001615 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 // The unqualified versions of the types are the same: there's no
1617 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001619 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001620 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001622 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001623 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001624 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001625 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001627 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001628 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001629 SCS.Second = ICK_Complex_Promotion;
1630 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001631 } else if (ToType->isBooleanType() &&
1632 (FromType->isArithmeticType() ||
1633 FromType->isAnyPointerType() ||
1634 FromType->isBlockPointerType() ||
1635 FromType->isMemberPointerType() ||
1636 FromType->isNullPtrType())) {
1637 // Boolean conversions (C++ 4.12).
1638 SCS.Second = ICK_Boolean_Conversion;
1639 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001640 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001641 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001642 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001645 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001646 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001647 SCS.Second = ICK_Complex_Conversion;
1648 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001649 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1650 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001651 // Complex-real conversions (C99 6.3.1.7)
1652 SCS.Second = ICK_Complex_Real;
1653 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001654 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001655 // Floating point conversions (C++ 4.8).
1656 SCS.Second = ICK_Floating_Conversion;
1657 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001659 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001660 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001661 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001662 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001663 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001665 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001666 SCS.Second = ICK_Block_Pointer_Conversion;
1667 } else if (AllowObjCWritebackConversion &&
1668 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1669 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001670 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1671 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001672 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001674 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001675 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001677 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001678 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001679 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001680 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001681 SCS.Second = SecondICK;
1682 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001683 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001684 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001685 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001686 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001687 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001688 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001689 // Treat a conversion that strips "noreturn" as an identity conversion.
1690 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001691 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1692 InOverloadResolution,
1693 SCS, CStyle)) {
1694 SCS.Second = ICK_TransparentUnionConversion;
1695 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001696 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1697 CStyle)) {
1698 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001699 // appropriately.
1700 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001701 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001702 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001703 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001704 SCS.Second = ICK_Zero_Event_Conversion;
1705 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 } else {
1707 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001708 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001710 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001712 QualType CanonFrom;
1713 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001715 bool ObjCLifetimeConversion;
1716 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1717 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001718 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001719 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001721 CanonFrom = S.Context.getCanonicalType(FromType);
1722 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723 } else {
1724 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001725 SCS.Third = ICK_Identity;
1726
Mike Stump11289f42009-09-09 15:08:12 +00001727 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001728 // [...] Any difference in top-level cv-qualification is
1729 // subsumed by the initialization itself and does not constitute
1730 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001731 CanonFrom = S.Context.getCanonicalType(FromType);
1732 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001734 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001735 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001736 FromType = ToType;
1737 CanonFrom = CanonTo;
1738 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001740 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001741
George Burgess IV45461812015-10-11 20:13:20 +00001742 if (CanonFrom == CanonTo)
1743 return true;
1744
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001745 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001746 // this is a bad conversion sequence, unless we're resolving an overload in C.
1747 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001748 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749
George Burgess IV45461812015-10-11 20:13:20 +00001750 ExprResult ER = ExprResult{From};
1751 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1752 /*Diagnose=*/false,
1753 /*DiagnoseCFAudited=*/false,
1754 /*ConvertRHS=*/false);
1755 if (Conv != Sema::Compatible)
1756 return false;
1757
1758 SCS.setAllToTypes(ToType);
1759 // We need to set all three because we want this conversion to rank terribly,
1760 // and we don't know what conversions it may overlap with.
1761 SCS.First = ICK_C_Only_Conversion;
1762 SCS.Second = ICK_C_Only_Conversion;
1763 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001764 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001765}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001766
1767static bool
1768IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1769 QualType &ToType,
1770 bool InOverloadResolution,
1771 StandardConversionSequence &SCS,
1772 bool CStyle) {
1773
1774 const RecordType *UT = ToType->getAsUnionType();
1775 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1776 return false;
1777 // The field to initialize within the transparent union.
1778 RecordDecl *UD = UT->getDecl();
1779 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001780 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001781 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1782 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001783 ToType = it->getType();
1784 return true;
1785 }
1786 }
1787 return false;
1788}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789
1790/// IsIntegralPromotion - Determines whether the conversion from the
1791/// expression From (whose potentially-adjusted type is FromType) to
1792/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1793/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001794bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001795 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001796 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001797 if (!To) {
1798 return false;
1799 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800
1801 // An rvalue of type char, signed char, unsigned char, short int, or
1802 // unsigned short int can be converted to an rvalue of type int if
1803 // int can represent all the values of the source type; otherwise,
1804 // the source rvalue can be converted to an rvalue of type unsigned
1805 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001806 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1807 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 if (// We can promote any signed, promotable integer type to an int
1809 (FromType->isSignedIntegerType() ||
1810 // We can promote any unsigned integer type whose size is
1811 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001812 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001813 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001814 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001815 }
1816
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 return To->getKind() == BuiltinType::UInt;
1818 }
1819
Richard Smithb9c5a602012-09-13 21:18:54 +00001820 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 // A prvalue of an unscoped enumeration type whose underlying type is not
1822 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1823 // following types that can represent all the values of the enumeration
1824 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1825 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001826 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001827 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001828 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001829 // with lowest integer conversion rank (4.13) greater than the rank of long
1830 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001831 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001832 // C++11 [conv.prom]p4:
1833 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1834 // can be converted to a prvalue of its underlying type. Moreover, if
1835 // integral promotion can be applied to its underlying type, a prvalue of an
1836 // unscoped enumeration type whose underlying type is fixed can also be
1837 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001838 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1839 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1840 // provided for a scoped enumeration.
1841 if (FromEnumType->getDecl()->isScoped())
1842 return false;
1843
Richard Smithb9c5a602012-09-13 21:18:54 +00001844 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001845 // even if that's not the promoted type. Note that the check for promoting
1846 // the underlying type is based on the type alone, and does not consider
1847 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001848 if (FromEnumType->getDecl()->isFixed()) {
1849 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1850 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001851 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001852 }
1853
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001854 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001856 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001857 return Context.hasSameUnqualifiedType(
1858 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001859 }
John McCall56774992009-12-09 09:09:27 +00001860
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001861 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1863 // to an rvalue a prvalue of the first of the following types that can
1864 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001865 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001867 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001869 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001871 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001872 // Determine whether the type we're converting from is signed or
1873 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001874 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001875 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001877 // The types we'll try to promote to, in the appropriate
1878 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001879 QualType PromoteTypes[6] = {
1880 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001881 Context.LongTy, Context.UnsignedLongTy ,
1882 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001884 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001885 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1886 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001887 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001888 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1889 // We found the type that we can promote to. If this is the
1890 // type we wanted, we have a promotion. Otherwise, no
1891 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001892 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001893 }
1894 }
1895 }
1896
1897 // An rvalue for an integral bit-field (9.6) can be converted to an
1898 // rvalue of type int if int can represent all the values of the
1899 // bit-field; otherwise, it can be converted to unsigned int if
1900 // unsigned int can represent all the values of the bit-field. If
1901 // the bit-field is larger yet, no integral promotion applies to
1902 // it. If the bit-field has an enumerated type, it is treated as any
1903 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001904 // FIXME: We should delay checking of bit-fields until we actually perform the
1905 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001906 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001907 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001908 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001909 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001910 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001911 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001912 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001914 // Are we promoting to an int from a bitfield that fits in an int?
1915 if (BitWidth < ToSize ||
1916 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1917 return To->getKind() == BuiltinType::Int;
1918 }
Mike Stump11289f42009-09-09 15:08:12 +00001919
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001920 // Are we promoting to an unsigned int from an unsigned bitfield
1921 // that fits into an unsigned int?
1922 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1923 return To->getKind() == BuiltinType::UInt;
1924 }
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001926 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001927 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001928 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001929 }
Mike Stump11289f42009-09-09 15:08:12 +00001930
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001931 // An rvalue of type bool can be converted to an rvalue of type int,
1932 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001933 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001935 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936
1937 return false;
1938}
1939
1940/// IsFloatingPointPromotion - Determines whether the conversion from
1941/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1942/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001943bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001944 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1945 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001946 /// An rvalue of type float can be converted to an rvalue of type
1947 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001948 if (FromBuiltin->getKind() == BuiltinType::Float &&
1949 ToBuiltin->getKind() == BuiltinType::Double)
1950 return true;
1951
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001952 // C99 6.3.1.5p1:
1953 // When a float is promoted to double or long double, or a
1954 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001955 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001956 (FromBuiltin->getKind() == BuiltinType::Float ||
1957 FromBuiltin->getKind() == BuiltinType::Double) &&
1958 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1959 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001960
1961 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001962 if (!getLangOpts().NativeHalfType &&
1963 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001964 ToBuiltin->getKind() == BuiltinType::Float)
1965 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001966 }
1967
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 return false;
1969}
1970
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001971/// \brief Determine if a conversion is a complex promotion.
1972///
1973/// A complex promotion is defined as a complex -> complex conversion
1974/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001975/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001976bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001977 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001978 if (!FromComplex)
1979 return false;
1980
John McCall9dd450b2009-09-21 23:43:11 +00001981 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001982 if (!ToComplex)
1983 return false;
1984
1985 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001986 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001987 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001988 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001989}
1990
Douglas Gregor237f96c2008-11-26 23:31:11 +00001991/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1992/// the pointer type FromPtr to a pointer to type ToPointee, with the
1993/// same type qualifiers as FromPtr has on its pointee type. ToType,
1994/// if non-empty, will be a pointer to ToType that may or may not have
1995/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001996///
Mike Stump11289f42009-09-09 15:08:12 +00001997static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001998BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001999 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002000 ASTContext &Context,
2001 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002002 assert((FromPtr->getTypeClass() == Type::Pointer ||
2003 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2004 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
John McCall31168b02011-06-15 23:02:42 +00002006 /// Conversions to 'id' subsume cv-qualifier conversions.
2007 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002008 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
2010 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002011 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002012 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002013 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002014
John McCall31168b02011-06-15 23:02:42 +00002015 if (StripObjCLifetime)
2016 Quals.removeObjCLifetime();
2017
Mike Stump11289f42009-09-09 15:08:12 +00002018 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002019 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002020 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002021 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002022 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002023
2024 // Build a pointer to ToPointee. It has the right qualifiers
2025 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002026 if (isa<ObjCObjectPointerType>(ToType))
2027 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002028 return Context.getPointerType(ToPointee);
2029 }
2030
2031 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002032 QualType QualifiedCanonToPointee
2033 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002035 if (isa<ObjCObjectPointerType>(ToType))
2036 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2037 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002038}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039
Mike Stump11289f42009-09-09 15:08:12 +00002040static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002041 bool InOverloadResolution,
2042 ASTContext &Context) {
2043 // Handle value-dependent integral null pointer constants correctly.
2044 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2045 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002046 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002047 return !InOverloadResolution;
2048
Douglas Gregor56751b52009-09-25 04:25:58 +00002049 return Expr->isNullPointerConstant(Context,
2050 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2051 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002052}
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002054/// IsPointerConversion - Determines whether the conversion of the
2055/// expression From, which has the (possibly adjusted) type FromType,
2056/// can be converted to the type ToType via a pointer conversion (C++
2057/// 4.10). If so, returns true and places the converted type (that
2058/// might differ from ToType in its cv-qualifiers at some level) into
2059/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002060///
Douglas Gregora29dc052008-11-27 01:19:21 +00002061/// This routine also supports conversions to and from block pointers
2062/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2063/// pointers to interfaces. FIXME: Once we've determined the
2064/// appropriate overloading rules for Objective-C, we may want to
2065/// split the Objective-C checks into a different routine; however,
2066/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002067/// conversions, so for now they live here. IncompatibleObjC will be
2068/// set if the conversion is an allowed Objective-C conversion that
2069/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002070bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002071 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002072 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002073 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002074 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002075 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2076 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002077 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002078
Mike Stump11289f42009-09-09 15:08:12 +00002079 // Conversion from a null pointer constant to any Objective-C pointer type.
2080 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002082 ConvertedType = ToType;
2083 return true;
2084 }
2085
Douglas Gregor231d1c62008-11-27 00:15:41 +00002086 // Blocks: Block pointers can be converted to void*.
2087 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002088 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002089 ConvertedType = ToType;
2090 return true;
2091 }
2092 // Blocks: A null pointer constant can be converted to a block
2093 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002094 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002095 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002096 ConvertedType = ToType;
2097 return true;
2098 }
2099
Sebastian Redl576fd422009-05-10 18:38:11 +00002100 // If the left-hand-side is nullptr_t, the right side can be a null
2101 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002102 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002103 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002104 ConvertedType = ToType;
2105 return true;
2106 }
2107
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002108 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 if (!ToTypePtr)
2110 return false;
2111
2112 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002113 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002114 ConvertedType = ToType;
2115 return true;
2116 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002117
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002119 // , including objective-c pointers.
2120 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002121 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002122 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002123 ConvertedType = BuildSimilarlyQualifiedPointerType(
2124 FromType->getAs<ObjCObjectPointerType>(),
2125 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002126 ToType, Context);
2127 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002128 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002129 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002130 if (!FromTypePtr)
2131 return false;
2132
2133 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002134
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002136 // pointer conversion, so don't do all of the work below.
2137 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2138 return false;
2139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002140 // An rvalue of type "pointer to cv T," where T is an object type,
2141 // can be converted to an rvalue of type "pointer to cv void" (C++
2142 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002143 if (FromPointeeType->isIncompleteOrObjectType() &&
2144 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002146 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002147 ToType, Context,
2148 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002149 return true;
2150 }
2151
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002152 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002153 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002154 ToPointeeType->isVoidType()) {
2155 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2156 ToPointeeType,
2157 ToType, Context);
2158 return true;
2159 }
2160
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002161 // When we're overloading in C, we allow a special kind of pointer
2162 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002163 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002164 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002166 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002167 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002168 return true;
2169 }
2170
Douglas Gregor5c407d92008-10-23 00:40:37 +00002171 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002172 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002173 // An rvalue of type "pointer to cv D," where D is a class type,
2174 // can be converted to an rvalue of type "pointer to cv B," where
2175 // B is a base class (clause 10) of D. If B is an inaccessible
2176 // (clause 11) or ambiguous (10.2) base class of D, a program that
2177 // necessitates this conversion is ill-formed. The result of the
2178 // conversion is a pointer to the base class sub-object of the
2179 // derived class object. The null pointer value is converted to
2180 // the null pointer value of the destination type.
2181 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002182 // Note that we do not check for ambiguity or inaccessibility
2183 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002184 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002185 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002186 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002187 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002188 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002189 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002190 ToType, Context);
2191 return true;
2192 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002193
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002194 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2195 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2196 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2197 ToPointeeType,
2198 ToType, Context);
2199 return true;
2200 }
2201
Douglas Gregora119f102008-12-19 19:13:09 +00002202 return false;
2203}
Douglas Gregoraec25842011-04-26 23:16:46 +00002204
2205/// \brief Adopt the given qualifiers for the given type.
2206static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2207 Qualifiers TQs = T.getQualifiers();
2208
2209 // Check whether qualifiers already match.
2210 if (TQs == Qs)
2211 return T;
2212
2213 if (Qs.compatiblyIncludes(TQs))
2214 return Context.getQualifiedType(T, Qs);
2215
2216 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2217}
Douglas Gregora119f102008-12-19 19:13:09 +00002218
2219/// isObjCPointerConversion - Determines whether this is an
2220/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2221/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002222bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002223 QualType& ConvertedType,
2224 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002225 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002226 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002227
Douglas Gregoraec25842011-04-26 23:16:46 +00002228 // The set of qualifiers on the type we're converting from.
2229 Qualifiers FromQualifiers = FromType.getQualifiers();
2230
Steve Naroff7cae42b2009-07-10 23:34:53 +00002231 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002232 const ObjCObjectPointerType* ToObjCPtr =
2233 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002234 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002235 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002236
Steve Naroff7cae42b2009-07-10 23:34:53 +00002237 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002238 // If the pointee types are the same (ignoring qualifications),
2239 // then this is not a pointer conversion.
2240 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2241 FromObjCPtr->getPointeeType()))
2242 return false;
2243
Douglas Gregorab209d82015-07-07 03:58:42 +00002244 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002245 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002246 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2247 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002248 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002249 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2250 FromObjCPtr->getPointeeType()))
2251 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002253 ToObjCPtr->getPointeeType(),
2254 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002256 return true;
2257 }
2258
2259 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2260 // Okay: this is some kind of implicit downcast of Objective-C
2261 // interfaces, which is permitted. However, we're going to
2262 // complain about it.
2263 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002264 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002265 ToObjCPtr->getPointeeType(),
2266 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002268 return true;
2269 }
Mike Stump11289f42009-09-09 15:08:12 +00002270 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002271 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002272 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002273 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002274 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002275 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002276 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002277 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002278 // to a block pointer type.
2279 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002280 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002281 return true;
2282 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002283 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002285 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002286 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002287 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002288 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002289 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002290 return true;
2291 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002292 else
Douglas Gregora119f102008-12-19 19:13:09 +00002293 return false;
2294
Douglas Gregor033f56d2008-12-23 00:53:59 +00002295 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002296 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002297 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002298 else if (const BlockPointerType *FromBlockPtr =
2299 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002300 FromPointeeType = FromBlockPtr->getPointeeType();
2301 else
Douglas Gregora119f102008-12-19 19:13:09 +00002302 return false;
2303
Douglas Gregora119f102008-12-19 19:13:09 +00002304 // If we have pointers to pointers, recursively check whether this
2305 // is an Objective-C conversion.
2306 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2307 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2308 IncompatibleObjC)) {
2309 // We always complain about this conversion.
2310 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002311 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002312 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002313 return true;
2314 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002315 // Allow conversion of pointee being objective-c pointer to another one;
2316 // as in I* to id.
2317 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2318 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2319 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2320 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002321
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002322 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002323 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002324 return true;
2325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002326
Douglas Gregor033f56d2008-12-23 00:53:59 +00002327 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002328 // differences in the argument and result types are in Objective-C
2329 // pointer conversions. If so, we permit the conversion (but
2330 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002331 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002332 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002333 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002334 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002335 if (FromFunctionType && ToFunctionType) {
2336 // If the function types are exactly the same, this isn't an
2337 // Objective-C pointer conversion.
2338 if (Context.getCanonicalType(FromPointeeType)
2339 == Context.getCanonicalType(ToPointeeType))
2340 return false;
2341
2342 // Perform the quick checks that will tell us whether these
2343 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002344 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002345 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2346 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2347 return false;
2348
2349 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002350 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2351 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002352 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002353 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2354 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002355 ConvertedType, IncompatibleObjC)) {
2356 // Okay, we have an Objective-C pointer conversion.
2357 HasObjCConversion = true;
2358 } else {
2359 // Function types are too different. Abort.
2360 return false;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregora119f102008-12-19 19:13:09 +00002363 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002365 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002366 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2367 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002368 if (Context.getCanonicalType(FromArgType)
2369 == Context.getCanonicalType(ToArgType)) {
2370 // Okay, the types match exactly. Nothing to do.
2371 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2372 ConvertedType, IncompatibleObjC)) {
2373 // Okay, we have an Objective-C pointer conversion.
2374 HasObjCConversion = true;
2375 } else {
2376 // Argument types are too different. Abort.
2377 return false;
2378 }
2379 }
2380
2381 if (HasObjCConversion) {
2382 // We had an Objective-C conversion. Allow this pointer
2383 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002384 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002385 IncompatibleObjC = true;
2386 return true;
2387 }
2388 }
2389
Sebastian Redl72b597d2009-01-25 19:43:20 +00002390 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002391}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392
John McCall31168b02011-06-15 23:02:42 +00002393/// \brief Determine whether this is an Objective-C writeback conversion,
2394/// used for parameter passing when performing automatic reference counting.
2395///
2396/// \param FromType The type we're converting form.
2397///
2398/// \param ToType The type we're converting to.
2399///
2400/// \param ConvertedType The type that will be produced after applying
2401/// this conversion.
2402bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2403 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002404 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002405 Context.hasSameUnqualifiedType(FromType, ToType))
2406 return false;
2407
2408 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2409 QualType ToPointee;
2410 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2411 ToPointee = ToPointer->getPointeeType();
2412 else
2413 return false;
2414
2415 Qualifiers ToQuals = ToPointee.getQualifiers();
2416 if (!ToPointee->isObjCLifetimeType() ||
2417 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002418 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002419 return false;
2420
2421 // Argument must be a pointer to __strong to __weak.
2422 QualType FromPointee;
2423 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2424 FromPointee = FromPointer->getPointeeType();
2425 else
2426 return false;
2427
2428 Qualifiers FromQuals = FromPointee.getQualifiers();
2429 if (!FromPointee->isObjCLifetimeType() ||
2430 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2431 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2432 return false;
2433
2434 // Make sure that we have compatible qualifiers.
2435 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2436 if (!ToQuals.compatiblyIncludes(FromQuals))
2437 return false;
2438
2439 // Remove qualifiers from the pointee type we're converting from; they
2440 // aren't used in the compatibility check belong, and we'll be adding back
2441 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2442 FromPointee = FromPointee.getUnqualifiedType();
2443
2444 // The unqualified form of the pointee types must be compatible.
2445 ToPointee = ToPointee.getUnqualifiedType();
2446 bool IncompatibleObjC;
2447 if (Context.typesAreCompatible(FromPointee, ToPointee))
2448 FromPointee = ToPointee;
2449 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2450 IncompatibleObjC))
2451 return false;
2452
2453 /// \brief Construct the type we're converting to, which is a pointer to
2454 /// __autoreleasing pointee.
2455 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2456 ConvertedType = Context.getPointerType(FromPointee);
2457 return true;
2458}
2459
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002460bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2461 QualType& ConvertedType) {
2462 QualType ToPointeeType;
2463 if (const BlockPointerType *ToBlockPtr =
2464 ToType->getAs<BlockPointerType>())
2465 ToPointeeType = ToBlockPtr->getPointeeType();
2466 else
2467 return false;
2468
2469 QualType FromPointeeType;
2470 if (const BlockPointerType *FromBlockPtr =
2471 FromType->getAs<BlockPointerType>())
2472 FromPointeeType = FromBlockPtr->getPointeeType();
2473 else
2474 return false;
2475 // We have pointer to blocks, check whether the only
2476 // differences in the argument and result types are in Objective-C
2477 // pointer conversions. If so, we permit the conversion.
2478
2479 const FunctionProtoType *FromFunctionType
2480 = FromPointeeType->getAs<FunctionProtoType>();
2481 const FunctionProtoType *ToFunctionType
2482 = ToPointeeType->getAs<FunctionProtoType>();
2483
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002484 if (!FromFunctionType || !ToFunctionType)
2485 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002486
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002487 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002488 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002489
2490 // Perform the quick checks that will tell us whether these
2491 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002492 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002493 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2494 return false;
2495
2496 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2497 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2498 if (FromEInfo != ToEInfo)
2499 return false;
2500
2501 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002502 if (Context.hasSameType(FromFunctionType->getReturnType(),
2503 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002504 // Okay, the types match exactly. Nothing to do.
2505 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002506 QualType RHS = FromFunctionType->getReturnType();
2507 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002508 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002509 !RHS.hasQualifiers() && LHS.hasQualifiers())
2510 LHS = LHS.getUnqualifiedType();
2511
2512 if (Context.hasSameType(RHS,LHS)) {
2513 // OK exact match.
2514 } else if (isObjCPointerConversion(RHS, LHS,
2515 ConvertedType, IncompatibleObjC)) {
2516 if (IncompatibleObjC)
2517 return false;
2518 // Okay, we have an Objective-C pointer conversion.
2519 }
2520 else
2521 return false;
2522 }
2523
2524 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002525 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002526 ArgIdx != NumArgs; ++ArgIdx) {
2527 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002528 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2529 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002530 if (Context.hasSameType(FromArgType, ToArgType)) {
2531 // Okay, the types match exactly. Nothing to do.
2532 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2533 ConvertedType, IncompatibleObjC)) {
2534 if (IncompatibleObjC)
2535 return false;
2536 // Okay, we have an Objective-C pointer conversion.
2537 } else
2538 // Argument types are too different. Abort.
2539 return false;
2540 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002541 if (LangOpts.ObjCAutoRefCount &&
2542 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2543 ToFunctionType))
2544 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002545
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002546 ConvertedType = ToType;
2547 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002548}
2549
Richard Trieucaff2472011-11-23 22:32:32 +00002550enum {
2551 ft_default,
2552 ft_different_class,
2553 ft_parameter_arity,
2554 ft_parameter_mismatch,
2555 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002556 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002557};
2558
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002559/// Attempts to get the FunctionProtoType from a Type. Handles
2560/// MemberFunctionPointers properly.
2561static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2562 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2563 return FPT;
2564
2565 if (auto *MPT = FromType->getAs<MemberPointerType>())
2566 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2567
2568 return nullptr;
2569}
2570
Richard Trieucaff2472011-11-23 22:32:32 +00002571/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2572/// function types. Catches different number of parameter, mismatch in
2573/// parameter types, and different return types.
2574void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2575 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002576 // If either type is not valid, include no extra info.
2577 if (FromType.isNull() || ToType.isNull()) {
2578 PDiag << ft_default;
2579 return;
2580 }
2581
Richard Trieucaff2472011-11-23 22:32:32 +00002582 // Get the function type from the pointers.
2583 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2584 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2585 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002586 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002587 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2588 << QualType(FromMember->getClass(), 0);
2589 return;
2590 }
2591 FromType = FromMember->getPointeeType();
2592 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002593 }
2594
Richard Trieu96ed5b62011-12-13 23:19:45 +00002595 if (FromType->isPointerType())
2596 FromType = FromType->getPointeeType();
2597 if (ToType->isPointerType())
2598 ToType = ToType->getPointeeType();
2599
2600 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002601 FromType = FromType.getNonReferenceType();
2602 ToType = ToType.getNonReferenceType();
2603
Richard Trieucaff2472011-11-23 22:32:32 +00002604 // Don't print extra info for non-specialized template functions.
2605 if (FromType->isInstantiationDependentType() &&
2606 !FromType->getAs<TemplateSpecializationType>()) {
2607 PDiag << ft_default;
2608 return;
2609 }
2610
Richard Trieu96ed5b62011-12-13 23:19:45 +00002611 // No extra info for same types.
2612 if (Context.hasSameType(FromType, ToType)) {
2613 PDiag << ft_default;
2614 return;
2615 }
2616
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002617 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2618 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002619
2620 // Both types need to be function types.
2621 if (!FromFunction || !ToFunction) {
2622 PDiag << ft_default;
2623 return;
2624 }
2625
Alp Toker9cacbab2014-01-20 20:26:09 +00002626 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2627 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2628 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002629 return;
2630 }
2631
2632 // Handle different parameter types.
2633 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002634 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002635 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002636 << ToFunction->getParamType(ArgPos)
2637 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002638 return;
2639 }
2640
2641 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002642 if (!Context.hasSameType(FromFunction->getReturnType(),
2643 ToFunction->getReturnType())) {
2644 PDiag << ft_return_type << ToFunction->getReturnType()
2645 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002646 return;
2647 }
2648
2649 unsigned FromQuals = FromFunction->getTypeQuals(),
2650 ToQuals = ToFunction->getTypeQuals();
2651 if (FromQuals != ToQuals) {
2652 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2653 return;
2654 }
2655
2656 // Unable to find a difference, so add no extra info.
2657 PDiag << ft_default;
2658}
2659
Alp Toker9cacbab2014-01-20 20:26:09 +00002660/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002661/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002662/// they have same number of arguments. If the parameters are different,
2663/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002664bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2665 const FunctionProtoType *NewType,
2666 unsigned *ArgPos) {
2667 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2668 N = NewType->param_type_begin(),
2669 E = OldType->param_type_end();
2670 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002671 if (!Context.hasSameType(O->getUnqualifiedType(),
2672 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002673 if (ArgPos)
2674 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002675 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002676 }
2677 }
2678 return true;
2679}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002680
Douglas Gregor39c16d42008-10-24 04:54:22 +00002681/// CheckPointerConversion - Check the pointer conversion from the
2682/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002683/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002684/// conversions for which IsPointerConversion has already returned
2685/// true. It returns true and produces a diagnostic if there was an
2686/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002687bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002688 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002689 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002690 bool IgnoreBaseAccess,
2691 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002692 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002693 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002694
John McCall8cb679e2010-11-15 09:13:47 +00002695 Kind = CK_BitCast;
2696
George Burgess IV60bc9722016-01-13 23:36:34 +00002697 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002698 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002699 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002700 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2701 DiagRuntimeBehavior(From->getExprLoc(), From,
2702 PDiag(diag::warn_impcast_bool_to_null_pointer)
2703 << ToType << From->getSourceRange());
2704 else if (!isUnevaluatedContext())
2705 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2706 << ToType << From->getSourceRange();
2707 }
John McCall9320b872011-09-09 05:25:32 +00002708 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2709 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002710 QualType FromPointeeType = FromPtrType->getPointeeType(),
2711 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002712
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002713 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2714 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002715 // We must have a derived-to-base conversion. Check an
2716 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002717 unsigned InaccessibleID = 0;
2718 unsigned AmbigiousID = 0;
2719 if (Diagnose) {
2720 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2721 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2722 }
2723 if (CheckDerivedToBaseConversion(
2724 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2725 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2726 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002727 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002728
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002729 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002730 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002731 }
David Majnemer6bf02822015-10-31 08:42:14 +00002732
George Burgess IV60bc9722016-01-13 23:36:34 +00002733 if (Diagnose && !IsCStyleOrFunctionalCast &&
2734 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002735 assert(getLangOpts().MSVCCompat &&
2736 "this should only be possible with MSVCCompat!");
2737 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2738 << From->getSourceRange();
2739 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002740 }
John McCall9320b872011-09-09 05:25:32 +00002741 } else if (const ObjCObjectPointerType *ToPtrType =
2742 ToType->getAs<ObjCObjectPointerType>()) {
2743 if (const ObjCObjectPointerType *FromPtrType =
2744 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002745 // Objective-C++ conversions are always okay.
2746 // FIXME: We should have a different class of conversions for the
2747 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002748 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002749 return false;
John McCall9320b872011-09-09 05:25:32 +00002750 } else if (FromType->isBlockPointerType()) {
2751 Kind = CK_BlockPointerToObjCPointerCast;
2752 } else {
2753 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002754 }
John McCall9320b872011-09-09 05:25:32 +00002755 } else if (ToType->isBlockPointerType()) {
2756 if (!FromType->isBlockPointerType())
2757 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002758 }
John McCall8cb679e2010-11-15 09:13:47 +00002759
2760 // We shouldn't fall into this case unless it's valid for other
2761 // reasons.
2762 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2763 Kind = CK_NullToPointer;
2764
Douglas Gregor39c16d42008-10-24 04:54:22 +00002765 return false;
2766}
2767
Sebastian Redl72b597d2009-01-25 19:43:20 +00002768/// IsMemberPointerConversion - Determines whether the conversion of the
2769/// expression From, which has the (possibly adjusted) type FromType, can be
2770/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2771/// If so, returns true and places the converted type (that might differ from
2772/// ToType in its cv-qualifiers at some level) into ConvertedType.
2773bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002774 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002775 bool InOverloadResolution,
2776 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002777 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002778 if (!ToTypePtr)
2779 return false;
2780
2781 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002782 if (From->isNullPointerConstant(Context,
2783 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2784 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002785 ConvertedType = ToType;
2786 return true;
2787 }
2788
2789 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002790 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002791 if (!FromTypePtr)
2792 return false;
2793
2794 // A pointer to member of B can be converted to a pointer to member of D,
2795 // where D is derived from B (C++ 4.11p2).
2796 QualType FromClass(FromTypePtr->getClass(), 0);
2797 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002798
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002799 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002800 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002801 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2802 ToClass.getTypePtr());
2803 return true;
2804 }
2805
2806 return false;
2807}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002808
Sebastian Redl72b597d2009-01-25 19:43:20 +00002809/// CheckMemberPointerConversion - Check the member pointer conversion from the
2810/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002811/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002812/// for which IsMemberPointerConversion has already returned true. It returns
2813/// true and produces a diagnostic if there was an error, or returns false
2814/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002815bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002816 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002817 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002818 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002819 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002820 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002821 if (!FromPtrType) {
2822 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002824 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002825 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002826 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002827 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002828 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002829
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002830 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002831 assert(ToPtrType && "No member pointer cast has a target type "
2832 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002833
Sebastian Redled8f2002009-01-28 18:33:18 +00002834 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2835 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002836
Sebastian Redled8f2002009-01-28 18:33:18 +00002837 // FIXME: What about dependent types?
2838 assert(FromClass->isRecordType() && "Pointer into non-class.");
2839 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002840
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002841 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002842 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002843 bool DerivationOkay =
2844 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002845 assert(DerivationOkay &&
2846 "Should not have been called if derivation isn't OK.");
2847 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002848
Sebastian Redled8f2002009-01-28 18:33:18 +00002849 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2850 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002851 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2852 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2853 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2854 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002855 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002856
Douglas Gregor89ee6822009-02-28 01:32:25 +00002857 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002858 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2859 << FromClass << ToClass << QualType(VBase, 0)
2860 << From->getSourceRange();
2861 return true;
2862 }
2863
John McCall5b0829a2010-02-10 09:31:12 +00002864 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002865 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2866 Paths.front(),
2867 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002868
Anders Carlssond7923c62009-08-22 23:33:40 +00002869 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002870 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002871 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002872 return false;
2873}
2874
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002875/// Determine whether the lifetime conversion between the two given
2876/// qualifiers sets is nontrivial.
2877static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2878 Qualifiers ToQuals) {
2879 // Converting anything to const __unsafe_unretained is trivial.
2880 if (ToQuals.hasConst() &&
2881 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2882 return false;
2883
2884 return true;
2885}
2886
Douglas Gregor9a657932008-10-21 23:43:52 +00002887/// IsQualificationConversion - Determines whether the conversion from
2888/// an rvalue of type FromType to ToType is a qualification conversion
2889/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002890///
2891/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2892/// when the qualification conversion involves a change in the Objective-C
2893/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002894bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002895Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002896 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002897 FromType = Context.getCanonicalType(FromType);
2898 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002899 ObjCLifetimeConversion = false;
2900
Douglas Gregor9a657932008-10-21 23:43:52 +00002901 // If FromType and ToType are the same type, this is not a
2902 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002903 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002904 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002905
Douglas Gregor9a657932008-10-21 23:43:52 +00002906 // (C++ 4.4p4):
2907 // A conversion can add cv-qualifiers at levels other than the first
2908 // in multi-level pointers, subject to the following rules: [...]
2909 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002910 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002911 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002912 // Within each iteration of the loop, we check the qualifiers to
2913 // determine if this still looks like a qualification
2914 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002915 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002916 // until there are no more pointers or pointers-to-members left to
2917 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002918 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002919
Douglas Gregor90609aa2011-04-25 18:40:17 +00002920 Qualifiers FromQuals = FromType.getQualifiers();
2921 Qualifiers ToQuals = ToType.getQualifiers();
2922
John McCall31168b02011-06-15 23:02:42 +00002923 // Objective-C ARC:
2924 // Check Objective-C lifetime conversions.
2925 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2926 UnwrappedAnyPointer) {
2927 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002928 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2929 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002930 FromQuals.removeObjCLifetime();
2931 ToQuals.removeObjCLifetime();
2932 } else {
2933 // Qualification conversions cannot cast between different
2934 // Objective-C lifetime qualifiers.
2935 return false;
2936 }
2937 }
2938
Douglas Gregorf30053d2011-05-08 06:09:53 +00002939 // Allow addition/removal of GC attributes but not changing GC attributes.
2940 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2941 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2942 FromQuals.removeObjCGCAttr();
2943 ToQuals.removeObjCGCAttr();
2944 }
2945
Douglas Gregor9a657932008-10-21 23:43:52 +00002946 // -- for every j > 0, if const is in cv 1,j then const is in cv
2947 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002948 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002949 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregor9a657932008-10-21 23:43:52 +00002951 // -- if the cv 1,j and cv 2,j are different, then const is in
2952 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002953 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002954 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002955 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002956
Douglas Gregor9a657932008-10-21 23:43:52 +00002957 // Keep track of whether all prior cv-qualifiers in the "to" type
2958 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002959 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002960 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002961 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002962
2963 // We are left with FromType and ToType being the pointee types
2964 // after unwrapping the original FromType and ToType the same number
2965 // of types. If we unwrapped any pointers, and if FromType and
2966 // ToType have the same unqualified type (since we checked
2967 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002968 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002969}
2970
Douglas Gregorc79862f2012-04-12 17:51:55 +00002971/// \brief - Determine whether this is a conversion from a scalar type to an
2972/// atomic type.
2973///
2974/// If successful, updates \c SCS's second and third steps in the conversion
2975/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002976static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2977 bool InOverloadResolution,
2978 StandardConversionSequence &SCS,
2979 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002980 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2981 if (!ToAtomic)
2982 return false;
2983
2984 StandardConversionSequence InnerSCS;
2985 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2986 InOverloadResolution, InnerSCS,
2987 CStyle, /*AllowObjCWritebackConversion=*/false))
2988 return false;
2989
2990 SCS.Second = InnerSCS.Second;
2991 SCS.setToType(1, InnerSCS.getToType(1));
2992 SCS.Third = InnerSCS.Third;
2993 SCS.QualificationIncludesObjCLifetime
2994 = InnerSCS.QualificationIncludesObjCLifetime;
2995 SCS.setToType(2, InnerSCS.getToType(2));
2996 return true;
2997}
2998
Sebastian Redle5417162012-03-27 18:33:03 +00002999static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3000 CXXConstructorDecl *Constructor,
3001 QualType Type) {
3002 const FunctionProtoType *CtorType =
3003 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003004 if (CtorType->getNumParams() > 0) {
3005 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003006 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3007 return true;
3008 }
3009 return false;
3010}
3011
Sebastian Redl82ace982012-02-11 23:51:08 +00003012static OverloadingResult
3013IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3014 CXXRecordDecl *To,
3015 UserDefinedConversionSequence &User,
3016 OverloadCandidateSet &CandidateSet,
3017 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00003018 DeclContext::lookup_result R = S.LookupConstructors(To);
3019 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00003020 Con != ConEnd; ++Con) {
3021 NamedDecl *D = *Con;
3022 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3023
3024 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003025 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00003026 FunctionTemplateDecl *ConstructorTmpl
3027 = dyn_cast<FunctionTemplateDecl>(D);
3028 if (ConstructorTmpl)
3029 Constructor
3030 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3031 else
3032 Constructor = cast<CXXConstructorDecl>(D);
3033
3034 bool Usable = !Constructor->isInvalidDecl() &&
3035 S.isInitListConstructor(Constructor) &&
3036 (AllowExplicit || !Constructor->isExplicit());
3037 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003038 // If the first argument is (a reference to) the target type,
3039 // suppress conversions.
3040 bool SuppressUserConversions =
3041 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003042 if (ConstructorTmpl)
3043 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003044 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003045 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003046 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003047 else
3048 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003049 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003050 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003051 }
3052 }
3053
3054 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3055
3056 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003057 switch (auto Result =
3058 CandidateSet.BestViableFunction(S, From->getLocStart(),
3059 Best, true)) {
3060 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003061 case OR_Success: {
3062 // Record the standard conversion we used and the conversion function.
3063 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003064 QualType ThisType = Constructor->getThisType(S.Context);
3065 // Initializer lists don't have conversions as such.
3066 User.Before.setAsIdentityConversion();
3067 User.HadMultipleCandidates = HadMultipleCandidates;
3068 User.ConversionFunction = Constructor;
3069 User.FoundConversionFunction = Best->FoundDecl;
3070 User.After.setAsIdentityConversion();
3071 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3072 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003073 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003074 }
3075
3076 case OR_No_Viable_Function:
3077 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003078 case OR_Ambiguous:
3079 return OR_Ambiguous;
3080 }
3081
3082 llvm_unreachable("Invalid OverloadResult!");
3083}
3084
Douglas Gregor576e98c2009-01-30 23:27:23 +00003085/// Determines whether there is a user-defined conversion sequence
3086/// (C++ [over.ics.user]) that converts expression From to the type
3087/// ToType. If such a conversion exists, User will contain the
3088/// user-defined conversion sequence that performs such a conversion
3089/// and this routine will return true. Otherwise, this routine returns
3090/// false and User is unspecified.
3091///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003092/// \param AllowExplicit true if the conversion should consider C++0x
3093/// "explicit" conversion functions as well as non-explicit conversion
3094/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003095///
3096/// \param AllowObjCConversionOnExplicit true if the conversion should
3097/// allow an extra Objective-C pointer conversion on uses of explicit
3098/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003099static OverloadingResult
3100IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003101 UserDefinedConversionSequence &User,
3102 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003103 bool AllowExplicit,
3104 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003105 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003106
Douglas Gregor5ab11652010-04-17 22:01:05 +00003107 // Whether we will only visit constructors.
3108 bool ConstructorsOnly = false;
3109
3110 // If the type we are conversion to is a class type, enumerate its
3111 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003112 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003113 // C++ [over.match.ctor]p1:
3114 // When objects of class type are direct-initialized (8.5), or
3115 // copy-initialized from an expression of the same or a
3116 // derived class type (8.5), overload resolution selects the
3117 // constructor. [...] For copy-initialization, the candidate
3118 // functions are all the converting constructors (12.3.1) of
3119 // that class. The argument list is the expression-list within
3120 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003121 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003122 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003123 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003124 ConstructorsOnly = true;
3125
Richard Smithdb0ac552015-12-18 22:40:25 +00003126 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003127 // We're not going to find any constructors.
3128 } else if (CXXRecordDecl *ToRecordDecl
3129 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003130
3131 Expr **Args = &From;
3132 unsigned NumArgs = 1;
3133 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003134 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003135 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003136 OverloadingResult Result = IsInitializerListConstructorConversion(
3137 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3138 if (Result != OR_No_Viable_Function)
3139 return Result;
3140 // Never mind.
3141 CandidateSet.clear();
3142
3143 // If we're list-initializing, we pass the individual elements as
3144 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003145 Args = InitList->getInits();
3146 NumArgs = InitList->getNumInits();
3147 ListInitializing = true;
3148 }
3149
David Blaikieff7d47a2012-12-19 00:45:41 +00003150 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3151 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003152 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003153 NamedDecl *D = *Con;
3154 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3155
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003156 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003157 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003158 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003159 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003160 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003161 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003162 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3163 else
John McCalla0296f72010-03-19 07:35:19 +00003164 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003166 bool Usable = !Constructor->isInvalidDecl();
3167 if (ListInitializing)
3168 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3169 else
3170 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3171 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003172 bool SuppressUserConversions = !ConstructorsOnly;
3173 if (SuppressUserConversions && ListInitializing) {
3174 SuppressUserConversions = false;
3175 if (NumArgs == 1) {
3176 // If the first argument is (a reference to) the target type,
3177 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003178 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3179 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003180 }
3181 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003182 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003183 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003184 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003185 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003186 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003187 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003188 // Allow one user-defined conversion when user specifies a
3189 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003190 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003191 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003192 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003193 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003194 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003195 }
3196 }
3197
Douglas Gregor5ab11652010-04-17 22:01:05 +00003198 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003199 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003200 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003201 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003202 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003203 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003204 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003205 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3206 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003207 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3208 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003209 DeclAccessPair FoundDecl = I.getPair();
3210 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003211 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3212 if (isa<UsingShadowDecl>(D))
3213 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3214
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003215 CXXConversionDecl *Conv;
3216 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003217 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3218 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003219 else
John McCallda4458e2010-03-31 01:36:47 +00003220 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003221
3222 if (AllowExplicit || !Conv->isExplicit()) {
3223 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003224 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3225 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003226 CandidateSet,
3227 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003228 else
John McCall5c32be02010-08-24 20:38:10 +00003229 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003230 From, ToType, CandidateSet,
3231 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003232 }
3233 }
3234 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003235 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003236
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003237 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3238
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003239 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003240 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3241 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003242 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003243 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003244 // Record the standard conversion we used and the conversion function.
3245 if (CXXConstructorDecl *Constructor
3246 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3247 // C++ [over.ics.user]p1:
3248 // If the user-defined conversion is specified by a
3249 // constructor (12.3.1), the initial standard conversion
3250 // sequence converts the source type to the type required by
3251 // the argument of the constructor.
3252 //
3253 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003254 if (isa<InitListExpr>(From)) {
3255 // Initializer lists don't have conversions as such.
3256 User.Before.setAsIdentityConversion();
3257 } else {
3258 if (Best->Conversions[0].isEllipsis())
3259 User.EllipsisConversion = true;
3260 else {
3261 User.Before = Best->Conversions[0].Standard;
3262 User.EllipsisConversion = false;
3263 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003264 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003265 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003266 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003267 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003268 User.After.setAsIdentityConversion();
3269 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3270 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003271 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003272 }
3273 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003274 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3275 // C++ [over.ics.user]p1:
3276 //
3277 // [...] If the user-defined conversion is specified by a
3278 // conversion function (12.3.2), the initial standard
3279 // conversion sequence converts the source type to the
3280 // implicit object parameter of the conversion function.
3281 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003282 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003283 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003284 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003285 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003286
John McCall5c32be02010-08-24 20:38:10 +00003287 // C++ [over.ics.user]p2:
3288 // The second standard conversion sequence converts the
3289 // result of the user-defined conversion to the target type
3290 // for the sequence. Since an implicit conversion sequence
3291 // is an initialization, the special rules for
3292 // initialization by user-defined conversion apply when
3293 // selecting the best user-defined conversion for a
3294 // user-defined conversion sequence (see 13.3.3 and
3295 // 13.3.3.1).
3296 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003297 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003298 }
David Blaikie8a40f702012-01-17 06:56:22 +00003299 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003300
John McCall5c32be02010-08-24 20:38:10 +00003301 case OR_No_Viable_Function:
3302 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
John McCall5c32be02010-08-24 20:38:10 +00003304 case OR_Ambiguous:
3305 return OR_Ambiguous;
3306 }
3307
David Blaikie8a40f702012-01-17 06:56:22 +00003308 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003309}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003311bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003312Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003313 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003314 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3315 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003317 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003318 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003319 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003320 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3321 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003322 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003323 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003324 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003325 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003326 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003327 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003328 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003329 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003330 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003332}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003333
Douglas Gregor2837aa22012-02-22 17:32:19 +00003334/// \brief Compare the user-defined conversion functions or constructors
3335/// of two user-defined conversion sequences to determine whether any ordering
3336/// is possible.
3337static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003338compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003339 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003340 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003341 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003342
Douglas Gregor2837aa22012-02-22 17:32:19 +00003343 // Objective-C++:
3344 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003345 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003346 // respectively, always prefer the conversion to a function pointer,
3347 // because the function pointer is more lightweight and is more likely
3348 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003349 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003350 if (!Conv1)
3351 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003352
Douglas Gregor2837aa22012-02-22 17:32:19 +00003353 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3354 if (!Conv2)
3355 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003356
Douglas Gregor2837aa22012-02-22 17:32:19 +00003357 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3358 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3359 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3360 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003361 return Block1 ? ImplicitConversionSequence::Worse
3362 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003363 }
3364
3365 return ImplicitConversionSequence::Indistinguishable;
3366}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003367
3368static bool hasDeprecatedStringLiteralToCharPtrConversion(
3369 const ImplicitConversionSequence &ICS) {
3370 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3371 (ICS.isUserDefined() &&
3372 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3373}
3374
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003375/// CompareImplicitConversionSequences - Compare two implicit
3376/// conversion sequences to determine whether one is better than the
3377/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003378static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003379CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003380 const ImplicitConversionSequence& ICS1,
3381 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003382{
3383 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3384 // conversion sequences (as defined in 13.3.3.1)
3385 // -- a standard conversion sequence (13.3.3.1.1) is a better
3386 // conversion sequence than a user-defined conversion sequence or
3387 // an ellipsis conversion sequence, and
3388 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3389 // conversion sequence than an ellipsis conversion sequence
3390 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003391 //
John McCall0d1da222010-01-12 00:44:57 +00003392 // C++0x [over.best.ics]p10:
3393 // For the purpose of ranking implicit conversion sequences as
3394 // described in 13.3.3.2, the ambiguous conversion sequence is
3395 // treated as a user-defined sequence that is indistinguishable
3396 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003397
3398 // String literal to 'char *' conversion has been deprecated in C++03. It has
3399 // been removed from C++11. We still accept this conversion, if it happens at
3400 // the best viable function. Otherwise, this conversion is considered worse
3401 // than ellipsis conversion. Consider this as an extension; this is not in the
3402 // standard. For example:
3403 //
3404 // int &f(...); // #1
3405 // void f(char*); // #2
3406 // void g() { int &r = f("foo"); }
3407 //
3408 // In C++03, we pick #2 as the best viable function.
3409 // In C++11, we pick #1 as the best viable function, because ellipsis
3410 // conversion is better than string-literal to char* conversion (since there
3411 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3412 // convert arguments, #2 would be the best viable function in C++11.
3413 // If the best viable function has this conversion, a warning will be issued
3414 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3415
3416 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3417 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3418 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3419 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3420 ? ImplicitConversionSequence::Worse
3421 : ImplicitConversionSequence::Better;
3422
Douglas Gregor5ab11652010-04-17 22:01:05 +00003423 if (ICS1.getKindRank() < ICS2.getKindRank())
3424 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003425 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003426 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003427
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003428 // The following checks require both conversion sequences to be of
3429 // the same kind.
3430 if (ICS1.getKind() != ICS2.getKind())
3431 return ImplicitConversionSequence::Indistinguishable;
3432
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003433 ImplicitConversionSequence::CompareKind Result =
3434 ImplicitConversionSequence::Indistinguishable;
3435
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003436 // Two implicit conversion sequences of the same form are
3437 // indistinguishable conversion sequences unless one of the
3438 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003439
3440 // List-initialization sequence L1 is a better conversion sequence than
3441 // list-initialization sequence L2 if:
3442 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3443 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003444 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003445 // and N1 is smaller than N2.,
3446 // even if one of the other rules in this paragraph would otherwise apply.
3447 if (!ICS1.isBad()) {
3448 if (ICS1.isStdInitializerListElement() &&
3449 !ICS2.isStdInitializerListElement())
3450 return ImplicitConversionSequence::Better;
3451 if (!ICS1.isStdInitializerListElement() &&
3452 ICS2.isStdInitializerListElement())
3453 return ImplicitConversionSequence::Worse;
3454 }
3455
John McCall0d1da222010-01-12 00:44:57 +00003456 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003457 // Standard conversion sequence S1 is a better conversion sequence than
3458 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003459 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003460 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003461 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003462 // User-defined conversion sequence U1 is a better conversion
3463 // sequence than another user-defined conversion sequence U2 if
3464 // they contain the same user-defined conversion function or
3465 // constructor and if the second standard conversion sequence of
3466 // U1 is better than the second standard conversion sequence of
3467 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003468 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003469 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003470 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003471 ICS1.UserDefined.After,
3472 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003473 else
3474 Result = compareConversionFunctions(S,
3475 ICS1.UserDefined.ConversionFunction,
3476 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003477 }
3478
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003479 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480}
3481
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003482static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3483 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3484 Qualifiers Quals;
3485 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003489 return Context.hasSameUnqualifiedType(T1, T2);
3490}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003492// Per 13.3.3.2p3, compare the given standard conversion sequences to
3493// determine if one is a proper subset of the other.
3494static ImplicitConversionSequence::CompareKind
3495compareStandardConversionSubsets(ASTContext &Context,
3496 const StandardConversionSequence& SCS1,
3497 const StandardConversionSequence& SCS2) {
3498 ImplicitConversionSequence::CompareKind Result
3499 = ImplicitConversionSequence::Indistinguishable;
3500
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003502 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003503 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3504 return ImplicitConversionSequence::Better;
3505 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3506 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003508 if (SCS1.Second != SCS2.Second) {
3509 if (SCS1.Second == ICK_Identity)
3510 Result = ImplicitConversionSequence::Better;
3511 else if (SCS2.Second == ICK_Identity)
3512 Result = ImplicitConversionSequence::Worse;
3513 else
3514 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003515 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003516 return ImplicitConversionSequence::Indistinguishable;
3517
3518 if (SCS1.Third == SCS2.Third) {
3519 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3520 : ImplicitConversionSequence::Indistinguishable;
3521 }
3522
3523 if (SCS1.Third == ICK_Identity)
3524 return Result == ImplicitConversionSequence::Worse
3525 ? ImplicitConversionSequence::Indistinguishable
3526 : ImplicitConversionSequence::Better;
3527
3528 if (SCS2.Third == ICK_Identity)
3529 return Result == ImplicitConversionSequence::Better
3530 ? ImplicitConversionSequence::Indistinguishable
3531 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003533 return ImplicitConversionSequence::Indistinguishable;
3534}
3535
Douglas Gregore696ebb2011-01-26 14:52:12 +00003536/// \brief Determine whether one of the given reference bindings is better
3537/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003538static bool
3539isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3540 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003541 // C++0x [over.ics.rank]p3b4:
3542 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3543 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003545 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003547 // reference*.
3548 //
3549 // FIXME: Rvalue references. We're going rogue with the above edits,
3550 // because the semantics in the current C++0x working paper (N3225 at the
3551 // time of this writing) break the standard definition of std::forward
3552 // and std::reference_wrapper when dealing with references to functions.
3553 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003554 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3555 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3556 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557
Douglas Gregore696ebb2011-01-26 14:52:12 +00003558 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3559 SCS2.IsLvalueReference) ||
3560 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003561 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003562}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003564/// CompareStandardConversionSequences - Compare two standard
3565/// conversion sequences to determine whether one is better than the
3566/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003567static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003568CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003569 const StandardConversionSequence& SCS1,
3570 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003571{
3572 // Standard conversion sequence S1 is a better conversion sequence
3573 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3574
3575 // -- S1 is a proper subsequence of S2 (comparing the conversion
3576 // sequences in the canonical form defined by 13.3.3.1.1,
3577 // excluding any Lvalue Transformation; the identity conversion
3578 // sequence is considered to be a subsequence of any
3579 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003580 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003581 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003582 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003583
3584 // -- the rank of S1 is better than the rank of S2 (by the rules
3585 // defined below), or, if not that,
3586 ImplicitConversionRank Rank1 = SCS1.getRank();
3587 ImplicitConversionRank Rank2 = SCS2.getRank();
3588 if (Rank1 < Rank2)
3589 return ImplicitConversionSequence::Better;
3590 else if (Rank2 < Rank1)
3591 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003592
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003593 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3594 // are indistinguishable unless one of the following rules
3595 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003596
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003597 // A conversion that is not a conversion of a pointer, or
3598 // pointer to member, to bool is better than another conversion
3599 // that is such a conversion.
3600 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3601 return SCS2.isPointerConversionToBool()
3602 ? ImplicitConversionSequence::Better
3603 : ImplicitConversionSequence::Worse;
3604
Douglas Gregor5c407d92008-10-23 00:40:37 +00003605 // C++ [over.ics.rank]p4b2:
3606 //
3607 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003608 // conversion of B* to A* is better than conversion of B* to
3609 // void*, and conversion of A* to void* is better than conversion
3610 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003611 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003612 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003613 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003614 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003615 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3616 // Exactly one of the conversion sequences is a conversion to
3617 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003618 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3619 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003620 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3621 // Neither conversion sequence converts to a void pointer; compare
3622 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003623 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003624 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003625 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003626 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3627 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003628 // Both conversion sequences are conversions to void
3629 // pointers. Compare the source types to determine if there's an
3630 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003631 QualType FromType1 = SCS1.getFromType();
3632 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003633
3634 // Adjust the types we're converting from via the array-to-pointer
3635 // conversion, if we need to.
3636 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003637 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003638 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003639 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003640
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003641 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3642 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003643
Richard Smith0f59cb32015-12-18 21:45:41 +00003644 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003645 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003646 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003647 return ImplicitConversionSequence::Worse;
3648
3649 // Objective-C++: If one interface is more specific than the
3650 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003651 const ObjCObjectPointerType* FromObjCPtr1
3652 = FromType1->getAs<ObjCObjectPointerType>();
3653 const ObjCObjectPointerType* FromObjCPtr2
3654 = FromType2->getAs<ObjCObjectPointerType>();
3655 if (FromObjCPtr1 && FromObjCPtr2) {
3656 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3657 FromObjCPtr2);
3658 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3659 FromObjCPtr1);
3660 if (AssignLeft != AssignRight) {
3661 return AssignLeft? ImplicitConversionSequence::Better
3662 : ImplicitConversionSequence::Worse;
3663 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003664 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003665 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003666
3667 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3668 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003669 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003670 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003671 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003672
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003673 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003674 // Check for a better reference binding based on the kind of bindings.
3675 if (isBetterReferenceBindingKind(SCS1, SCS2))
3676 return ImplicitConversionSequence::Better;
3677 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3678 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Sebastian Redlb28b4072009-03-22 23:49:27 +00003680 // C++ [over.ics.rank]p3b4:
3681 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3682 // which the references refer are the same type except for
3683 // top-level cv-qualifiers, and the type to which the reference
3684 // initialized by S2 refers is more cv-qualified than the type
3685 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003686 QualType T1 = SCS1.getToType(2);
3687 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003688 T1 = S.Context.getCanonicalType(T1);
3689 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003690 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003691 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3692 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003693 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003694 // Objective-C++ ARC: If the references refer to objects with different
3695 // lifetimes, prefer bindings that don't change lifetime.
3696 if (SCS1.ObjCLifetimeConversionBinding !=
3697 SCS2.ObjCLifetimeConversionBinding) {
3698 return SCS1.ObjCLifetimeConversionBinding
3699 ? ImplicitConversionSequence::Worse
3700 : ImplicitConversionSequence::Better;
3701 }
3702
Chandler Carruth8e543b32010-12-12 08:17:55 +00003703 // If the type is an array type, promote the element qualifiers to the
3704 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003705 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003706 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003707 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003708 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003709 if (T2.isMoreQualifiedThan(T1))
3710 return ImplicitConversionSequence::Better;
3711 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003712 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003713 }
3714 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715
Francois Pichet08d2fa02011-09-18 21:37:37 +00003716 // In Microsoft mode, prefer an integral conversion to a
3717 // floating-to-integral conversion if the integral conversion
3718 // is between types of the same size.
3719 // For example:
3720 // void f(float);
3721 // void f(int);
3722 // int main {
3723 // long a;
3724 // f(a);
3725 // }
3726 // Here, MSVC will call f(int) instead of generating a compile error
3727 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003728 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3729 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003730 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003731 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003732 return ImplicitConversionSequence::Better;
3733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 return ImplicitConversionSequence::Indistinguishable;
3735}
3736
3737/// CompareQualificationConversions - Compares two standard conversion
3738/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003739/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003740static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003741CompareQualificationConversions(Sema &S,
3742 const StandardConversionSequence& SCS1,
3743 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003744 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003745 // -- S1 and S2 differ only in their qualification conversion and
3746 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3747 // cv-qualification signature of type T1 is a proper subset of
3748 // the cv-qualification signature of type T2, and S1 is not the
3749 // deprecated string literal array-to-pointer conversion (4.2).
3750 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3751 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3752 return ImplicitConversionSequence::Indistinguishable;
3753
3754 // FIXME: the example in the standard doesn't use a qualification
3755 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003756 QualType T1 = SCS1.getToType(2);
3757 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003758 T1 = S.Context.getCanonicalType(T1);
3759 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003760 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003761 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3762 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003763
3764 // If the types are the same, we won't learn anything by unwrapped
3765 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003766 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003767 return ImplicitConversionSequence::Indistinguishable;
3768
Chandler Carruth607f38e2009-12-29 07:16:59 +00003769 // If the type is an array type, promote the element qualifiers to the type
3770 // for comparison.
3771 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003772 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003773 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003774 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003775
Mike Stump11289f42009-09-09 15:08:12 +00003776 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003777 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003778
3779 // Objective-C++ ARC:
3780 // Prefer qualification conversions not involving a change in lifetime
3781 // to qualification conversions that do not change lifetime.
3782 if (SCS1.QualificationIncludesObjCLifetime !=
3783 SCS2.QualificationIncludesObjCLifetime) {
3784 Result = SCS1.QualificationIncludesObjCLifetime
3785 ? ImplicitConversionSequence::Worse
3786 : ImplicitConversionSequence::Better;
3787 }
3788
John McCall5c32be02010-08-24 20:38:10 +00003789 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003790 // Within each iteration of the loop, we check the qualifiers to
3791 // determine if this still looks like a qualification
3792 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003793 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003794 // until there are no more pointers or pointers-to-members left
3795 // to unwrap. This essentially mimics what
3796 // IsQualificationConversion does, but here we're checking for a
3797 // strict subset of qualifiers.
3798 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3799 // The qualifiers are the same, so this doesn't tell us anything
3800 // about how the sequences rank.
3801 ;
3802 else if (T2.isMoreQualifiedThan(T1)) {
3803 // T1 has fewer qualifiers, so it could be the better sequence.
3804 if (Result == ImplicitConversionSequence::Worse)
3805 // Neither has qualifiers that are a subset of the other's
3806 // qualifiers.
3807 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003808
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003809 Result = ImplicitConversionSequence::Better;
3810 } else if (T1.isMoreQualifiedThan(T2)) {
3811 // T2 has fewer qualifiers, so it could be the better sequence.
3812 if (Result == ImplicitConversionSequence::Better)
3813 // Neither has qualifiers that are a subset of the other's
3814 // qualifiers.
3815 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003816
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003817 Result = ImplicitConversionSequence::Worse;
3818 } else {
3819 // Qualifiers are disjoint.
3820 return ImplicitConversionSequence::Indistinguishable;
3821 }
3822
3823 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003824 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003825 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003826 }
3827
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003828 // Check that the winning standard conversion sequence isn't using
3829 // the deprecated string literal array to pointer conversion.
3830 switch (Result) {
3831 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003832 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003833 Result = ImplicitConversionSequence::Indistinguishable;
3834 break;
3835
3836 case ImplicitConversionSequence::Indistinguishable:
3837 break;
3838
3839 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003840 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003841 Result = ImplicitConversionSequence::Indistinguishable;
3842 break;
3843 }
3844
3845 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003846}
3847
Douglas Gregor5c407d92008-10-23 00:40:37 +00003848/// CompareDerivedToBaseConversions - Compares two standard conversion
3849/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003850/// various kinds of derived-to-base conversions (C++
3851/// [over.ics.rank]p4b3). As part of these checks, we also look at
3852/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003853static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003854CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003855 const StandardConversionSequence& SCS1,
3856 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003857 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003858 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003859 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003860 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003861
3862 // Adjust the types we're converting from via the array-to-pointer
3863 // conversion, if we need to.
3864 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003865 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003866 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003867 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003868
3869 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003870 FromType1 = S.Context.getCanonicalType(FromType1);
3871 ToType1 = S.Context.getCanonicalType(ToType1);
3872 FromType2 = S.Context.getCanonicalType(FromType2);
3873 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003874
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003875 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003876 //
3877 // If class B is derived directly or indirectly from class A and
3878 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003879 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003880 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003881 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003882 SCS2.Second == ICK_Pointer_Conversion &&
3883 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3884 FromType1->isPointerType() && FromType2->isPointerType() &&
3885 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003886 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003887 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003888 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003889 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003890 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003891 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003892 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003893 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003894
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003895 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003897 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003898 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003899 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003900 return ImplicitConversionSequence::Worse;
3901 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003902
3903 // -- conversion of B* to A* is better than conversion of C* to A*,
3904 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003905 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003906 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003907 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003908 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003909 }
3910 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3911 SCS2.Second == ICK_Pointer_Conversion) {
3912 const ObjCObjectPointerType *FromPtr1
3913 = FromType1->getAs<ObjCObjectPointerType>();
3914 const ObjCObjectPointerType *FromPtr2
3915 = FromType2->getAs<ObjCObjectPointerType>();
3916 const ObjCObjectPointerType *ToPtr1
3917 = ToType1->getAs<ObjCObjectPointerType>();
3918 const ObjCObjectPointerType *ToPtr2
3919 = ToType2->getAs<ObjCObjectPointerType>();
3920
3921 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3922 // Apply the same conversion ranking rules for Objective-C pointer types
3923 // that we do for C++ pointers to class types. However, we employ the
3924 // Objective-C pseudo-subtyping relationship used for assignment of
3925 // Objective-C pointer types.
3926 bool FromAssignLeft
3927 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3928 bool FromAssignRight
3929 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3930 bool ToAssignLeft
3931 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3932 bool ToAssignRight
3933 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3934
3935 // A conversion to an a non-id object pointer type or qualified 'id'
3936 // type is better than a conversion to 'id'.
3937 if (ToPtr1->isObjCIdType() &&
3938 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3939 return ImplicitConversionSequence::Worse;
3940 if (ToPtr2->isObjCIdType() &&
3941 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3942 return ImplicitConversionSequence::Better;
3943
3944 // A conversion to a non-id object pointer type is better than a
3945 // conversion to a qualified 'id' type
3946 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3947 return ImplicitConversionSequence::Worse;
3948 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3949 return ImplicitConversionSequence::Better;
3950
3951 // A conversion to an a non-Class object pointer type or qualified 'Class'
3952 // type is better than a conversion to 'Class'.
3953 if (ToPtr1->isObjCClassType() &&
3954 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3955 return ImplicitConversionSequence::Worse;
3956 if (ToPtr2->isObjCClassType() &&
3957 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3958 return ImplicitConversionSequence::Better;
3959
3960 // A conversion to a non-Class object pointer type is better than a
3961 // conversion to a qualified 'Class' type.
3962 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3963 return ImplicitConversionSequence::Worse;
3964 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3965 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003966
Douglas Gregor058d3de2011-01-31 18:51:41 +00003967 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3968 if (S.Context.hasSameType(FromType1, FromType2) &&
3969 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3970 (ToAssignLeft != ToAssignRight))
3971 return ToAssignLeft? ImplicitConversionSequence::Worse
3972 : ImplicitConversionSequence::Better;
3973
3974 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3975 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3976 (FromAssignLeft != FromAssignRight))
3977 return FromAssignLeft? ImplicitConversionSequence::Better
3978 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003979 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003980 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003981
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003982 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003983 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3984 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3985 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003987 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003989 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003990 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003991 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003993 ToType2->getAs<MemberPointerType>();
3994 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3995 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3996 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3997 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3998 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3999 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4000 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4001 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004002 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004003 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004004 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004005 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004006 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004007 return ImplicitConversionSequence::Better;
4008 }
4009 // conversion of B::* to C::* is better than conversion of A::* to C::*
4010 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004011 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004012 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004013 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004014 return ImplicitConversionSequence::Worse;
4015 }
4016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017
Douglas Gregor5ab11652010-04-17 22:01:05 +00004018 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004019 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004020 // -- binding of an expression of type C to a reference of type
4021 // B& is better than binding an expression of type C to a
4022 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004023 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4024 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004025 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004026 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004027 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004028 return ImplicitConversionSequence::Worse;
4029 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004030
Douglas Gregor2fe98832008-11-03 19:09:14 +00004031 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004032 // -- binding of an expression of type B to a reference of type
4033 // A& is better than binding an expression of type C to a
4034 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004035 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4036 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004037 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004038 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004039 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004040 return ImplicitConversionSequence::Worse;
4041 }
4042 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004043
Douglas Gregor5c407d92008-10-23 00:40:37 +00004044 return ImplicitConversionSequence::Indistinguishable;
4045}
4046
Douglas Gregor45bb4832013-03-26 23:36:30 +00004047/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4048/// C++ class.
4049static bool isTypeValid(QualType T) {
4050 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4051 return !Record->isInvalidDecl();
4052
4053 return true;
4054}
4055
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004056/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4057/// determine whether they are reference-related,
4058/// reference-compatible, reference-compatible with added
4059/// qualification, or incompatible, for use in C++ initialization by
4060/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4061/// type, and the first type (T1) is the pointee type of the reference
4062/// type being initialized.
4063Sema::ReferenceCompareResult
4064Sema::CompareReferenceRelationship(SourceLocation Loc,
4065 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004066 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004067 bool &ObjCConversion,
4068 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004069 assert(!OrigT1->isReferenceType() &&
4070 "T1 must be the pointee type of the reference type");
4071 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4072
4073 QualType T1 = Context.getCanonicalType(OrigT1);
4074 QualType T2 = Context.getCanonicalType(OrigT2);
4075 Qualifiers T1Quals, T2Quals;
4076 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4077 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4078
4079 // C++ [dcl.init.ref]p4:
4080 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4081 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4082 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004083 DerivedToBase = false;
4084 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004085 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004086 if (UnqualT1 == UnqualT2) {
4087 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004088 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004089 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004090 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004091 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004092 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4093 UnqualT2->isObjCObjectOrInterfaceType() &&
4094 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4095 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004096 else
4097 return Ref_Incompatible;
4098
4099 // At this point, we know that T1 and T2 are reference-related (at
4100 // least).
4101
4102 // If the type is an array type, promote the element qualifiers to the type
4103 // for comparison.
4104 if (isa<ArrayType>(T1) && T1Quals)
4105 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4106 if (isa<ArrayType>(T2) && T2Quals)
4107 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4108
4109 // C++ [dcl.init.ref]p4:
4110 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4111 // reference-related to T2 and cv1 is the same cv-qualification
4112 // as, or greater cv-qualification than, cv2. For purposes of
4113 // overload resolution, cases for which cv1 is greater
4114 // cv-qualification than cv2 are identified as
4115 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004116 //
4117 // Note that we also require equivalence of Objective-C GC and address-space
4118 // qualifiers when performing these computations, so that e.g., an int in
4119 // address space 1 is not reference-compatible with an int in address
4120 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004121 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4122 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004123 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4124 ObjCLifetimeConversion = true;
4125
John McCall31168b02011-06-15 23:02:42 +00004126 T1Quals.removeObjCLifetime();
4127 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004128 }
4129
Douglas Gregord517d552011-04-28 17:56:11 +00004130 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004131 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004132 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004133 return Ref_Compatible_With_Added_Qualification;
4134 else
4135 return Ref_Related;
4136}
4137
Douglas Gregor836a7e82010-08-11 02:15:33 +00004138/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004139/// with DeclType. Return true if something definite is found.
4140static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004141FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4142 QualType DeclType, SourceLocation DeclLoc,
4143 Expr *Init, QualType T2, bool AllowRvalues,
4144 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004145 assert(T2->isRecordType() && "Can only find conversions of record types.");
4146 CXXRecordDecl *T2RecordDecl
4147 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4148
Richard Smith100b24a2014-04-17 01:52:14 +00004149 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004150 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4151 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004152 NamedDecl *D = *I;
4153 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4154 if (isa<UsingShadowDecl>(D))
4155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4156
4157 FunctionTemplateDecl *ConvTemplate
4158 = dyn_cast<FunctionTemplateDecl>(D);
4159 CXXConversionDecl *Conv;
4160 if (ConvTemplate)
4161 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4162 else
4163 Conv = cast<CXXConversionDecl>(D);
4164
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004166 // explicit conversions, skip it.
4167 if (!AllowExplicit && Conv->isExplicit())
4168 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169
Douglas Gregor836a7e82010-08-11 02:15:33 +00004170 if (AllowRvalues) {
4171 bool DerivedToBase = false;
4172 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004173 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004174
4175 // If we are initializing an rvalue reference, don't permit conversion
4176 // functions that return lvalues.
4177 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4178 const ReferenceType *RefType
4179 = Conv->getConversionType()->getAs<LValueReferenceType>();
4180 if (RefType && !RefType->getPointeeType()->isFunctionType())
4181 continue;
4182 }
4183
Douglas Gregor836a7e82010-08-11 02:15:33 +00004184 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004185 S.CompareReferenceRelationship(
4186 DeclLoc,
4187 Conv->getConversionType().getNonReferenceType()
4188 .getUnqualifiedType(),
4189 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004190 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004191 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004192 continue;
4193 } else {
4194 // If the conversion function doesn't return a reference type,
4195 // it can't be considered for this conversion. An rvalue reference
4196 // is only acceptable if its referencee is a function type.
4197
4198 const ReferenceType *RefType =
4199 Conv->getConversionType()->getAs<ReferenceType>();
4200 if (!RefType ||
4201 (!RefType->isLValueReferenceType() &&
4202 !RefType->getPointeeType()->isFunctionType()))
4203 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Douglas Gregor836a7e82010-08-11 02:15:33 +00004206 if (ConvTemplate)
4207 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004208 Init, DeclType, CandidateSet,
4209 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004210 else
4211 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004212 DeclType, CandidateSet,
4213 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004214 }
4215
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004216 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4217
Sebastian Redld92badf2010-06-30 18:13:39 +00004218 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004219 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004220 case OR_Success:
4221 // C++ [over.ics.ref]p1:
4222 //
4223 // [...] If the parameter binds directly to the result of
4224 // applying a conversion function to the argument
4225 // expression, the implicit conversion sequence is a
4226 // user-defined conversion sequence (13.3.3.1.2), with the
4227 // second standard conversion sequence either an identity
4228 // conversion or, if the conversion function returns an
4229 // entity of a type that is a derived class of the parameter
4230 // type, a derived-to-base Conversion.
4231 if (!Best->FinalConversion.DirectBinding)
4232 return false;
4233
4234 ICS.setUserDefined();
4235 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4236 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004237 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004238 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004239 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004240 ICS.UserDefined.EllipsisConversion = false;
4241 assert(ICS.UserDefined.After.ReferenceBinding &&
4242 ICS.UserDefined.After.DirectBinding &&
4243 "Expected a direct reference binding!");
4244 return true;
4245
4246 case OR_Ambiguous:
4247 ICS.setAmbiguous();
4248 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4249 Cand != CandidateSet.end(); ++Cand)
4250 if (Cand->Viable)
4251 ICS.Ambiguous.addConversion(Cand->Function);
4252 return true;
4253
4254 case OR_No_Viable_Function:
4255 case OR_Deleted:
4256 // There was no suitable conversion, or we found a deleted
4257 // conversion; continue with other checks.
4258 return false;
4259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
David Blaikie8a40f702012-01-17 06:56:22 +00004261 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004262}
4263
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004264/// \brief Compute an implicit conversion sequence for reference
4265/// initialization.
4266static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004267TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004268 SourceLocation DeclLoc,
4269 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004270 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004271 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4272
4273 // Most paths end in a failed conversion.
4274 ImplicitConversionSequence ICS;
4275 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4276
4277 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4278 QualType T2 = Init->getType();
4279
4280 // If the initializer is the address of an overloaded function, try
4281 // to resolve the overloaded function. If all goes well, T2 is the
4282 // type of the resulting function.
4283 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4284 DeclAccessPair Found;
4285 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4286 false, Found))
4287 T2 = Fn->getType();
4288 }
4289
4290 // Compute some basic properties of the types and the initializer.
4291 bool isRValRef = DeclType->isRValueReferenceType();
4292 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004293 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004294 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004295 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004296 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004297 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004298 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004299
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300
Sebastian Redld92badf2010-06-30 18:13:39 +00004301 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004302 // A reference to type "cv1 T1" is initialized by an expression
4303 // of type "cv2 T2" as follows:
4304
Sebastian Redld92badf2010-06-30 18:13:39 +00004305 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004306 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004307 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4308 // reference-compatible with "cv2 T2," or
4309 //
4310 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4311 if (InitCategory.isLValue() &&
4312 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004313 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004314 // When a parameter of reference type binds directly (8.5.3)
4315 // to an argument expression, the implicit conversion sequence
4316 // is the identity conversion, unless the argument expression
4317 // has a type that is a derived class of the parameter type,
4318 // in which case the implicit conversion sequence is a
4319 // derived-to-base Conversion (13.3.3.1).
4320 ICS.setStandard();
4321 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004322 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4323 : ObjCConversion? ICK_Compatible_Conversion
4324 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004325 ICS.Standard.Third = ICK_Identity;
4326 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4327 ICS.Standard.setToType(0, T2);
4328 ICS.Standard.setToType(1, T1);
4329 ICS.Standard.setToType(2, T1);
4330 ICS.Standard.ReferenceBinding = true;
4331 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004332 ICS.Standard.IsLvalueReference = !isRValRef;
4333 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4334 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004335 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004336 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004337 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004338 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004339
Sebastian Redld92badf2010-06-30 18:13:39 +00004340 // Nothing more to do: the inaccessibility/ambiguity check for
4341 // derived-to-base conversions is suppressed when we're
4342 // computing the implicit conversion sequence (C++
4343 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004344 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004345 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004346
Sebastian Redld92badf2010-06-30 18:13:39 +00004347 // -- has a class type (i.e., T2 is a class type), where T1 is
4348 // not reference-related to T2, and can be implicitly
4349 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4350 // is reference-compatible with "cv3 T3" 92) (this
4351 // conversion is selected by enumerating the applicable
4352 // conversion functions (13.3.1.6) and choosing the best
4353 // one through overload resolution (13.3)),
4354 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004355 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004356 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004357 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4358 Init, T2, /*AllowRvalues=*/false,
4359 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004360 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004361 }
4362 }
4363
Sebastian Redld92badf2010-06-30 18:13:39 +00004364 // -- Otherwise, the reference shall be an lvalue reference to a
4365 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004366 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004367 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004368 return ICS;
4369
Douglas Gregorf143cd52011-01-24 16:14:37 +00004370 // -- If the initializer expression
4371 //
4372 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004373 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004374 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4375 (InitCategory.isXValue() ||
4376 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4377 (InitCategory.isLValue() && T2->isFunctionType()))) {
4378 ICS.setStandard();
4379 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004381 : ObjCConversion? ICK_Compatible_Conversion
4382 : ICK_Identity;
4383 ICS.Standard.Third = ICK_Identity;
4384 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4385 ICS.Standard.setToType(0, T2);
4386 ICS.Standard.setToType(1, T1);
4387 ICS.Standard.setToType(2, T1);
4388 ICS.Standard.ReferenceBinding = true;
4389 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4390 // binding unless we're binding to a class prvalue.
4391 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4392 // allow the use of rvalue references in C++98/03 for the benefit of
4393 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004395 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004396 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004397 ICS.Standard.IsLvalueReference = !isRValRef;
4398 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004400 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004401 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004402 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004403 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Douglas Gregorf143cd52011-01-24 16:14:37 +00004407 // -- has a class type (i.e., T2 is a class type), where T1 is not
4408 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409 // an xvalue, class prvalue, or function lvalue of type
4410 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004411 // "cv3 T3",
4412 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004414 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004416 // class subobject).
4417 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004418 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004419 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4420 Init, T2, /*AllowRvalues=*/true,
4421 AllowExplicit)) {
4422 // In the second case, if the reference is an rvalue reference
4423 // and the second standard conversion sequence of the
4424 // user-defined conversion sequence includes an lvalue-to-rvalue
4425 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004427 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4428 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4429
Douglas Gregor95273c32011-01-21 16:36:05 +00004430 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432
Richard Smith19172c42014-07-14 02:28:44 +00004433 // A temporary of function type cannot be created; don't even try.
4434 if (T1->isFunctionType())
4435 return ICS;
4436
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004437 // -- Otherwise, a temporary of type "cv1 T1" is created and
4438 // initialized from the initializer expression using the
4439 // rules for a non-reference copy initialization (8.5). The
4440 // reference is then bound to the temporary. If T1 is
4441 // reference-related to T2, cv1 must be the same
4442 // cv-qualification as, or greater cv-qualification than,
4443 // cv2; otherwise, the program is ill-formed.
4444 if (RefRelationship == Sema::Ref_Related) {
4445 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4446 // we would be reference-compatible or reference-compatible with
4447 // added qualification. But that wasn't the case, so the reference
4448 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004449 //
4450 // Note that we only want to check address spaces and cvr-qualifiers here.
4451 // ObjC GC and lifetime qualifiers aren't important.
4452 Qualifiers T1Quals = T1.getQualifiers();
4453 Qualifiers T2Quals = T2.getQualifiers();
4454 T1Quals.removeObjCGCAttr();
4455 T1Quals.removeObjCLifetime();
4456 T2Quals.removeObjCGCAttr();
4457 T2Quals.removeObjCLifetime();
4458 if (!T1Quals.compatiblyIncludes(T2Quals))
4459 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004460 }
4461
4462 // If at least one of the types is a class type, the types are not
4463 // related, and we aren't allowed any user conversions, the
4464 // reference binding fails. This case is important for breaking
4465 // recursion, since TryImplicitConversion below will attempt to
4466 // create a temporary through the use of a copy constructor.
4467 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4468 (T1->isRecordType() || T2->isRecordType()))
4469 return ICS;
4470
Douglas Gregorcba72b12011-01-21 05:18:22 +00004471 // If T1 is reference-related to T2 and the reference is an rvalue
4472 // reference, the initializer expression shall not be an lvalue.
4473 if (RefRelationship >= Sema::Ref_Related &&
4474 isRValRef && Init->Classify(S.Context).isLValue())
4475 return ICS;
4476
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004477 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004478 // When a parameter of reference type is not bound directly to
4479 // an argument expression, the conversion sequence is the one
4480 // required to convert the argument expression to the
4481 // underlying type of the reference according to
4482 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4483 // to copy-initializing a temporary of the underlying type with
4484 // the argument expression. Any difference in top-level
4485 // cv-qualification is subsumed by the initialization itself
4486 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004487 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4488 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004489 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004490 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004491 /*AllowObjCWritebackConversion=*/false,
4492 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004493
4494 // Of course, that's still a reference binding.
4495 if (ICS.isStandard()) {
4496 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004497 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004498 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004499 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004500 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004501 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004502 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004503 const ReferenceType *LValRefType =
4504 ICS.UserDefined.ConversionFunction->getReturnType()
4505 ->getAs<LValueReferenceType>();
4506
4507 // C++ [over.ics.ref]p3:
4508 // Except for an implicit object parameter, for which see 13.3.1, a
4509 // standard conversion sequence cannot be formed if it requires [...]
4510 // binding an rvalue reference to an lvalue other than a function
4511 // lvalue.
4512 // Note that the function case is not possible here.
4513 if (DeclType->isRValueReferenceType() && LValRefType) {
4514 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4515 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4516 // reference to an rvalue!
4517 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4518 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004519 }
Richard Smith19172c42014-07-14 02:28:44 +00004520
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004521 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004522 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004523 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004524 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4525 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004526 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4527 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004528 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004529
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004530 return ICS;
4531}
4532
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004533static ImplicitConversionSequence
4534TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4535 bool SuppressUserConversions,
4536 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004537 bool AllowObjCWritebackConversion,
4538 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004539
4540/// TryListConversion - Try to copy-initialize a value of type ToType from the
4541/// initializer list From.
4542static ImplicitConversionSequence
4543TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4544 bool SuppressUserConversions,
4545 bool InOverloadResolution,
4546 bool AllowObjCWritebackConversion) {
4547 // C++11 [over.ics.list]p1:
4548 // When an argument is an initializer list, it is not an expression and
4549 // special rules apply for converting it to a parameter type.
4550
4551 ImplicitConversionSequence Result;
4552 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4553
Sebastian Redl09edce02012-01-23 22:09:39 +00004554 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004555 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004556 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004557 return Result;
4558
Larisse Voufo19d08672015-01-27 18:47:05 +00004559 // Per DR1467:
4560 // If the parameter type is a class X and the initializer list has a single
4561 // element of type cv U, where U is X or a class derived from X, the
4562 // implicit conversion sequence is the one required to convert the element
4563 // to the parameter type.
4564 //
4565 // Otherwise, if the parameter type is a character array [... ]
4566 // and the initializer list has a single element that is an
4567 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4568 // implicit conversion sequence is the identity conversion.
4569 if (From->getNumInits() == 1) {
4570 if (ToType->isRecordType()) {
4571 QualType InitType = From->getInit(0)->getType();
4572 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004573 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004574 return TryCopyInitialization(S, From->getInit(0), ToType,
4575 SuppressUserConversions,
4576 InOverloadResolution,
4577 AllowObjCWritebackConversion);
4578 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004579 // FIXME: Check the other conditions here: array of character type,
4580 // initializer is a string literal.
4581 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004582 InitializedEntity Entity =
4583 InitializedEntity::InitializeParameter(S.Context, ToType,
4584 /*Consumed=*/false);
4585 if (S.CanPerformCopyInitialization(Entity, From)) {
4586 Result.setStandard();
4587 Result.Standard.setAsIdentityConversion();
4588 Result.Standard.setFromType(ToType);
4589 Result.Standard.setAllToTypes(ToType);
4590 return Result;
4591 }
4592 }
4593 }
4594
4595 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004596 // C++11 [over.ics.list]p2:
4597 // If the parameter type is std::initializer_list<X> or "array of X" and
4598 // all the elements can be implicitly converted to X, the implicit
4599 // conversion sequence is the worst conversion necessary to convert an
4600 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004601 //
4602 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004603 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004604 // list has exactly N elements or if it has fewer than N elements and X is
4605 // default-constructible, and if all the elements of the initializer list
4606 // can be implicitly converted to X, the implicit conversion sequence is
4607 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004608 //
4609 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004610 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004611 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004612 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004613 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004614 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004615 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004616 if (!X.isNull()) {
4617 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4618 Expr *Init = From->getInit(i);
4619 ImplicitConversionSequence ICS =
4620 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4621 InOverloadResolution,
4622 AllowObjCWritebackConversion);
4623 // If a single element isn't convertible, fail.
4624 if (ICS.isBad()) {
4625 Result = ICS;
4626 break;
4627 }
4628 // Otherwise, look for the worst conversion.
4629 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004630 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4631 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004632 ImplicitConversionSequence::Worse)
4633 Result = ICS;
4634 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004635
4636 // For an empty list, we won't have computed any conversion sequence.
4637 // Introduce the identity conversion sequence.
4638 if (From->getNumInits() == 0) {
4639 Result.setStandard();
4640 Result.Standard.setAsIdentityConversion();
4641 Result.Standard.setFromType(ToType);
4642 Result.Standard.setAllToTypes(ToType);
4643 }
4644
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004645 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004646 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004647 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004648
Larisse Voufo19d08672015-01-27 18:47:05 +00004649 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004650 // C++11 [over.ics.list]p3:
4651 // Otherwise, if the parameter is a non-aggregate class X and overload
4652 // resolution chooses a single best constructor [...] the implicit
4653 // conversion sequence is a user-defined conversion sequence. If multiple
4654 // constructors are viable but none is better than the others, the
4655 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004656 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4657 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004658 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4659 /*AllowExplicit=*/false,
4660 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004661 AllowObjCWritebackConversion,
4662 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004663 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004664
Larisse Voufo19d08672015-01-27 18:47:05 +00004665 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004666 // C++11 [over.ics.list]p4:
4667 // Otherwise, if the parameter has an aggregate type which can be
4668 // initialized from the initializer list [...] the implicit conversion
4669 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004670 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004671 // Type is an aggregate, argument is an init list. At this point it comes
4672 // down to checking whether the initialization works.
4673 // FIXME: Find out whether this parameter is consumed or not.
4674 InitializedEntity Entity =
4675 InitializedEntity::InitializeParameter(S.Context, ToType,
4676 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004677 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004678 Result.setUserDefined();
4679 Result.UserDefined.Before.setAsIdentityConversion();
4680 // Initializer lists don't have a type.
4681 Result.UserDefined.Before.setFromType(QualType());
4682 Result.UserDefined.Before.setAllToTypes(QualType());
4683
4684 Result.UserDefined.After.setAsIdentityConversion();
4685 Result.UserDefined.After.setFromType(ToType);
4686 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004687 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004688 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004689 return Result;
4690 }
4691
Larisse Voufo19d08672015-01-27 18:47:05 +00004692 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004693 // C++11 [over.ics.list]p5:
4694 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004695 if (ToType->isReferenceType()) {
4696 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4697 // mention initializer lists in any way. So we go by what list-
4698 // initialization would do and try to extrapolate from that.
4699
4700 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4701
4702 // If the initializer list has a single element that is reference-related
4703 // to the parameter type, we initialize the reference from that.
4704 if (From->getNumInits() == 1) {
4705 Expr *Init = From->getInit(0);
4706
4707 QualType T2 = Init->getType();
4708
4709 // If the initializer is the address of an overloaded function, try
4710 // to resolve the overloaded function. If all goes well, T2 is the
4711 // type of the resulting function.
4712 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4713 DeclAccessPair Found;
4714 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4715 Init, ToType, false, Found))
4716 T2 = Fn->getType();
4717 }
4718
4719 // Compute some basic properties of the types and the initializer.
4720 bool dummy1 = false;
4721 bool dummy2 = false;
4722 bool dummy3 = false;
4723 Sema::ReferenceCompareResult RefRelationship
4724 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4725 dummy2, dummy3);
4726
Richard Smith4d2bbd72013-09-06 01:22:42 +00004727 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004728 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4729 SuppressUserConversions,
4730 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004731 }
Sebastian Redldf888642011-12-03 14:54:30 +00004732 }
4733
4734 // Otherwise, we bind the reference to a temporary created from the
4735 // initializer list.
4736 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4737 InOverloadResolution,
4738 AllowObjCWritebackConversion);
4739 if (Result.isFailure())
4740 return Result;
4741 assert(!Result.isEllipsis() &&
4742 "Sub-initialization cannot result in ellipsis conversion.");
4743
4744 // Can we even bind to a temporary?
4745 if (ToType->isRValueReferenceType() ||
4746 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4747 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4748 Result.UserDefined.After;
4749 SCS.ReferenceBinding = true;
4750 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4751 SCS.BindsToRvalue = true;
4752 SCS.BindsToFunctionLvalue = false;
4753 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4754 SCS.ObjCLifetimeConversionBinding = false;
4755 } else
4756 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4757 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004758 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004759 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004760
Larisse Voufo19d08672015-01-27 18:47:05 +00004761 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004762 // C++11 [over.ics.list]p6:
4763 // Otherwise, if the parameter type is not a class:
4764 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004765 // - if the initializer list has one element that is not itself an
4766 // initializer list, the implicit conversion sequence is the one
4767 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004768 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004769 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004770 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4771 SuppressUserConversions,
4772 InOverloadResolution,
4773 AllowObjCWritebackConversion);
4774 // - if the initializer list has no elements, the implicit conversion
4775 // sequence is the identity conversion.
4776 else if (NumInits == 0) {
4777 Result.setStandard();
4778 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004779 Result.Standard.setFromType(ToType);
4780 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004781 }
4782 return Result;
4783 }
4784
Larisse Voufo19d08672015-01-27 18:47:05 +00004785 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004786 // C++11 [over.ics.list]p7:
4787 // In all cases other than those enumerated above, no conversion is possible
4788 return Result;
4789}
4790
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004791/// TryCopyInitialization - Try to copy-initialize a value of type
4792/// ToType from the expression From. Return the implicit conversion
4793/// sequence required to pass this argument, which may be a bad
4794/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004795/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004796/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004797static ImplicitConversionSequence
4798TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004799 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004800 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004801 bool AllowObjCWritebackConversion,
4802 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004803 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4804 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4805 InOverloadResolution,AllowObjCWritebackConversion);
4806
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004807 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004808 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004809 /*FIXME:*/From->getLocStart(),
4810 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004811 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004812
John McCall5c32be02010-08-24 20:38:10 +00004813 return TryImplicitConversion(S, From, ToType,
4814 SuppressUserConversions,
4815 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004816 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004817 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004818 AllowObjCWritebackConversion,
4819 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004820}
4821
Anna Zaks1b068122011-07-28 19:46:48 +00004822static bool TryCopyInitialization(const CanQualType FromQTy,
4823 const CanQualType ToQTy,
4824 Sema &S,
4825 SourceLocation Loc,
4826 ExprValueKind FromVK) {
4827 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4828 ImplicitConversionSequence ICS =
4829 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4830
4831 return !ICS.isBad();
4832}
4833
Douglas Gregor436424c2008-11-18 23:14:02 +00004834/// TryObjectArgumentInitialization - Try to initialize the object
4835/// parameter of the given member function (@c Method) from the
4836/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004837static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004838TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004839 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004840 CXXMethodDecl *Method,
4841 CXXRecordDecl *ActingContext) {
4842 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004843 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4844 // const volatile object.
4845 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4846 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004847 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004848
4849 // Set up the conversion sequence as a "bad" conversion, to allow us
4850 // to exit early.
4851 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004852
4853 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004854 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004855 FromType = PT->getPointeeType();
4856
Douglas Gregor02824322011-01-26 19:30:28 +00004857 // When we had a pointer, it's implicitly dereferenced, so we
4858 // better have an lvalue.
4859 assert(FromClassification.isLValue());
4860 }
4861
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004862 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004863
Douglas Gregor02824322011-01-26 19:30:28 +00004864 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004866 // parameter is
4867 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004868 // - "lvalue reference to cv X" for functions declared without a
4869 // ref-qualifier or with the & ref-qualifier
4870 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004871 // ref-qualifier
4872 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004874 // cv-qualification on the member function declaration.
4875 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004877 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004878 // (C++ [over.match.funcs]p5). We perform a simplified version of
4879 // reference binding here, that allows class rvalues to bind to
4880 // non-constant references.
4881
Douglas Gregor02824322011-01-26 19:30:28 +00004882 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004883 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004885 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004886 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004887 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004888 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004889 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004890 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004891
4892 // Check that we have either the same type or a derived type. It
4893 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004894 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004895 ImplicitConversionKind SecondKind;
4896 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4897 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004898 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004899 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004900 else {
John McCall65eb8792010-02-25 01:37:24 +00004901 ICS.setBad(BadConversionSequence::unrelated_class,
4902 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004903 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004904 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004905
Douglas Gregor02824322011-01-26 19:30:28 +00004906 // Check the ref-qualifier.
4907 switch (Method->getRefQualifier()) {
4908 case RQ_None:
4909 // Do nothing; we don't care about lvalueness or rvalueness.
4910 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911
Douglas Gregor02824322011-01-26 19:30:28 +00004912 case RQ_LValue:
4913 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4914 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004916 ImplicitParamType);
4917 return ICS;
4918 }
4919 break;
4920
4921 case RQ_RValue:
4922 if (!FromClassification.isRValue()) {
4923 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004925 ImplicitParamType);
4926 return ICS;
4927 }
4928 break;
4929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930
Douglas Gregor436424c2008-11-18 23:14:02 +00004931 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004932 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004933 ICS.Standard.setAsIdentityConversion();
4934 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004935 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004936 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004937 ICS.Standard.ReferenceBinding = true;
4938 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004940 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004941 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4942 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4943 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004944 return ICS;
4945}
4946
4947/// PerformObjectArgumentInitialization - Perform initialization of
4948/// the implicit object parameter for the given Method with the given
4949/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004950ExprResult
4951Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004952 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004953 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004954 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004955 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004956 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004957 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004958
Douglas Gregor02824322011-01-26 19:30:28 +00004959 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004960 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004961 FromRecordType = PT->getPointeeType();
4962 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004963 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004964 } else {
4965 FromRecordType = From->getType();
4966 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004967 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004968 }
4969
John McCall6e9f8f62009-12-03 04:06:58 +00004970 // Note that we always use the true parent context when performing
4971 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004972 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00004973 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4974 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004975 if (ICS.isBad()) {
4976 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4977 Qualifiers FromQs = FromRecordType.getQualifiers();
4978 Qualifiers ToQs = DestType.getQualifiers();
4979 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4980 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004981 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004982 diag::err_member_function_call_bad_cvr)
4983 << Method->getDeclName() << FromRecordType << (CVR - 1)
4984 << From->getSourceRange();
4985 Diag(Method->getLocation(), diag::note_previous_decl)
4986 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004987 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004988 }
4989 }
4990
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004991 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004992 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004993 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004994 }
Mike Stump11289f42009-09-09 15:08:12 +00004995
John Wiegley01296292011-04-08 18:41:53 +00004996 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4997 ExprResult FromRes =
4998 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4999 if (FromRes.isInvalid())
5000 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005001 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005002 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005003
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005004 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005005 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005006 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005007 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005008}
5009
Douglas Gregor5fb53972009-01-14 15:45:31 +00005010/// TryContextuallyConvertToBool - Attempt to contextually convert the
5011/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005012static ImplicitConversionSequence
5013TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005014 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005015 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005016 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005017 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005018 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005019 /*AllowObjCWritebackConversion=*/false,
5020 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005021}
5022
5023/// PerformContextuallyConvertToBool - Perform a contextual conversion
5024/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005025ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005026 if (checkPlaceholderForOverload(*this, From))
5027 return ExprError();
5028
John McCall5c32be02010-08-24 20:38:10 +00005029 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005030 if (!ICS.isBad())
5031 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032
Fariborz Jahanian76197412009-11-18 18:26:29 +00005033 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005034 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005035 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005036 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005037 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005038}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039
Richard Smithf8379a02012-01-18 23:55:52 +00005040/// Check that the specified conversion is permitted in a converted constant
5041/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5042/// is acceptable.
5043static bool CheckConvertedConstantConversions(Sema &S,
5044 StandardConversionSequence &SCS) {
5045 // Since we know that the target type is an integral or unscoped enumeration
5046 // type, most conversion kinds are impossible. All possible First and Third
5047 // conversions are fine.
5048 switch (SCS.Second) {
5049 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005050 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005051 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005052 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005053 return true;
5054
5055 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005056 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005057 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5058 // conversion, so we allow it in a converted constant expression.
5059 //
5060 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5061 // a lot of popular code. We should at least add a warning for this
5062 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005063 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5064 SCS.getToType(2)->isBooleanType();
5065
Richard Smith410cc892014-11-26 03:26:53 +00005066 case ICK_Pointer_Conversion:
5067 case ICK_Pointer_Member:
5068 // C++1z: null pointer conversions and null member pointer conversions are
5069 // only permitted if the source type is std::nullptr_t.
5070 return SCS.getFromType()->isNullPtrType();
5071
5072 case ICK_Floating_Promotion:
5073 case ICK_Complex_Promotion:
5074 case ICK_Floating_Conversion:
5075 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005076 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005077 case ICK_Compatible_Conversion:
5078 case ICK_Derived_To_Base:
5079 case ICK_Vector_Conversion:
5080 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005081 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005082 case ICK_Block_Pointer_Conversion:
5083 case ICK_TransparentUnionConversion:
5084 case ICK_Writeback_Conversion:
5085 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005086 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005087 return false;
5088
5089 case ICK_Lvalue_To_Rvalue:
5090 case ICK_Array_To_Pointer:
5091 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005092 llvm_unreachable("found a first conversion kind in Second");
5093
Richard Smithf8379a02012-01-18 23:55:52 +00005094 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005095 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005096
5097 case ICK_Num_Conversion_Kinds:
5098 break;
5099 }
5100
5101 llvm_unreachable("unknown conversion kind");
5102}
5103
5104/// CheckConvertedConstantExpression - Check that the expression From is a
5105/// converted constant expression of type T, perform the conversion and produce
5106/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005107static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5108 QualType T, APValue &Value,
5109 Sema::CCEKind CCE,
5110 bool RequireInt) {
5111 assert(S.getLangOpts().CPlusPlus11 &&
5112 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005113
Richard Smith410cc892014-11-26 03:26:53 +00005114 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005115 return ExprError();
5116
Richard Smith410cc892014-11-26 03:26:53 +00005117 // C++1z [expr.const]p3:
5118 // A converted constant expression of type T is an expression,
5119 // implicitly converted to type T, where the converted
5120 // expression is a constant expression and the implicit conversion
5121 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005122 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005123 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005124 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005125 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005126 /*AllowObjcWritebackConversion=*/false,
5127 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005128 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005129 switch (ICS.getKind()) {
5130 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005131 SCS = &ICS.Standard;
5132 break;
5133 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005134 // We are converting to a non-class type, so the Before sequence
5135 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005136 SCS = &ICS.UserDefined.After;
5137 break;
5138 case ImplicitConversionSequence::AmbiguousConversion:
5139 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005140 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5141 return S.Diag(From->getLocStart(),
5142 diag::err_typecheck_converted_constant_expression)
5143 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005144 return ExprError();
5145
5146 case ImplicitConversionSequence::EllipsisConversion:
5147 llvm_unreachable("ellipsis conversion in converted constant expression");
5148 }
5149
Richard Smith410cc892014-11-26 03:26:53 +00005150 // Check that we would only use permitted conversions.
5151 if (!CheckConvertedConstantConversions(S, *SCS)) {
5152 return S.Diag(From->getLocStart(),
5153 diag::err_typecheck_converted_constant_expression_disallowed)
5154 << From->getType() << From->getSourceRange() << T;
5155 }
5156 // [...] and where the reference binding (if any) binds directly.
5157 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5158 return S.Diag(From->getLocStart(),
5159 diag::err_typecheck_converted_constant_expression_indirect)
5160 << From->getType() << From->getSourceRange() << T;
5161 }
5162
5163 ExprResult Result =
5164 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005165 if (Result.isInvalid())
5166 return Result;
5167
5168 // Check for a narrowing implicit conversion.
5169 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005170 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005171 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005172 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005173 case NK_Variable_Narrowing:
5174 // Implicit conversion to a narrower type, and the value is not a constant
5175 // expression. We'll diagnose this in a moment.
5176 case NK_Not_Narrowing:
5177 break;
5178
5179 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005180 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005181 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005182 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005183 break;
5184
5185 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005186 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005187 << CCE << /*Constant*/0 << From->getType() << T;
5188 break;
5189 }
5190
5191 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005192 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005193 Expr::EvalResult Eval;
5194 Eval.Diag = &Notes;
5195
Richard Smith410cc892014-11-26 03:26:53 +00005196 if ((T->isReferenceType()
5197 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5198 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5199 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005200 // The expression can't be folded, so we can't keep it at this position in
5201 // the AST.
5202 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005203 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005204 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005205
5206 if (Notes.empty()) {
5207 // It's a constant expression.
5208 return Result;
5209 }
Richard Smithf8379a02012-01-18 23:55:52 +00005210 }
5211
5212 // It's not a constant expression. Produce an appropriate diagnostic.
5213 if (Notes.size() == 1 &&
5214 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005215 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005216 else {
Richard Smith410cc892014-11-26 03:26:53 +00005217 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005218 << CCE << From->getSourceRange();
5219 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005220 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005221 }
Richard Smith410cc892014-11-26 03:26:53 +00005222 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005223}
5224
Richard Smith410cc892014-11-26 03:26:53 +00005225ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5226 APValue &Value, CCEKind CCE) {
5227 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5228}
5229
5230ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5231 llvm::APSInt &Value,
5232 CCEKind CCE) {
5233 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5234
5235 APValue V;
5236 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5237 if (!R.isInvalid())
5238 Value = V.getInt();
5239 return R;
5240}
5241
5242
John McCallfec112d2011-09-09 06:11:02 +00005243/// dropPointerConversions - If the given standard conversion sequence
5244/// involves any pointer conversions, remove them. This may change
5245/// the result type of the conversion sequence.
5246static void dropPointerConversion(StandardConversionSequence &SCS) {
5247 if (SCS.Second == ICK_Pointer_Conversion) {
5248 SCS.Second = ICK_Identity;
5249 SCS.Third = ICK_Identity;
5250 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5251 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005252}
John McCall5c32be02010-08-24 20:38:10 +00005253
John McCallfec112d2011-09-09 06:11:02 +00005254/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5255/// convert the expression From to an Objective-C pointer type.
5256static ImplicitConversionSequence
5257TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5258 // Do an implicit conversion to 'id'.
5259 QualType Ty = S.Context.getObjCIdType();
5260 ImplicitConversionSequence ICS
5261 = TryImplicitConversion(S, From, Ty,
5262 // FIXME: Are these flags correct?
5263 /*SuppressUserConversions=*/false,
5264 /*AllowExplicit=*/true,
5265 /*InOverloadResolution=*/false,
5266 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005267 /*AllowObjCWritebackConversion=*/false,
5268 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005269
5270 // Strip off any final conversions to 'id'.
5271 switch (ICS.getKind()) {
5272 case ImplicitConversionSequence::BadConversion:
5273 case ImplicitConversionSequence::AmbiguousConversion:
5274 case ImplicitConversionSequence::EllipsisConversion:
5275 break;
5276
5277 case ImplicitConversionSequence::UserDefinedConversion:
5278 dropPointerConversion(ICS.UserDefined.After);
5279 break;
5280
5281 case ImplicitConversionSequence::StandardConversion:
5282 dropPointerConversion(ICS.Standard);
5283 break;
5284 }
5285
5286 return ICS;
5287}
5288
5289/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5290/// conversion of the expression From to an Objective-C pointer type.
5291ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005292 if (checkPlaceholderForOverload(*this, From))
5293 return ExprError();
5294
John McCall8b07ec22010-05-15 11:32:37 +00005295 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005296 ImplicitConversionSequence ICS =
5297 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005298 if (!ICS.isBad())
5299 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005300 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005301}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005302
Richard Smith8dd34252012-02-04 07:07:42 +00005303/// Determine whether the provided type is an integral type, or an enumeration
5304/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005305bool Sema::ICEConvertDiagnoser::match(QualType T) {
5306 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5307 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005308}
5309
Larisse Voufo236bec22013-06-10 06:50:24 +00005310static ExprResult
5311diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5312 Sema::ContextualImplicitConverter &Converter,
5313 QualType T, UnresolvedSetImpl &ViableConversions) {
5314
5315 if (Converter.Suppress)
5316 return ExprError();
5317
5318 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5319 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5320 CXXConversionDecl *Conv =
5321 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5322 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5323 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5324 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005325 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005326}
5327
5328static bool
5329diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5330 Sema::ContextualImplicitConverter &Converter,
5331 QualType T, bool HadMultipleCandidates,
5332 UnresolvedSetImpl &ExplicitConversions) {
5333 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5334 DeclAccessPair Found = ExplicitConversions[0];
5335 CXXConversionDecl *Conversion =
5336 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5337
5338 // The user probably meant to invoke the given explicit
5339 // conversion; use it.
5340 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5341 std::string TypeStr;
5342 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5343
5344 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5345 << FixItHint::CreateInsertion(From->getLocStart(),
5346 "static_cast<" + TypeStr + ">(")
5347 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005348 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005349 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5350
5351 // If we aren't in a SFINAE context, build a call to the
5352 // explicit conversion function.
5353 if (SemaRef.isSFINAEContext())
5354 return true;
5355
Craig Topperc3ec1492014-05-26 06:22:03 +00005356 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005357 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5358 HadMultipleCandidates);
5359 if (Result.isInvalid())
5360 return true;
5361 // Record usage of conversion in an implicit cast.
5362 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005363 CK_UserDefinedConversion, Result.get(),
5364 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005365 }
5366 return false;
5367}
5368
5369static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5370 Sema::ContextualImplicitConverter &Converter,
5371 QualType T, bool HadMultipleCandidates,
5372 DeclAccessPair &Found) {
5373 CXXConversionDecl *Conversion =
5374 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005375 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005376
5377 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5378 if (!Converter.SuppressConversion) {
5379 if (SemaRef.isSFINAEContext())
5380 return true;
5381
5382 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5383 << From->getSourceRange();
5384 }
5385
5386 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5387 HadMultipleCandidates);
5388 if (Result.isInvalid())
5389 return true;
5390 // Record usage of conversion in an implicit cast.
5391 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005392 CK_UserDefinedConversion, Result.get(),
5393 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005394 return false;
5395}
5396
5397static ExprResult finishContextualImplicitConversion(
5398 Sema &SemaRef, SourceLocation Loc, Expr *From,
5399 Sema::ContextualImplicitConverter &Converter) {
5400 if (!Converter.match(From->getType()) && !Converter.Suppress)
5401 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5402 << From->getSourceRange();
5403
5404 return SemaRef.DefaultLvalueConversion(From);
5405}
5406
5407static void
5408collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5409 UnresolvedSetImpl &ViableConversions,
5410 OverloadCandidateSet &CandidateSet) {
5411 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5412 DeclAccessPair FoundDecl = ViableConversions[I];
5413 NamedDecl *D = FoundDecl.getDecl();
5414 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5415 if (isa<UsingShadowDecl>(D))
5416 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5417
5418 CXXConversionDecl *Conv;
5419 FunctionTemplateDecl *ConvTemplate;
5420 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5421 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5422 else
5423 Conv = cast<CXXConversionDecl>(D);
5424
5425 if (ConvTemplate)
5426 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005427 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5428 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005429 else
5430 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005431 ToType, CandidateSet,
5432 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005433 }
5434}
5435
Richard Smithccc11812013-05-21 19:05:48 +00005436/// \brief Attempt to convert the given expression to a type which is accepted
5437/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005438///
Richard Smithccc11812013-05-21 19:05:48 +00005439/// This routine will attempt to convert an expression of class type to a
5440/// type accepted by the specified converter. In C++11 and before, the class
5441/// must have a single non-explicit conversion function converting to a matching
5442/// type. In C++1y, there can be multiple such conversion functions, but only
5443/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005444///
Douglas Gregor4799d032010-06-30 00:20:43 +00005445/// \param Loc The source location of the construct that requires the
5446/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005447///
James Dennett18348b62012-06-22 08:52:37 +00005448/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005449///
Richard Smithccc11812013-05-21 19:05:48 +00005450/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005451///
Douglas Gregor4799d032010-06-30 00:20:43 +00005452/// \returns The expression, converted to an integral or enumeration type if
5453/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005454ExprResult Sema::PerformContextualImplicitConversion(
5455 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005456 // We can't perform any more checking for type-dependent expressions.
5457 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005458 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005459
Eli Friedman1da70392012-01-26 00:26:18 +00005460 // Process placeholders immediately.
5461 if (From->hasPlaceholderType()) {
5462 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005463 if (result.isInvalid())
5464 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005465 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005466 }
5467
Richard Smithccc11812013-05-21 19:05:48 +00005468 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005469 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005470 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005471 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005472
5473 // FIXME: Check for missing '()' if T is a function type?
5474
Richard Smithccc11812013-05-21 19:05:48 +00005475 // We can only perform contextual implicit conversions on objects of class
5476 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005477 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005478 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005479 if (!Converter.Suppress)
5480 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005481 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005484 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005485 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005486 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005487 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005488
5489 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005490 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005491
Craig Toppere14c0f82014-03-12 04:55:44 +00005492 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005493 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005494 }
Richard Smithccc11812013-05-21 19:05:48 +00005495 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005496
Richard Smithdb0ac552015-12-18 22:40:25 +00005497 if (Converter.Suppress ? !isCompleteType(Loc, T)
5498 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005499 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005501 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005502 UnresolvedSet<4>
5503 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005504 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005505 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005506 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005507
Larisse Voufo236bec22013-06-10 06:50:24 +00005508 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005509 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005510
Larisse Voufo236bec22013-06-10 06:50:24 +00005511 // To check that there is only one target type, in C++1y:
5512 QualType ToType;
5513 bool HasUniqueTargetType = true;
5514
5515 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005516 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005517 NamedDecl *D = (*I)->getUnderlyingDecl();
5518 CXXConversionDecl *Conversion;
5519 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5520 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005521 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005522 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5523 else
5524 continue; // C++11 does not consider conversion operator templates(?).
5525 } else
5526 Conversion = cast<CXXConversionDecl>(D);
5527
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005528 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005529 "Conversion operator templates are considered potentially "
5530 "viable in C++1y");
5531
5532 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5533 if (Converter.match(CurToType) || ConvTemplate) {
5534
5535 if (Conversion->isExplicit()) {
5536 // FIXME: For C++1y, do we need this restriction?
5537 // cf. diagnoseNoViableConversion()
5538 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005539 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005540 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005541 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005542 if (ToType.isNull())
5543 ToType = CurToType.getUnqualifiedType();
5544 else if (HasUniqueTargetType &&
5545 (CurToType.getUnqualifiedType() != ToType))
5546 HasUniqueTargetType = false;
5547 }
5548 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005549 }
Richard Smith8dd34252012-02-04 07:07:42 +00005550 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005553 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005554 // C++1y [conv]p6:
5555 // ... An expression e of class type E appearing in such a context
5556 // is said to be contextually implicitly converted to a specified
5557 // type T and is well-formed if and only if e can be implicitly
5558 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005559 // for conversion functions whose return type is cv T or reference to
5560 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005561 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Larisse Voufo236bec22013-06-10 06:50:24 +00005563 // If no unique T is found:
5564 if (ToType.isNull()) {
5565 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5566 HadMultipleCandidates,
5567 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005568 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005569 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005571
Larisse Voufo236bec22013-06-10 06:50:24 +00005572 // If more than one unique Ts are found:
5573 if (!HasUniqueTargetType)
5574 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5575 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Larisse Voufo236bec22013-06-10 06:50:24 +00005577 // If one unique T is found:
5578 // First, build a candidate set from the previously recorded
5579 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005580 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005581 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5582 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005583
Larisse Voufo236bec22013-06-10 06:50:24 +00005584 // Then, perform overload resolution over the candidate set.
5585 OverloadCandidateSet::iterator Best;
5586 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5587 case OR_Success: {
5588 // Apply this conversion.
5589 DeclAccessPair Found =
5590 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5591 if (recordConversion(*this, Loc, From, Converter, T,
5592 HadMultipleCandidates, Found))
5593 return ExprError();
5594 break;
5595 }
5596 case OR_Ambiguous:
5597 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5598 ViableConversions);
5599 case OR_No_Viable_Function:
5600 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5601 HadMultipleCandidates,
5602 ExplicitConversions))
5603 return ExprError();
5604 // fall through 'OR_Deleted' case.
5605 case OR_Deleted:
5606 // We'll complain below about a non-integral condition type.
5607 break;
5608 }
5609 } else {
5610 switch (ViableConversions.size()) {
5611 case 0: {
5612 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5613 HadMultipleCandidates,
5614 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005615 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Larisse Voufo236bec22013-06-10 06:50:24 +00005617 // We'll complain below about a non-integral condition type.
5618 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005619 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005620 case 1: {
5621 // Apply this conversion.
5622 DeclAccessPair Found = ViableConversions[0];
5623 if (recordConversion(*this, Loc, From, Converter, T,
5624 HadMultipleCandidates, Found))
5625 return ExprError();
5626 break;
5627 }
5628 default:
5629 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5630 ViableConversions);
5631 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Larisse Voufo236bec22013-06-10 06:50:24 +00005634 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005635}
5636
Richard Smith100b24a2014-04-17 01:52:14 +00005637/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5638/// an acceptable non-member overloaded operator for a call whose
5639/// arguments have types T1 (and, if non-empty, T2). This routine
5640/// implements the check in C++ [over.match.oper]p3b2 concerning
5641/// enumeration types.
5642static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5643 FunctionDecl *Fn,
5644 ArrayRef<Expr *> Args) {
5645 QualType T1 = Args[0]->getType();
5646 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5647
5648 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5649 return true;
5650
5651 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5652 return true;
5653
5654 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5655 if (Proto->getNumParams() < 1)
5656 return false;
5657
5658 if (T1->isEnumeralType()) {
5659 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5660 if (Context.hasSameUnqualifiedType(T1, ArgType))
5661 return true;
5662 }
5663
5664 if (Proto->getNumParams() < 2)
5665 return false;
5666
5667 if (!T2.isNull() && T2->isEnumeralType()) {
5668 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5669 if (Context.hasSameUnqualifiedType(T2, ArgType))
5670 return true;
5671 }
5672
5673 return false;
5674}
5675
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005676/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005677/// candidate functions, using the given function call arguments. If
5678/// @p SuppressUserConversions, then don't allow user-defined
5679/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005680///
James Dennett2a4d13c2012-06-15 07:13:21 +00005681/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005682/// based on an incomplete set of function arguments. This feature is used by
5683/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005684void
5685Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005686 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005687 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005688 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005689 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005690 bool PartialOverloading,
5691 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005692 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005693 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005694 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005695 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005696 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005697
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005699 if (!isa<CXXConstructorDecl>(Method)) {
5700 // If we get here, it's because we're calling a member function
5701 // that is named without a member access expression (e.g.,
5702 // "this->f") that was either written explicitly or created
5703 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005704 // function, e.g., X::f(). We use an empty type for the implied
5705 // object argument (C++ [over.call.func]p3), and the acting context
5706 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005707 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005708 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005709 Args, CandidateSet, SuppressUserConversions,
5710 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005711 return;
5712 }
5713 // We treat a constructor like a non-member function, since its object
5714 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005715 }
5716
Douglas Gregorff7028a2009-11-13 23:59:09 +00005717 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005718 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005719
Richard Smith100b24a2014-04-17 01:52:14 +00005720 // C++ [over.match.oper]p3:
5721 // if no operand has a class type, only those non-member functions in the
5722 // lookup set that have a first parameter of type T1 or "reference to
5723 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5724 // is a right operand) a second parameter of type T2 or "reference to
5725 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5726 // candidate functions.
5727 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5728 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5729 return;
5730
Richard Smith8b86f2d2013-11-04 01:48:18 +00005731 // C++11 [class.copy]p11: [DR1402]
5732 // A defaulted move constructor that is defined as deleted is ignored by
5733 // overload resolution.
5734 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5735 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5736 Constructor->isMoveConstructor())
5737 return;
5738
Douglas Gregor27381f32009-11-23 12:27:39 +00005739 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005740 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005741
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005742 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005743 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005744 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005745 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005746 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005747 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005748 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005749 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750
John McCall578a1f82014-12-14 01:46:53 +00005751 if (Constructor) {
5752 // C++ [class.copy]p3:
5753 // A member function template is never instantiated to perform the copy
5754 // of a class object to an object of its class type.
5755 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005756 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005757 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005758 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5759 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005760 Candidate.Viable = false;
5761 Candidate.FailureKind = ovl_fail_illegal_constructor;
5762 return;
5763 }
5764 }
5765
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005766 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005767
5768 // (C++ 13.3.2p2): A candidate function having fewer than m
5769 // parameters is viable only if it has an ellipsis in its parameter
5770 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005771 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005772 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005773 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005774 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005775 return;
5776 }
5777
5778 // (C++ 13.3.2p2): A candidate function having more than m parameters
5779 // is viable only if the (m+1)st parameter has a default argument
5780 // (8.3.6). For the purposes of overload resolution, the
5781 // parameter list is truncated on the right, so that there are
5782 // exactly m parameters.
5783 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005784 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005785 // Not enough arguments.
5786 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005787 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005788 return;
5789 }
5790
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005791 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005792 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005793 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005794 // Skip the check for callers that are implicit members, because in this
5795 // case we may not yet know what the member's target is; the target is
5796 // inferred for the member automatically, based on the bases and fields of
5797 // the class.
5798 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005799 Candidate.Viable = false;
5800 Candidate.FailureKind = ovl_fail_bad_target;
5801 return;
5802 }
5803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005804 // Determine the implicit conversion sequences for each of the
5805 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005806 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005807 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005808 // (C++ 13.3.2p3): for F to be a viable function, there shall
5809 // exist for each argument an implicit conversion sequence
5810 // (13.3.3.1) that converts that argument to the corresponding
5811 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005812 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005813 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005814 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005815 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005816 /*InOverloadResolution=*/true,
5817 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005818 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005819 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005820 if (Candidate.Conversions[ArgIdx].isBad()) {
5821 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005822 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005823 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005824 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005825 } else {
5826 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5827 // argument for which there is no corresponding parameter is
5828 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005829 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005830 }
5831 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005832
5833 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5834 Candidate.Viable = false;
5835 Candidate.FailureKind = ovl_fail_enable_if;
5836 Candidate.DeductionFailure.Data = FailedAttr;
5837 return;
5838 }
5839}
5840
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005841ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005842 bool IsInstance) {
5843 SmallVector<ObjCMethodDecl*, 4> Methods;
5844 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5845 return nullptr;
5846
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005847 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5848 bool Match = true;
5849 ObjCMethodDecl *Method = Methods[b];
5850 unsigned NumNamedArgs = Sel.getNumArgs();
5851 // Method might have more arguments than selector indicates. This is due
5852 // to addition of c-style arguments in method.
5853 if (Method->param_size() > NumNamedArgs)
5854 NumNamedArgs = Method->param_size();
5855 if (Args.size() < NumNamedArgs)
5856 continue;
5857
5858 for (unsigned i = 0; i < NumNamedArgs; i++) {
5859 // We can't do any type-checking on a type-dependent argument.
5860 if (Args[i]->isTypeDependent()) {
5861 Match = false;
5862 break;
5863 }
5864
5865 ParmVarDecl *param = Method->parameters()[i];
5866 Expr *argExpr = Args[i];
5867 assert(argExpr && "SelectBestMethod(): missing expression");
5868
5869 // Strip the unbridged-cast placeholder expression off unless it's
5870 // a consumed argument.
5871 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5872 !param->hasAttr<CFConsumedAttr>())
5873 argExpr = stripARCUnbridgedCast(argExpr);
5874
5875 // If the parameter is __unknown_anytype, move on to the next method.
5876 if (param->getType() == Context.UnknownAnyTy) {
5877 Match = false;
5878 break;
5879 }
George Burgess IV45461812015-10-11 20:13:20 +00005880
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005881 ImplicitConversionSequence ConversionState
5882 = TryCopyInitialization(*this, argExpr, param->getType(),
5883 /*SuppressUserConversions*/false,
5884 /*InOverloadResolution=*/true,
5885 /*AllowObjCWritebackConversion=*/
5886 getLangOpts().ObjCAutoRefCount,
5887 /*AllowExplicit*/false);
5888 if (ConversionState.isBad()) {
5889 Match = false;
5890 break;
5891 }
5892 }
5893 // Promote additional arguments to variadic methods.
5894 if (Match && Method->isVariadic()) {
5895 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5896 if (Args[i]->isTypeDependent()) {
5897 Match = false;
5898 break;
5899 }
5900 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5901 nullptr);
5902 if (Arg.isInvalid()) {
5903 Match = false;
5904 break;
5905 }
5906 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005907 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005908 // Check for extra arguments to non-variadic methods.
5909 if (Args.size() != NumNamedArgs)
5910 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005911 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5912 // Special case when selectors have no argument. In this case, select
5913 // one with the most general result type of 'id'.
5914 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5915 QualType ReturnT = Methods[b]->getReturnType();
5916 if (ReturnT->isObjCIdType())
5917 return Methods[b];
5918 }
5919 }
5920 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005921
5922 if (Match)
5923 return Method;
5924 }
5925 return nullptr;
5926}
5927
George Burgess IV2a6150d2015-10-16 01:17:38 +00005928// specific_attr_iterator iterates over enable_if attributes in reverse, and
5929// enable_if is order-sensitive. As a result, we need to reverse things
5930// sometimes. Size of 4 elements is arbitrary.
5931static SmallVector<EnableIfAttr *, 4>
5932getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5933 SmallVector<EnableIfAttr *, 4> Result;
5934 if (!Function->hasAttrs())
5935 return Result;
5936
5937 const auto &FuncAttrs = Function->getAttrs();
5938 for (Attr *Attr : FuncAttrs)
5939 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5940 Result.push_back(EnableIf);
5941
5942 std::reverse(Result.begin(), Result.end());
5943 return Result;
5944}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005945
5946EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5947 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005948 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5949 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005950 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005951
5952 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005953 SmallVector<Expr *, 16> ConvertedArgs;
5954 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005955 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005956
5957 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005958 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5959 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005960 !cast<CXXMethodDecl>(Function)->isStatic() &&
5961 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005962 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5963 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005964 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005965 Method, Method);
5966 if (R.isInvalid()) {
5967 InitializationFailed = true;
5968 break;
5969 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005970 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005971 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005972 } else {
5973 ExprResult R =
5974 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5975 Context,
5976 Function->getParamDecl(i)),
5977 SourceLocation(),
5978 Args[i]);
5979 if (R.isInvalid()) {
5980 InitializationFailed = true;
5981 break;
5982 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005983 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005984 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005985 }
5986 }
5987
5988 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005989 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005990
Nick Lewyckye283c552015-08-25 22:33:16 +00005991 // Push default arguments if needed.
5992 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5993 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5994 ParmVarDecl *P = Function->getParamDecl(i);
5995 ExprResult R = PerformCopyInitialization(
5996 InitializedEntity::InitializeParameter(Context,
5997 Function->getParamDecl(i)),
5998 SourceLocation(),
5999 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6000 : P->getDefaultArg());
6001 if (R.isInvalid()) {
6002 InitializationFailed = true;
6003 break;
6004 }
6005 ContainsValueDependentExpr |= R.get()->isValueDependent();
6006 ConvertedArgs.push_back(R.get());
6007 }
6008
6009 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006010 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006011 }
6012
George Burgess IV2a6150d2015-10-16 01:17:38 +00006013 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006014 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006015 if (EIA->getCond()->isValueDependent()) {
6016 // Don't even try now, we'll examine it after instantiation.
6017 continue;
6018 }
6019
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006020 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00006021 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6022 if (!ContainsValueDependentExpr)
6023 return EIA;
6024 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006025 return EIA;
6026 }
6027 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006028 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006029}
6030
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006031/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006032/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006033void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006034 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006035 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006036 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006037 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006038 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006039 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006040 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006042 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006043 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006044 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006045 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006046 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006047 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006048 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006049 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006050 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006051 } else {
John McCalla0296f72010-03-19 07:35:19 +00006052 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006053 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6054 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006055 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006056 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006057 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006058 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006059 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006060 CandidateSet, SuppressUserConversions,
6061 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006062 else
John McCalla0296f72010-03-19 07:35:19 +00006063 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006064 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006065 CandidateSet, SuppressUserConversions,
6066 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006067 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006068 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006069}
6070
John McCallf0f1cf02009-11-17 07:50:12 +00006071/// AddMethodCandidate - Adds a named decl (which is some kind of
6072/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006073void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006074 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006075 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006076 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006077 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006078 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006079 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006080 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006081
6082 if (isa<UsingShadowDecl>(Decl))
6083 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006084
John McCallf0f1cf02009-11-17 07:50:12 +00006085 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6086 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6087 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006088 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006089 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006090 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006091 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006092 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006093 } else {
John McCalla0296f72010-03-19 07:35:19 +00006094 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006095 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006096 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006097 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006098 }
6099}
6100
Douglas Gregor436424c2008-11-18 23:14:02 +00006101/// AddMethodCandidate - Adds the given C++ member function to the set
6102/// of candidate functions, using the given function call arguments
6103/// and the object argument (@c Object). For example, in a call
6104/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6105/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6106/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006107/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006108void
John McCalla0296f72010-03-19 07:35:19 +00006109Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006110 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006111 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006112 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006113 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006114 bool SuppressUserConversions,
6115 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006116 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006117 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006118 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006119 assert(!isa<CXXConstructorDecl>(Method) &&
6120 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006121
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006122 if (!CandidateSet.isNewCandidate(Method))
6123 return;
6124
Richard Smith8b86f2d2013-11-04 01:48:18 +00006125 // C++11 [class.copy]p23: [DR1402]
6126 // A defaulted move assignment operator that is defined as deleted is
6127 // ignored by overload resolution.
6128 if (Method->isDefaulted() && Method->isDeleted() &&
6129 Method->isMoveAssignmentOperator())
6130 return;
6131
Douglas Gregor27381f32009-11-23 12:27:39 +00006132 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006133 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006134
Douglas Gregor436424c2008-11-18 23:14:02 +00006135 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006136 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006137 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006138 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006139 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006140 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006141 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006142
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006143 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006144
6145 // (C++ 13.3.2p2): A candidate function having fewer than m
6146 // parameters is viable only if it has an ellipsis in its parameter
6147 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006148 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6149 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006150 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006151 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006152 return;
6153 }
6154
6155 // (C++ 13.3.2p2): A candidate function having more than m parameters
6156 // is viable only if the (m+1)st parameter has a default argument
6157 // (8.3.6). For the purposes of overload resolution, the
6158 // parameter list is truncated on the right, so that there are
6159 // exactly m parameters.
6160 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006161 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006162 // Not enough arguments.
6163 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006164 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006165 return;
6166 }
6167
6168 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006169
John McCall6e9f8f62009-12-03 04:06:58 +00006170 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006171 // The implicit object argument is ignored.
6172 Candidate.IgnoreObjectArgument = true;
6173 else {
6174 // Determine the implicit conversion sequence for the object
6175 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006176 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6177 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6178 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006179 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006180 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006181 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006182 return;
6183 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006184 }
6185
Eli Bendersky291a57e2014-09-25 23:59:08 +00006186 // (CUDA B.1): Check for invalid calls between targets.
6187 if (getLangOpts().CUDA)
6188 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6189 if (CheckCUDATarget(Caller, Method)) {
6190 Candidate.Viable = false;
6191 Candidate.FailureKind = ovl_fail_bad_target;
6192 return;
6193 }
6194
Douglas Gregor436424c2008-11-18 23:14:02 +00006195 // Determine the implicit conversion sequences for each of the
6196 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006197 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006198 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006199 // (C++ 13.3.2p3): for F to be a viable function, there shall
6200 // exist for each argument an implicit conversion sequence
6201 // (13.3.3.1) that converts that argument to the corresponding
6202 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006203 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006204 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006205 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006207 /*InOverloadResolution=*/true,
6208 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006209 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006210 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006211 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006212 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006213 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006214 }
6215 } else {
6216 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6217 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006218 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006219 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006220 }
6221 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006222
6223 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6224 Candidate.Viable = false;
6225 Candidate.FailureKind = ovl_fail_enable_if;
6226 Candidate.DeductionFailure.Data = FailedAttr;
6227 return;
6228 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006229}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006230
Douglas Gregor97628d62009-08-21 00:16:32 +00006231/// \brief Add a C++ member function template as a candidate to the candidate
6232/// set, using template argument deduction to produce an appropriate member
6233/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006234void
Douglas Gregor97628d62009-08-21 00:16:32 +00006235Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006236 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006237 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006238 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006239 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006240 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006241 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006242 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006243 bool SuppressUserConversions,
6244 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006245 if (!CandidateSet.isNewCandidate(MethodTmpl))
6246 return;
6247
Douglas Gregor97628d62009-08-21 00:16:32 +00006248 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006249 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006250 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006251 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006252 // candidate functions in the usual way.113) A given name can refer to one
6253 // or more function templates and also to a set of overloaded non-template
6254 // functions. In such a case, the candidate functions generated from each
6255 // function template are combined with the set of non-template candidate
6256 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006257 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006258 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006259 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006260 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006261 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006262 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006263 Candidate.FoundDecl = FoundDecl;
6264 Candidate.Function = MethodTmpl->getTemplatedDecl();
6265 Candidate.Viable = false;
6266 Candidate.FailureKind = ovl_fail_bad_deduction;
6267 Candidate.IsSurrogate = false;
6268 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006269 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006270 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006271 Info);
6272 return;
6273 }
Mike Stump11289f42009-09-09 15:08:12 +00006274
Douglas Gregor97628d62009-08-21 00:16:32 +00006275 // Add the function template specialization produced by template argument
6276 // deduction as a candidate.
6277 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006278 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006279 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006280 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006281 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006282 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006283}
6284
Douglas Gregor05155d82009-08-21 23:19:43 +00006285/// \brief Add a C++ function template specialization as a candidate
6286/// in the candidate set, using template argument deduction to produce
6287/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006288void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006289Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006290 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006291 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006292 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006293 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006294 bool SuppressUserConversions,
6295 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006296 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6297 return;
6298
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006299 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006300 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006301 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006302 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006303 // candidate functions in the usual way.113) A given name can refer to one
6304 // or more function templates and also to a set of overloaded non-template
6305 // functions. In such a case, the candidate functions generated from each
6306 // function template are combined with the set of non-template candidate
6307 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006308 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006309 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006310 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006311 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006312 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006313 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006314 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006315 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6316 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006317 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006318 Candidate.IsSurrogate = false;
6319 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006320 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006321 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006322 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006323 return;
6324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006326 // Add the function template specialization produced by template argument
6327 // deduction as a candidate.
6328 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006329 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006330 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006331}
Mike Stump11289f42009-09-09 15:08:12 +00006332
Douglas Gregor4b60a152013-11-07 22:34:54 +00006333/// Determine whether this is an allowable conversion from the result
6334/// of an explicit conversion operator to the expected type, per C++
6335/// [over.match.conv]p1 and [over.match.ref]p1.
6336///
6337/// \param ConvType The return type of the conversion function.
6338///
6339/// \param ToType The type we are converting to.
6340///
6341/// \param AllowObjCPointerConversion Allow a conversion from one
6342/// Objective-C pointer to another.
6343///
6344/// \returns true if the conversion is allowable, false otherwise.
6345static bool isAllowableExplicitConversion(Sema &S,
6346 QualType ConvType, QualType ToType,
6347 bool AllowObjCPointerConversion) {
6348 QualType ToNonRefType = ToType.getNonReferenceType();
6349
6350 // Easy case: the types are the same.
6351 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6352 return true;
6353
6354 // Allow qualification conversions.
6355 bool ObjCLifetimeConversion;
6356 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6357 ObjCLifetimeConversion))
6358 return true;
6359
6360 // If we're not allowed to consider Objective-C pointer conversions,
6361 // we're done.
6362 if (!AllowObjCPointerConversion)
6363 return false;
6364
6365 // Is this an Objective-C pointer conversion?
6366 bool IncompatibleObjC = false;
6367 QualType ConvertedType;
6368 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6369 IncompatibleObjC);
6370}
6371
Douglas Gregora1f013e2008-11-07 22:36:19 +00006372/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006373/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006374/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006375/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006376/// (which may or may not be the same type as the type that the
6377/// conversion function produces).
6378void
6379Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006380 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006381 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006382 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006383 OverloadCandidateSet& CandidateSet,
6384 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006385 assert(!Conversion->getDescribedFunctionTemplate() &&
6386 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006387 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006388 if (!CandidateSet.isNewCandidate(Conversion))
6389 return;
6390
Richard Smith2a7d4812013-05-04 07:00:32 +00006391 // If the conversion function has an undeduced return type, trigger its
6392 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006393 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006394 if (DeduceReturnType(Conversion, From->getExprLoc()))
6395 return;
6396 ConvType = Conversion->getConversionType().getNonReferenceType();
6397 }
6398
Richard Smith089c3162013-09-21 21:55:46 +00006399 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6400 // operator is only a candidate if its return type is the target type or
6401 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006402 if (Conversion->isExplicit() &&
6403 !isAllowableExplicitConversion(*this, ConvType, ToType,
6404 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006405 return;
6406
Douglas Gregor27381f32009-11-23 12:27:39 +00006407 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006408 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006409
Douglas Gregora1f013e2008-11-07 22:36:19 +00006410 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006411 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006412 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006413 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006414 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006415 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006416 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006417 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006418 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006419 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006420 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006421
Douglas Gregor6affc782010-08-19 15:37:02 +00006422 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006423 // For conversion functions, the function is considered to be a member of
6424 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006425 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006426 //
6427 // Determine the implicit conversion sequence for the implicit
6428 // object parameter.
6429 QualType ImplicitParamType = From->getType();
6430 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6431 ImplicitParamType = FromPtrType->getPointeeType();
6432 CXXRecordDecl *ConversionContext
6433 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006434
Richard Smith0f59cb32015-12-18 21:45:41 +00006435 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6436 *this, CandidateSet.getLocation(), From->getType(),
6437 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438
John McCall0d1da222010-01-12 00:44:57 +00006439 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006440 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006441 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006442 return;
6443 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006444
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006445 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006446 // derived to base as such conversions are given Conversion Rank. They only
6447 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6448 QualType FromCanon
6449 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6450 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006451 if (FromCanon == ToCanon ||
6452 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006453 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006454 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006455 return;
6456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006457
Douglas Gregora1f013e2008-11-07 22:36:19 +00006458 // To determine what the conversion from the result of calling the
6459 // conversion function to the type we're eventually trying to
6460 // convert to (ToType), we need to synthesize a call to the
6461 // conversion function and attempt copy initialization from it. This
6462 // makes sure that we get the right semantics with respect to
6463 // lvalues/rvalues and the type. Fortunately, we can allocate this
6464 // call on the stack and we don't need its arguments to be
6465 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006466 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006467 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006468 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6469 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006470 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006471 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006472
Richard Smith48d24642011-07-13 22:53:21 +00006473 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006474 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006475 Candidate.Viable = false;
6476 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6477 return;
6478 }
6479
Richard Smith48d24642011-07-13 22:53:21 +00006480 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006481
Mike Stump11289f42009-09-09 15:08:12 +00006482 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006483 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6484 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006485 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006486 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006487 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006488 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006489 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006490 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006491 /*InOverloadResolution=*/false,
6492 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006493
John McCall0d1da222010-01-12 00:44:57 +00006494 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006495 case ImplicitConversionSequence::StandardConversion:
6496 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006497
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006498 // C++ [over.ics.user]p3:
6499 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006500 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006501 // shall have exact match rank.
6502 if (Conversion->getPrimaryTemplate() &&
6503 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6504 Candidate.Viable = false;
6505 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006506 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006508
Douglas Gregorcba72b12011-01-21 05:18:22 +00006509 // C++0x [dcl.init.ref]p5:
6510 // In the second case, if the reference is an rvalue reference and
6511 // the second standard conversion sequence of the user-defined
6512 // conversion sequence includes an lvalue-to-rvalue conversion, the
6513 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006514 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006515 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6516 Candidate.Viable = false;
6517 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006518 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006519 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006520 break;
6521
6522 case ImplicitConversionSequence::BadConversion:
6523 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006524 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006525 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006526
6527 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006528 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006529 "Can only end up with a standard conversion sequence or failure");
6530 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006531
Craig Topper5fc8fc22014-08-27 06:28:36 +00006532 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006533 Candidate.Viable = false;
6534 Candidate.FailureKind = ovl_fail_enable_if;
6535 Candidate.DeductionFailure.Data = FailedAttr;
6536 return;
6537 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006538}
6539
Douglas Gregor05155d82009-08-21 23:19:43 +00006540/// \brief Adds a conversion function template specialization
6541/// candidate to the overload set, using template argument deduction
6542/// to deduce the template arguments of the conversion function
6543/// template from the type that we are converting to (C++
6544/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006545void
Douglas Gregor05155d82009-08-21 23:19:43 +00006546Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006547 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006548 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +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(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6553 "Only conversion function templates permitted here");
6554
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006555 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6556 return;
6557
Craig Toppere6706e42012-09-19 02:26:47 +00006558 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006559 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006560 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006561 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006562 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006563 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006564 Candidate.FoundDecl = FoundDecl;
6565 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6566 Candidate.Viable = false;
6567 Candidate.FailureKind = ovl_fail_bad_deduction;
6568 Candidate.IsSurrogate = false;
6569 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006570 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006571 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006572 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006573 return;
6574 }
Mike Stump11289f42009-09-09 15:08:12 +00006575
Douglas Gregor05155d82009-08-21 23:19:43 +00006576 // Add the conversion function template specialization produced by
6577 // template argument deduction as a candidate.
6578 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006579 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006580 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006581}
6582
Douglas Gregorab7897a2008-11-19 22:57:39 +00006583/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6584/// converts the given @c Object to a function pointer via the
6585/// conversion function @c Conversion, and then attempts to call it
6586/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6587/// the type of function that we'll eventually be calling.
6588void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006589 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006590 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006591 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006592 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006593 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006594 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006595 if (!CandidateSet.isNewCandidate(Conversion))
6596 return;
6597
Douglas Gregor27381f32009-11-23 12:27:39 +00006598 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006599 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006600
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006601 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006602 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006603 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006604 Candidate.Surrogate = Conversion;
6605 Candidate.Viable = true;
6606 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006607 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006608 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006609
6610 // Determine the implicit conversion sequence for the implicit
6611 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006612 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6613 *this, CandidateSet.getLocation(), Object->getType(),
6614 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006615 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006616 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006617 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006618 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006619 return;
6620 }
6621
6622 // The first conversion is actually a user-defined conversion whose
6623 // first conversion is ObjectInit's standard conversion (which is
6624 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006625 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006626 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006627 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006628 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006629 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006630 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006631 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006632 = Candidate.Conversions[0].UserDefined.Before;
6633 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6634
Mike Stump11289f42009-09-09 15:08:12 +00006635 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006636 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006637
6638 // (C++ 13.3.2p2): A candidate function having fewer than m
6639 // parameters is viable only if it has an ellipsis in its parameter
6640 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006641 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006642 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006643 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006644 return;
6645 }
6646
6647 // Function types don't have any default arguments, so just check if
6648 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006649 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006650 // Not enough arguments.
6651 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006652 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006653 return;
6654 }
6655
6656 // Determine the implicit conversion sequences for each of the
6657 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006658 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006659 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006660 // (C++ 13.3.2p3): for F to be a viable function, there shall
6661 // exist for each argument an implicit conversion sequence
6662 // (13.3.3.1) that converts that argument to the corresponding
6663 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006664 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006665 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006666 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006667 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006668 /*InOverloadResolution=*/false,
6669 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006670 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006671 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006672 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006673 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006674 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006675 }
6676 } else {
6677 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6678 // argument for which there is no corresponding parameter is
6679 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006680 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006681 }
6682 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006683
Craig Topper5fc8fc22014-08-27 06:28:36 +00006684 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006685 Candidate.Viable = false;
6686 Candidate.FailureKind = ovl_fail_enable_if;
6687 Candidate.DeductionFailure.Data = FailedAttr;
6688 return;
6689 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006690}
6691
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006692/// \brief Add overload candidates for overloaded operators that are
6693/// member functions.
6694///
6695/// Add the overloaded operator candidates that are member functions
6696/// for the operator Op that was used in an operator expression such
6697/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6698/// CandidateSet will store the added overload candidates. (C++
6699/// [over.match.oper]).
6700void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6701 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006702 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006703 OverloadCandidateSet& CandidateSet,
6704 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006705 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6706
6707 // C++ [over.match.oper]p3:
6708 // For a unary operator @ with an operand of a type whose
6709 // cv-unqualified version is T1, and for a binary operator @ with
6710 // a left operand of a type whose cv-unqualified version is T1 and
6711 // a right operand of a type whose cv-unqualified version is T2,
6712 // three sets of candidate functions, designated member
6713 // candidates, non-member candidates and built-in candidates, are
6714 // constructed as follows:
6715 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006716
Richard Smith0feaf0c2013-04-20 12:41:22 +00006717 // -- If T1 is a complete class type or a class currently being
6718 // defined, the set of member candidates is the result of the
6719 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6720 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006721 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006722 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006723 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006724 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006725 // If the type is neither complete nor being defined, bail out now.
6726 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006727 return;
Mike Stump11289f42009-09-09 15:08:12 +00006728
John McCall27b18f82009-11-17 02:14:36 +00006729 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6730 LookupQualifiedName(Operators, T1Rec->getDecl());
6731 Operators.suppressDiagnostics();
6732
Mike Stump11289f42009-09-09 15:08:12 +00006733 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006734 OperEnd = Operators.end();
6735 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006736 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006737 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006738 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006739 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006740 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006741 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006742 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006743}
6744
Douglas Gregora11693b2008-11-12 17:17:38 +00006745/// AddBuiltinCandidate - Add a candidate for a built-in
6746/// operator. ResultTy and ParamTys are the result and parameter types
6747/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006748/// arguments being passed to the candidate. IsAssignmentOperator
6749/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006750/// operator. NumContextualBoolArguments is the number of arguments
6751/// (at the beginning of the argument list) that will be contextually
6752/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006753void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006754 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006755 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006756 bool IsAssignmentOperator,
6757 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006758 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006759 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006760
Douglas Gregora11693b2008-11-12 17:17:38 +00006761 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006762 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006763 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6764 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006765 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006766 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006767 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006768 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006769 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6770
6771 // Determine the implicit conversion sequences for each of the
6772 // arguments.
6773 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006774 Candidate.ExplicitCallArguments = Args.size();
6775 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006776 // C++ [over.match.oper]p4:
6777 // For the built-in assignment operators, conversions of the
6778 // left operand are restricted as follows:
6779 // -- no temporaries are introduced to hold the left operand, and
6780 // -- no user-defined conversions are applied to the left
6781 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006782 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006783 //
6784 // We block these conversions by turning off user-defined
6785 // conversions, since that is the only way that initialization of
6786 // a reference to a non-class type can occur from something that
6787 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006788 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006789 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006790 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006791 Candidate.Conversions[ArgIdx]
6792 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006793 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006794 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006795 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006796 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006797 /*InOverloadResolution=*/false,
6798 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006799 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006800 }
John McCall0d1da222010-01-12 00:44:57 +00006801 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006802 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006803 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006804 break;
6805 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006806 }
6807}
6808
Craig Toppercd7b0332013-07-01 06:29:40 +00006809namespace {
6810
Douglas Gregora11693b2008-11-12 17:17:38 +00006811/// BuiltinCandidateTypeSet - A set of types that will be used for the
6812/// candidate operator functions for built-in operators (C++
6813/// [over.built]). The types are separated into pointer types and
6814/// enumeration types.
6815class BuiltinCandidateTypeSet {
6816 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006817 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006818
6819 /// PointerTypes - The set of pointer types that will be used in the
6820 /// built-in candidates.
6821 TypeSet PointerTypes;
6822
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006823 /// MemberPointerTypes - The set of member pointer types that will be
6824 /// used in the built-in candidates.
6825 TypeSet MemberPointerTypes;
6826
Douglas Gregora11693b2008-11-12 17:17:38 +00006827 /// EnumerationTypes - The set of enumeration types that will be
6828 /// used in the built-in candidates.
6829 TypeSet EnumerationTypes;
6830
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006832 /// candidates.
6833 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006834
6835 /// \brief A flag indicating non-record types are viable candidates
6836 bool HasNonRecordTypes;
6837
6838 /// \brief A flag indicating whether either arithmetic or enumeration types
6839 /// were present in the candidate set.
6840 bool HasArithmeticOrEnumeralTypes;
6841
Douglas Gregor80af3132011-05-21 23:15:46 +00006842 /// \brief A flag indicating whether the nullptr type was present in the
6843 /// candidate set.
6844 bool HasNullPtrType;
6845
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006846 /// Sema - The semantic analysis instance where we are building the
6847 /// candidate type set.
6848 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006849
Douglas Gregora11693b2008-11-12 17:17:38 +00006850 /// Context - The AST context in which we will build the type sets.
6851 ASTContext &Context;
6852
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006853 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6854 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006855 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006856
6857public:
6858 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006859 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006860
Mike Stump11289f42009-09-09 15:08:12 +00006861 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006862 : HasNonRecordTypes(false),
6863 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006864 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006865 SemaRef(SemaRef),
6866 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006867
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006868 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006869 SourceLocation Loc,
6870 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006871 bool AllowExplicitConversions,
6872 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006873
6874 /// pointer_begin - First pointer type found;
6875 iterator pointer_begin() { return PointerTypes.begin(); }
6876
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006877 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006878 iterator pointer_end() { return PointerTypes.end(); }
6879
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006880 /// member_pointer_begin - First member pointer type found;
6881 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6882
6883 /// member_pointer_end - Past the last member pointer type found;
6884 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6885
Douglas Gregora11693b2008-11-12 17:17:38 +00006886 /// enumeration_begin - First enumeration type found;
6887 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6888
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006889 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006890 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006892 iterator vector_begin() { return VectorTypes.begin(); }
6893 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006894
6895 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6896 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006897 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006898};
6899
Craig Toppercd7b0332013-07-01 06:29:40 +00006900} // end anonymous namespace
6901
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006902/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006903/// the set of pointer types along with any more-qualified variants of
6904/// that type. For example, if @p Ty is "int const *", this routine
6905/// will add "int const *", "int const volatile *", "int const
6906/// restrict *", and "int const volatile restrict *" to the set of
6907/// pointer types. Returns true if the add of @p Ty itself succeeded,
6908/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006909///
6910/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006911bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006912BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6913 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006914
Douglas Gregora11693b2008-11-12 17:17:38 +00006915 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006916 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006917 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006919 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006920 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006921 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006922 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006923 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6924 PointeeTy = PTy->getPointeeType();
6925 buildObjCPtr = true;
6926 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006927 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006928 }
6929
Sebastian Redl4990a632009-11-18 20:39:26 +00006930 // Don't add qualified variants of arrays. For one, they're not allowed
6931 // (the qualifier would sink to the element type), and for another, the
6932 // only overload situation where it matters is subscript or pointer +- int,
6933 // and those shouldn't have qualifier variants anyway.
6934 if (PointeeTy->isArrayType())
6935 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006936
John McCall8ccfcb52009-09-24 19:53:00 +00006937 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006938 bool hasVolatile = VisibleQuals.hasVolatile();
6939 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
John McCall8ccfcb52009-09-24 19:53:00 +00006941 // Iterate through all strict supersets of BaseCVR.
6942 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6943 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006944 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006945 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006946
6947 // Skip over restrict if no restrict found anywhere in the types, or if
6948 // the type cannot be restrict-qualified.
6949 if ((CVR & Qualifiers::Restrict) &&
6950 (!hasRestrict ||
6951 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6952 continue;
6953
6954 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006955 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006956
6957 // Build qualified pointer type.
6958 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006959 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006960 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006961 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006962 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6963
6964 // Insert qualified pointer type.
6965 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006966 }
6967
6968 return true;
6969}
6970
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006971/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6972/// to the set of pointer types along with any more-qualified variants of
6973/// that type. For example, if @p Ty is "int const *", this routine
6974/// will add "int const *", "int const volatile *", "int const
6975/// restrict *", and "int const volatile restrict *" to the set of
6976/// pointer types. Returns true if the add of @p Ty itself succeeded,
6977/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006978///
6979/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006980bool
6981BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6982 QualType Ty) {
6983 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006984 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006985 return false;
6986
John McCall8ccfcb52009-09-24 19:53:00 +00006987 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6988 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006989
John McCall8ccfcb52009-09-24 19:53:00 +00006990 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006991 // Don't add qualified variants of arrays. For one, they're not allowed
6992 // (the qualifier would sink to the element type), and for another, the
6993 // only overload situation where it matters is subscript or pointer +- int,
6994 // and those shouldn't have qualifier variants anyway.
6995 if (PointeeTy->isArrayType())
6996 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006997 const Type *ClassTy = PointerTy->getClass();
6998
6999 // Iterate through all strict supersets of the pointee type's CVR
7000 // qualifiers.
7001 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7002 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7003 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007004
John McCall8ccfcb52009-09-24 19:53:00 +00007005 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007006 MemberPointerTypes.insert(
7007 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007008 }
7009
7010 return true;
7011}
7012
Douglas Gregora11693b2008-11-12 17:17:38 +00007013/// AddTypesConvertedFrom - Add each of the types to which the type @p
7014/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007015/// primarily interested in pointer types and enumeration types. We also
7016/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007017/// AllowUserConversions is true if we should look at the conversion
7018/// functions of a class type, and AllowExplicitConversions if we
7019/// should also include the explicit conversion functions of a class
7020/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007021void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007022BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007023 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007024 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007025 bool AllowExplicitConversions,
7026 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007027 // Only deal with canonical types.
7028 Ty = Context.getCanonicalType(Ty);
7029
7030 // Look through reference types; they aren't part of the type of an
7031 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007032 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007033 Ty = RefTy->getPointeeType();
7034
John McCall33ddac02011-01-19 10:06:00 +00007035 // If we're dealing with an array type, decay to the pointer.
7036 if (Ty->isArrayType())
7037 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7038
7039 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007040 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007041
Chandler Carruth00a38332010-12-13 01:44:01 +00007042 // Flag if we ever add a non-record type.
7043 const RecordType *TyRec = Ty->getAs<RecordType>();
7044 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7045
Chandler Carruth00a38332010-12-13 01:44:01 +00007046 // Flag if we encounter an arithmetic type.
7047 HasArithmeticOrEnumeralTypes =
7048 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7049
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007050 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7051 PointerTypes.insert(Ty);
7052 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007053 // Insert our type, and its more-qualified variants, into the set
7054 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007055 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007056 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007057 } else if (Ty->isMemberPointerType()) {
7058 // Member pointers are far easier, since the pointee can't be converted.
7059 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7060 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007061 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007062 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007063 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007064 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007065 // We treat vector types as arithmetic types in many contexts as an
7066 // extension.
7067 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007068 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007069 } else if (Ty->isNullPtrType()) {
7070 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007071 } else if (AllowUserConversions && TyRec) {
7072 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007073 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007074 return;
Mike Stump11289f42009-09-09 15:08:12 +00007075
Chandler Carruth00a38332010-12-13 01:44:01 +00007076 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007077 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007078 if (isa<UsingShadowDecl>(D))
7079 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007080
Chandler Carruth00a38332010-12-13 01:44:01 +00007081 // Skip conversion function templates; they don't tell us anything
7082 // about which builtin types we can convert to.
7083 if (isa<FunctionTemplateDecl>(D))
7084 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007085
Chandler Carruth00a38332010-12-13 01:44:01 +00007086 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7087 if (AllowExplicitConversions || !Conv->isExplicit()) {
7088 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7089 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007090 }
7091 }
7092 }
7093}
7094
Douglas Gregor84605ae2009-08-24 13:43:27 +00007095/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7096/// the volatile- and non-volatile-qualified assignment operators for the
7097/// given type to the candidate set.
7098static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7099 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007100 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007101 OverloadCandidateSet &CandidateSet) {
7102 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007103
Douglas Gregor84605ae2009-08-24 13:43:27 +00007104 // T& operator=(T&, T)
7105 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7106 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007108 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007109
Douglas Gregor84605ae2009-08-24 13:43:27 +00007110 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7111 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007112 ParamTypes[0]
7113 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007114 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007115 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007116 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007117 }
7118}
Mike Stump11289f42009-09-09 15:08:12 +00007119
Sebastian Redl1054fae2009-10-25 17:03:50 +00007120/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7121/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007122static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7123 Qualifiers VRQuals;
7124 const RecordType *TyRec;
7125 if (const MemberPointerType *RHSMPType =
7126 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007127 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007128 else
7129 TyRec = ArgExpr->getType()->getAs<RecordType>();
7130 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007131 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007132 VRQuals.addVolatile();
7133 VRQuals.addRestrict();
7134 return VRQuals;
7135 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007136
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007137 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007138 if (!ClassDecl->hasDefinition())
7139 return VRQuals;
7140
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007141 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007142 if (isa<UsingShadowDecl>(D))
7143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7144 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007145 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7146 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7147 CanTy = ResTypeRef->getPointeeType();
7148 // Need to go down the pointer/mempointer chain and add qualifiers
7149 // as see them.
7150 bool done = false;
7151 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007152 if (CanTy.isRestrictQualified())
7153 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007154 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7155 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007156 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007157 CanTy->getAs<MemberPointerType>())
7158 CanTy = ResTypeMPtr->getPointeeType();
7159 else
7160 done = true;
7161 if (CanTy.isVolatileQualified())
7162 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007163 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7164 return VRQuals;
7165 }
7166 }
7167 }
7168 return VRQuals;
7169}
John McCall52872982010-11-13 05:51:15 +00007170
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007171namespace {
John McCall52872982010-11-13 05:51:15 +00007172
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007173/// \brief Helper class to manage the addition of builtin operator overload
7174/// candidates. It provides shared state and utility methods used throughout
7175/// the process, as well as a helper method to add each group of builtin
7176/// operator overloads from the standard to a candidate set.
7177class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007178 // Common instance state available to all overload candidate addition methods.
7179 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007180 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007181 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007182 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007183 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007184 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007185
Chandler Carruthc6586e52010-12-12 10:35:00 +00007186 // Define some constants used to index and iterate over the arithemetic types
7187 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007188 // The "promoted arithmetic types" are the arithmetic
7189 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007190 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007191 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007192 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007193 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007194 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007195 LastPromotedArithmeticType = 11;
7196 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007197
Chandler Carruthc6586e52010-12-12 10:35:00 +00007198 /// \brief Get the canonical type for a given arithmetic type index.
7199 CanQualType getArithmeticType(unsigned index) {
7200 assert(index < NumArithmeticTypes);
7201 static CanQualType ASTContext::* const
7202 ArithmeticTypes[NumArithmeticTypes] = {
7203 // Start of promoted types.
7204 &ASTContext::FloatTy,
7205 &ASTContext::DoubleTy,
7206 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007207
Chandler Carruthc6586e52010-12-12 10:35:00 +00007208 // Start of integral types.
7209 &ASTContext::IntTy,
7210 &ASTContext::LongTy,
7211 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007212 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007213 &ASTContext::UnsignedIntTy,
7214 &ASTContext::UnsignedLongTy,
7215 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007216 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007217 // End of promoted types.
7218
7219 &ASTContext::BoolTy,
7220 &ASTContext::CharTy,
7221 &ASTContext::WCharTy,
7222 &ASTContext::Char16Ty,
7223 &ASTContext::Char32Ty,
7224 &ASTContext::SignedCharTy,
7225 &ASTContext::ShortTy,
7226 &ASTContext::UnsignedCharTy,
7227 &ASTContext::UnsignedShortTy,
7228 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007229 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007230 };
7231 return S.Context.*ArithmeticTypes[index];
7232 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007233
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007234 /// \brief Gets the canonical type resulting from the usual arithemetic
7235 /// converions for the given arithmetic types.
7236 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7237 // Accelerator table for performing the usual arithmetic conversions.
7238 // The rules are basically:
7239 // - if either is floating-point, use the wider floating-point
7240 // - if same signedness, use the higher rank
7241 // - if same size, use unsigned of the higher rank
7242 // - use the larger type
7243 // These rules, together with the axiom that higher ranks are
7244 // never smaller, are sufficient to precompute all of these results
7245 // *except* when dealing with signed types of higher rank.
7246 // (we could precompute SLL x UI for all known platforms, but it's
7247 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007248 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007249 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007250 Dep=-1,
7251 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007252 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007253 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007254 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007255/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7256/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7257/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7258/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7259/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7260/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7261/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7262/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7263/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7264/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7265/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007266 };
7267
7268 assert(L < LastPromotedArithmeticType);
7269 assert(R < LastPromotedArithmeticType);
7270 int Idx = ConversionsTable[L][R];
7271
7272 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007273 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007274
7275 // Slow path: we need to compare widths.
7276 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007277 CanQualType LT = getArithmeticType(L),
7278 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007279 unsigned LW = S.Context.getIntWidth(LT),
7280 RW = S.Context.getIntWidth(RT);
7281
7282 // If they're different widths, use the signed type.
7283 if (LW > RW) return LT;
7284 else if (LW < RW) return RT;
7285
7286 // Otherwise, use the unsigned type of the signed type's rank.
7287 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7288 assert(L == SLL || R == SLL);
7289 return S.Context.UnsignedLongLongTy;
7290 }
7291
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007292 /// \brief Helper method to factor out the common pattern of adding overloads
7293 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007294 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007295 bool HasVolatile,
7296 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 QualType ParamTypes[2] = {
7298 S.Context.getLValueReferenceType(CandidateTy),
7299 S.Context.IntTy
7300 };
7301
7302 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007303 if (Args.size() == 1)
7304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007305 else
Richard Smithe54c3072013-05-05 15:51:06 +00007306 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007307
7308 // Use a heuristic to reduce number of builtin candidates in the set:
7309 // add volatile version only if there are conversions to a volatile type.
7310 if (HasVolatile) {
7311 ParamTypes[0] =
7312 S.Context.getLValueReferenceType(
7313 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007314 if (Args.size() == 1)
7315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007316 else
Richard Smithe54c3072013-05-05 15:51:06 +00007317 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007318 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007319
7320 // Add restrict version only if there are conversions to a restrict type
7321 // and our candidate type is a non-restrict-qualified pointer.
7322 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7323 !CandidateTy.isRestrictQualified()) {
7324 ParamTypes[0]
7325 = S.Context.getLValueReferenceType(
7326 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007327 if (Args.size() == 1)
7328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007329 else
Richard Smithe54c3072013-05-05 15:51:06 +00007330 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007331
7332 if (HasVolatile) {
7333 ParamTypes[0]
7334 = S.Context.getLValueReferenceType(
7335 S.Context.getCVRQualifiedType(CandidateTy,
7336 (Qualifiers::Volatile |
7337 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007338 if (Args.size() == 1)
7339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007340 else
Richard Smithe54c3072013-05-05 15:51:06 +00007341 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007342 }
7343 }
7344
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007345 }
7346
7347public:
7348 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007349 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007350 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007351 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007352 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007353 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007354 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007356 HasArithmeticOrEnumeralCandidateType(
7357 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 CandidateTypes(CandidateTypes),
7359 CandidateSet(CandidateSet) {
7360 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007361 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007362 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007363 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007364 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007365 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007366 assert(getArithmeticType(FirstPromotedArithmeticType)
7367 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007368 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007369 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007370 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007371 "Invalid last promoted arithmetic type");
7372 }
7373
7374 // C++ [over.built]p3:
7375 //
7376 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7377 // is either volatile or empty, there exist candidate operator
7378 // functions of the form
7379 //
7380 // VQ T& operator++(VQ T&);
7381 // T operator++(VQ T&, int);
7382 //
7383 // C++ [over.built]p4:
7384 //
7385 // For every pair (T, VQ), where T is an arithmetic type other
7386 // than bool, and VQ is either volatile or empty, there exist
7387 // candidate operator functions of the form
7388 //
7389 // VQ T& operator--(VQ T&);
7390 // T operator--(VQ T&, int);
7391 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007392 if (!HasArithmeticOrEnumeralCandidateType)
7393 return;
7394
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007395 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7396 Arith < NumArithmeticTypes; ++Arith) {
7397 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007398 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007399 VisibleTypeConversionsQuals.hasVolatile(),
7400 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007401 }
7402 }
7403
7404 // C++ [over.built]p5:
7405 //
7406 // For every pair (T, VQ), where T is a cv-qualified or
7407 // cv-unqualified object type, and VQ is either volatile or
7408 // empty, there exist candidate operator functions of the form
7409 //
7410 // T*VQ& operator++(T*VQ&);
7411 // T*VQ& operator--(T*VQ&);
7412 // T* operator++(T*VQ&, int);
7413 // T* operator--(T*VQ&, int);
7414 void addPlusPlusMinusMinusPointerOverloads() {
7415 for (BuiltinCandidateTypeSet::iterator
7416 Ptr = CandidateTypes[0].pointer_begin(),
7417 PtrEnd = CandidateTypes[0].pointer_end();
7418 Ptr != PtrEnd; ++Ptr) {
7419 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007420 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007421 continue;
7422
7423 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007424 (!(*Ptr).isVolatileQualified() &&
7425 VisibleTypeConversionsQuals.hasVolatile()),
7426 (!(*Ptr).isRestrictQualified() &&
7427 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 }
7429 }
7430
7431 // C++ [over.built]p6:
7432 // For every cv-qualified or cv-unqualified object type T, there
7433 // exist candidate operator functions of the form
7434 //
7435 // T& operator*(T*);
7436 //
7437 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007438 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007439 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007440 // T& operator*(T*);
7441 void addUnaryStarPointerOverloads() {
7442 for (BuiltinCandidateTypeSet::iterator
7443 Ptr = CandidateTypes[0].pointer_begin(),
7444 PtrEnd = CandidateTypes[0].pointer_end();
7445 Ptr != PtrEnd; ++Ptr) {
7446 QualType ParamTy = *Ptr;
7447 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007448 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7449 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450
Douglas Gregor02824322011-01-26 19:30:28 +00007451 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7452 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7453 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007455 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007456 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007457 }
7458 }
7459
7460 // C++ [over.built]p9:
7461 // For every promoted arithmetic type T, there exist candidate
7462 // operator functions of the form
7463 //
7464 // T operator+(T);
7465 // T operator-(T);
7466 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007467 if (!HasArithmeticOrEnumeralCandidateType)
7468 return;
7469
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007470 for (unsigned Arith = FirstPromotedArithmeticType;
7471 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007472 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007473 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007474 }
7475
7476 // Extension: We also add these operators for vector types.
7477 for (BuiltinCandidateTypeSet::iterator
7478 Vec = CandidateTypes[0].vector_begin(),
7479 VecEnd = CandidateTypes[0].vector_end();
7480 Vec != VecEnd; ++Vec) {
7481 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007482 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007483 }
7484 }
7485
7486 // C++ [over.built]p8:
7487 // For every type T, there exist candidate operator functions of
7488 // the form
7489 //
7490 // T* operator+(T*);
7491 void addUnaryPlusPointerOverloads() {
7492 for (BuiltinCandidateTypeSet::iterator
7493 Ptr = CandidateTypes[0].pointer_begin(),
7494 PtrEnd = CandidateTypes[0].pointer_end();
7495 Ptr != PtrEnd; ++Ptr) {
7496 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007497 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007498 }
7499 }
7500
7501 // C++ [over.built]p10:
7502 // For every promoted integral type T, there exist candidate
7503 // operator functions of the form
7504 //
7505 // T operator~(T);
7506 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007507 if (!HasArithmeticOrEnumeralCandidateType)
7508 return;
7509
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007510 for (unsigned Int = FirstPromotedIntegralType;
7511 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007512 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007513 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 }
7515
7516 // Extension: We also add this operator for vector types.
7517 for (BuiltinCandidateTypeSet::iterator
7518 Vec = CandidateTypes[0].vector_begin(),
7519 VecEnd = CandidateTypes[0].vector_end();
7520 Vec != VecEnd; ++Vec) {
7521 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007522 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007523 }
7524 }
7525
7526 // C++ [over.match.oper]p16:
7527 // For every pointer to member type T, there exist candidate operator
7528 // functions of the form
7529 //
7530 // bool operator==(T,T);
7531 // bool operator!=(T,T);
7532 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7533 /// Set of (canonical) types that we've already handled.
7534 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7535
Richard Smithe54c3072013-05-05 15:51:06 +00007536 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007537 for (BuiltinCandidateTypeSet::iterator
7538 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7539 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7540 MemPtr != MemPtrEnd;
7541 ++MemPtr) {
7542 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007543 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007544 continue;
7545
7546 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007547 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007548 }
7549 }
7550 }
7551
7552 // C++ [over.built]p15:
7553 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007554 // For every T, where T is an enumeration type, a pointer type, or
7555 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007556 //
7557 // bool operator<(T, T);
7558 // bool operator>(T, T);
7559 // bool operator<=(T, T);
7560 // bool operator>=(T, T);
7561 // bool operator==(T, T);
7562 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007563 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007564 // C++ [over.match.oper]p3:
7565 // [...]the built-in candidates include all of the candidate operator
7566 // functions defined in 13.6 that, compared to the given operator, [...]
7567 // do not have the same parameter-type-list as any non-template non-member
7568 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007569 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007570 // Note that in practice, this only affects enumeration types because there
7571 // aren't any built-in candidates of record type, and a user-defined operator
7572 // must have an operand of record or enumeration type. Also, the only other
7573 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007574 // cannot be overloaded for enumeration types, so this is the only place
7575 // where we must suppress candidates like this.
7576 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7577 UserDefinedBinaryOperators;
7578
Richard Smithe54c3072013-05-05 15:51:06 +00007579 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007580 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7581 CandidateTypes[ArgIdx].enumeration_end()) {
7582 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7583 CEnd = CandidateSet.end();
7584 C != CEnd; ++C) {
7585 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7586 continue;
7587
Eli Friedman14f082b2012-09-18 21:52:24 +00007588 if (C->Function->isFunctionTemplateSpecialization())
7589 continue;
7590
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007591 QualType FirstParamType =
7592 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7593 QualType SecondParamType =
7594 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7595
7596 // Skip if either parameter isn't of enumeral type.
7597 if (!FirstParamType->isEnumeralType() ||
7598 !SecondParamType->isEnumeralType())
7599 continue;
7600
7601 // Add this operator to the set of known user-defined operators.
7602 UserDefinedBinaryOperators.insert(
7603 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7604 S.Context.getCanonicalType(SecondParamType)));
7605 }
7606 }
7607 }
7608
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007609 /// Set of (canonical) types that we've already handled.
7610 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7611
Richard Smithe54c3072013-05-05 15:51:06 +00007612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007613 for (BuiltinCandidateTypeSet::iterator
7614 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7615 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7616 Ptr != PtrEnd; ++Ptr) {
7617 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007618 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007619 continue;
7620
7621 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007622 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 }
7624 for (BuiltinCandidateTypeSet::iterator
7625 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7626 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7627 Enum != EnumEnd; ++Enum) {
7628 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7629
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007630 // Don't add the same builtin candidate twice, or if a user defined
7631 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007632 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007633 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7634 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007635 continue;
7636
7637 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007638 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007639 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007640
7641 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7642 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007643 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007644 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007645 NullPtrTy))) {
7646 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007647 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007648 CandidateSet);
7649 }
7650 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 }
7652 }
7653
7654 // C++ [over.built]p13:
7655 //
7656 // For every cv-qualified or cv-unqualified object type T
7657 // there exist candidate operator functions of the form
7658 //
7659 // T* operator+(T*, ptrdiff_t);
7660 // T& operator[](T*, ptrdiff_t); [BELOW]
7661 // T* operator-(T*, ptrdiff_t);
7662 // T* operator+(ptrdiff_t, T*);
7663 // T& operator[](ptrdiff_t, T*); [BELOW]
7664 //
7665 // C++ [over.built]p14:
7666 //
7667 // For every T, where T is a pointer to object type, there
7668 // exist candidate operator functions of the form
7669 //
7670 // ptrdiff_t operator-(T, T);
7671 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7672 /// Set of (canonical) types that we've already handled.
7673 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7674
7675 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007676 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007677 S.Context.getPointerDiffType(),
7678 S.Context.getPointerDiffType(),
7679 };
7680 for (BuiltinCandidateTypeSet::iterator
7681 Ptr = CandidateTypes[Arg].pointer_begin(),
7682 PtrEnd = CandidateTypes[Arg].pointer_end();
7683 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007684 QualType PointeeTy = (*Ptr)->getPointeeType();
7685 if (!PointeeTy->isObjectType())
7686 continue;
7687
Eric Christopher9207a522015-08-21 16:24:01 +00007688 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007689 if (Arg == 0 || Op == OO_Plus) {
7690 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7691 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007692 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007693 }
7694 if (Op == OO_Minus) {
7695 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007696 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007697 continue;
7698
7699 QualType ParamTypes[2] = { *Ptr, *Ptr };
7700 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007701 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 }
7703 }
7704 }
7705 }
7706
7707 // C++ [over.built]p12:
7708 //
7709 // For every pair of promoted arithmetic types L and R, there
7710 // exist candidate operator functions of the form
7711 //
7712 // LR operator*(L, R);
7713 // LR operator/(L, R);
7714 // LR operator+(L, R);
7715 // LR operator-(L, R);
7716 // bool operator<(L, R);
7717 // bool operator>(L, R);
7718 // bool operator<=(L, R);
7719 // bool operator>=(L, R);
7720 // bool operator==(L, R);
7721 // bool operator!=(L, R);
7722 //
7723 // where LR is the result of the usual arithmetic conversions
7724 // between types L and R.
7725 //
7726 // C++ [over.built]p24:
7727 //
7728 // For every pair of promoted arithmetic types L and R, there exist
7729 // candidate operator functions of the form
7730 //
7731 // LR operator?(bool, L, R);
7732 //
7733 // where LR is the result of the usual arithmetic conversions
7734 // between types L and R.
7735 // Our candidates ignore the first parameter.
7736 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007737 if (!HasArithmeticOrEnumeralCandidateType)
7738 return;
7739
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007740 for (unsigned Left = FirstPromotedArithmeticType;
7741 Left < LastPromotedArithmeticType; ++Left) {
7742 for (unsigned Right = FirstPromotedArithmeticType;
7743 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007744 QualType LandR[2] = { getArithmeticType(Left),
7745 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007746 QualType Result =
7747 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007748 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007749 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007750 }
7751 }
7752
7753 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7754 // conditional operator for vector types.
7755 for (BuiltinCandidateTypeSet::iterator
7756 Vec1 = CandidateTypes[0].vector_begin(),
7757 Vec1End = CandidateTypes[0].vector_end();
7758 Vec1 != Vec1End; ++Vec1) {
7759 for (BuiltinCandidateTypeSet::iterator
7760 Vec2 = CandidateTypes[1].vector_begin(),
7761 Vec2End = CandidateTypes[1].vector_end();
7762 Vec2 != Vec2End; ++Vec2) {
7763 QualType LandR[2] = { *Vec1, *Vec2 };
7764 QualType Result = S.Context.BoolTy;
7765 if (!isComparison) {
7766 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7767 Result = *Vec1;
7768 else
7769 Result = *Vec2;
7770 }
7771
Richard Smithe54c3072013-05-05 15:51:06 +00007772 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007773 }
7774 }
7775 }
7776
7777 // C++ [over.built]p17:
7778 //
7779 // For every pair of promoted integral types L and R, there
7780 // exist candidate operator functions of the form
7781 //
7782 // LR operator%(L, R);
7783 // LR operator&(L, R);
7784 // LR operator^(L, R);
7785 // LR operator|(L, R);
7786 // L operator<<(L, R);
7787 // L operator>>(L, R);
7788 //
7789 // where LR is the result of the usual arithmetic conversions
7790 // between types L and R.
7791 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007792 if (!HasArithmeticOrEnumeralCandidateType)
7793 return;
7794
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007795 for (unsigned Left = FirstPromotedIntegralType;
7796 Left < LastPromotedIntegralType; ++Left) {
7797 for (unsigned Right = FirstPromotedIntegralType;
7798 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007799 QualType LandR[2] = { getArithmeticType(Left),
7800 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007801 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7802 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007803 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007804 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007805 }
7806 }
7807 }
7808
7809 // C++ [over.built]p20:
7810 //
7811 // For every pair (T, VQ), where T is an enumeration or
7812 // pointer to member type and VQ is either volatile or
7813 // empty, there exist candidate operator functions of the form
7814 //
7815 // VQ T& operator=(VQ T&, T);
7816 void addAssignmentMemberPointerOrEnumeralOverloads() {
7817 /// Set of (canonical) types that we've already handled.
7818 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7819
7820 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7821 for (BuiltinCandidateTypeSet::iterator
7822 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7823 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7824 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007825 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826 continue;
7827
Richard Smithe54c3072013-05-05 15:51:06 +00007828 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 }
7830
7831 for (BuiltinCandidateTypeSet::iterator
7832 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7833 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7834 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007835 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007836 continue;
7837
Richard Smithe54c3072013-05-05 15:51:06 +00007838 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007839 }
7840 }
7841 }
7842
7843 // C++ [over.built]p19:
7844 //
7845 // For every pair (T, VQ), where T is any type and VQ is either
7846 // volatile or empty, there exist candidate operator functions
7847 // of the form
7848 //
7849 // T*VQ& operator=(T*VQ&, T*);
7850 //
7851 // C++ [over.built]p21:
7852 //
7853 // For every pair (T, VQ), where T is a cv-qualified or
7854 // cv-unqualified object type and VQ is either volatile or
7855 // empty, there exist candidate operator functions of the form
7856 //
7857 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7858 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7859 void addAssignmentPointerOverloads(bool isEqualOp) {
7860 /// Set of (canonical) types that we've already handled.
7861 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7862
7863 for (BuiltinCandidateTypeSet::iterator
7864 Ptr = CandidateTypes[0].pointer_begin(),
7865 PtrEnd = CandidateTypes[0].pointer_end();
7866 Ptr != PtrEnd; ++Ptr) {
7867 // If this is operator=, keep track of the builtin candidates we added.
7868 if (isEqualOp)
7869 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007870 else if (!(*Ptr)->getPointeeType()->isObjectType())
7871 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872
7873 // non-volatile version
7874 QualType ParamTypes[2] = {
7875 S.Context.getLValueReferenceType(*Ptr),
7876 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7877 };
Richard Smithe54c3072013-05-05 15:51:06 +00007878 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 /*IsAssigmentOperator=*/ isEqualOp);
7880
Douglas Gregor5bee2582012-06-04 00:15:09 +00007881 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7882 VisibleTypeConversionsQuals.hasVolatile();
7883 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 // volatile version
7885 ParamTypes[0] =
7886 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007887 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888 /*IsAssigmentOperator=*/isEqualOp);
7889 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007890
7891 if (!(*Ptr).isRestrictQualified() &&
7892 VisibleTypeConversionsQuals.hasRestrict()) {
7893 // restrict version
7894 ParamTypes[0]
7895 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007897 /*IsAssigmentOperator=*/isEqualOp);
7898
7899 if (NeedVolatile) {
7900 // volatile restrict version
7901 ParamTypes[0]
7902 = S.Context.getLValueReferenceType(
7903 S.Context.getCVRQualifiedType(*Ptr,
7904 (Qualifiers::Volatile |
7905 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007906 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007907 /*IsAssigmentOperator=*/isEqualOp);
7908 }
7909 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007910 }
7911
7912 if (isEqualOp) {
7913 for (BuiltinCandidateTypeSet::iterator
7914 Ptr = CandidateTypes[1].pointer_begin(),
7915 PtrEnd = CandidateTypes[1].pointer_end();
7916 Ptr != PtrEnd; ++Ptr) {
7917 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007918 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007919 continue;
7920
Chandler Carruth8e543b32010-12-12 08:17:55 +00007921 QualType ParamTypes[2] = {
7922 S.Context.getLValueReferenceType(*Ptr),
7923 *Ptr,
7924 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007925
7926 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007928 /*IsAssigmentOperator=*/true);
7929
Douglas Gregor5bee2582012-06-04 00:15:09 +00007930 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7931 VisibleTypeConversionsQuals.hasVolatile();
7932 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007933 // volatile version
7934 ParamTypes[0] =
7935 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007936 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7937 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007938 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007939
7940 if (!(*Ptr).isRestrictQualified() &&
7941 VisibleTypeConversionsQuals.hasRestrict()) {
7942 // restrict version
7943 ParamTypes[0]
7944 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007945 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7946 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007947
7948 if (NeedVolatile) {
7949 // volatile restrict version
7950 ParamTypes[0]
7951 = S.Context.getLValueReferenceType(
7952 S.Context.getCVRQualifiedType(*Ptr,
7953 (Qualifiers::Volatile |
7954 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007955 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7956 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007957 }
7958 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007959 }
7960 }
7961 }
7962
7963 // C++ [over.built]p18:
7964 //
7965 // For every triple (L, VQ, R), where L is an arithmetic type,
7966 // VQ is either volatile or empty, and R is a promoted
7967 // arithmetic type, there exist candidate operator functions of
7968 // the form
7969 //
7970 // VQ L& operator=(VQ L&, R);
7971 // VQ L& operator*=(VQ L&, R);
7972 // VQ L& operator/=(VQ L&, R);
7973 // VQ L& operator+=(VQ L&, R);
7974 // VQ L& operator-=(VQ L&, R);
7975 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007976 if (!HasArithmeticOrEnumeralCandidateType)
7977 return;
7978
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7980 for (unsigned Right = FirstPromotedArithmeticType;
7981 Right < LastPromotedArithmeticType; ++Right) {
7982 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007983 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007984
7985 // Add this built-in operator as a candidate (VQ is empty).
7986 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007987 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007988 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007989 /*IsAssigmentOperator=*/isEqualOp);
7990
7991 // Add this built-in operator as a candidate (VQ is 'volatile').
7992 if (VisibleTypeConversionsQuals.hasVolatile()) {
7993 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007994 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007995 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007996 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007997 /*IsAssigmentOperator=*/isEqualOp);
7998 }
7999 }
8000 }
8001
8002 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8003 for (BuiltinCandidateTypeSet::iterator
8004 Vec1 = CandidateTypes[0].vector_begin(),
8005 Vec1End = CandidateTypes[0].vector_end();
8006 Vec1 != Vec1End; ++Vec1) {
8007 for (BuiltinCandidateTypeSet::iterator
8008 Vec2 = CandidateTypes[1].vector_begin(),
8009 Vec2End = CandidateTypes[1].vector_end();
8010 Vec2 != Vec2End; ++Vec2) {
8011 QualType ParamTypes[2];
8012 ParamTypes[1] = *Vec2;
8013 // Add this built-in operator as a candidate (VQ is empty).
8014 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008015 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008016 /*IsAssigmentOperator=*/isEqualOp);
8017
8018 // Add this built-in operator as a candidate (VQ is 'volatile').
8019 if (VisibleTypeConversionsQuals.hasVolatile()) {
8020 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8021 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008023 /*IsAssigmentOperator=*/isEqualOp);
8024 }
8025 }
8026 }
8027 }
8028
8029 // C++ [over.built]p22:
8030 //
8031 // For every triple (L, VQ, R), where L is an integral type, VQ
8032 // is either volatile or empty, and R is a promoted integral
8033 // type, there exist candidate operator functions of the form
8034 //
8035 // VQ L& operator%=(VQ L&, R);
8036 // VQ L& operator<<=(VQ L&, R);
8037 // VQ L& operator>>=(VQ L&, R);
8038 // VQ L& operator&=(VQ L&, R);
8039 // VQ L& operator^=(VQ L&, R);
8040 // VQ L& operator|=(VQ L&, R);
8041 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008042 if (!HasArithmeticOrEnumeralCandidateType)
8043 return;
8044
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008045 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8046 for (unsigned Right = FirstPromotedIntegralType;
8047 Right < LastPromotedIntegralType; ++Right) {
8048 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008049 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008050
8051 // Add this built-in operator as a candidate (VQ is empty).
8052 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008053 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008054 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008055 if (VisibleTypeConversionsQuals.hasVolatile()) {
8056 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008057 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008058 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8059 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008060 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008061 }
8062 }
8063 }
8064 }
8065
8066 // C++ [over.operator]p23:
8067 //
8068 // There also exist candidate operator functions of the form
8069 //
8070 // bool operator!(bool);
8071 // bool operator&&(bool, bool);
8072 // bool operator||(bool, bool);
8073 void addExclaimOverload() {
8074 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008075 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008076 /*IsAssignmentOperator=*/false,
8077 /*NumContextualBoolArguments=*/1);
8078 }
8079 void addAmpAmpOrPipePipeOverload() {
8080 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008081 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 /*IsAssignmentOperator=*/false,
8083 /*NumContextualBoolArguments=*/2);
8084 }
8085
8086 // C++ [over.built]p13:
8087 //
8088 // For every cv-qualified or cv-unqualified object type T there
8089 // exist candidate operator functions of the form
8090 //
8091 // T* operator+(T*, ptrdiff_t); [ABOVE]
8092 // T& operator[](T*, ptrdiff_t);
8093 // T* operator-(T*, ptrdiff_t); [ABOVE]
8094 // T* operator+(ptrdiff_t, T*); [ABOVE]
8095 // T& operator[](ptrdiff_t, T*);
8096 void addSubscriptOverloads() {
8097 for (BuiltinCandidateTypeSet::iterator
8098 Ptr = CandidateTypes[0].pointer_begin(),
8099 PtrEnd = CandidateTypes[0].pointer_end();
8100 Ptr != PtrEnd; ++Ptr) {
8101 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8102 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008103 if (!PointeeType->isObjectType())
8104 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008105
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008106 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8107
8108 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008109 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008110 }
8111
8112 for (BuiltinCandidateTypeSet::iterator
8113 Ptr = CandidateTypes[1].pointer_begin(),
8114 PtrEnd = CandidateTypes[1].pointer_end();
8115 Ptr != PtrEnd; ++Ptr) {
8116 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8117 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008118 if (!PointeeType->isObjectType())
8119 continue;
8120
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008121 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8122
8123 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008124 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008125 }
8126 }
8127
8128 // C++ [over.built]p11:
8129 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8130 // C1 is the same type as C2 or is a derived class of C2, T is an object
8131 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8132 // there exist candidate operator functions of the form
8133 //
8134 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8135 //
8136 // where CV12 is the union of CV1 and CV2.
8137 void addArrowStarOverloads() {
8138 for (BuiltinCandidateTypeSet::iterator
8139 Ptr = CandidateTypes[0].pointer_begin(),
8140 PtrEnd = CandidateTypes[0].pointer_end();
8141 Ptr != PtrEnd; ++Ptr) {
8142 QualType C1Ty = (*Ptr);
8143 QualType C1;
8144 QualifierCollector Q1;
8145 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8146 if (!isa<RecordType>(C1))
8147 continue;
8148 // heuristic to reduce number of builtin candidates in the set.
8149 // Add volatile/restrict version only if there are conversions to a
8150 // volatile/restrict type.
8151 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8152 continue;
8153 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8154 continue;
8155 for (BuiltinCandidateTypeSet::iterator
8156 MemPtr = CandidateTypes[1].member_pointer_begin(),
8157 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8158 MemPtr != MemPtrEnd; ++MemPtr) {
8159 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8160 QualType C2 = QualType(mptr->getClass(), 0);
8161 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008162 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008163 break;
8164 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8165 // build CV12 T&
8166 QualType T = mptr->getPointeeType();
8167 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8168 T.isVolatileQualified())
8169 continue;
8170 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8171 T.isRestrictQualified())
8172 continue;
8173 T = Q1.apply(S.Context, T);
8174 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008175 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008176 }
8177 }
8178 }
8179
8180 // Note that we don't consider the first argument, since it has been
8181 // contextually converted to bool long ago. The candidates below are
8182 // therefore added as binary.
8183 //
8184 // C++ [over.built]p25:
8185 // For every type T, where T is a pointer, pointer-to-member, or scoped
8186 // enumeration type, there exist candidate operator functions of the form
8187 //
8188 // T operator?(bool, T, T);
8189 //
8190 void addConditionalOperatorOverloads() {
8191 /// Set of (canonical) types that we've already handled.
8192 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8193
8194 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8195 for (BuiltinCandidateTypeSet::iterator
8196 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8197 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8198 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008199 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008200 continue;
8201
8202 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008203 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008204 }
8205
8206 for (BuiltinCandidateTypeSet::iterator
8207 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8208 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8209 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008210 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 continue;
8212
8213 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008214 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008215 }
8216
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008217 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008218 for (BuiltinCandidateTypeSet::iterator
8219 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8220 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8221 Enum != EnumEnd; ++Enum) {
8222 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8223 continue;
8224
David Blaikie82e95a32014-11-19 07:49:47 +00008225 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 continue;
8227
8228 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008229 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008230 }
8231 }
8232 }
8233 }
8234};
8235
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008236} // end anonymous namespace
8237
8238/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8239/// operator overloads to the candidate set (C++ [over.built]), based
8240/// on the operator @p Op and the arguments given. For example, if the
8241/// operator is a binary '+', this routine might add "int
8242/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008243void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8244 SourceLocation OpLoc,
8245 ArrayRef<Expr *> Args,
8246 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008247 // Find all of the types that the arguments can convert to, but only
8248 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008249 // that make use of these types. Also record whether we encounter non-record
8250 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008251 Qualifiers VisibleTypeConversionsQuals;
8252 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008253 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008254 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008255
8256 bool HasNonRecordCandidateType = false;
8257 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008258 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008259 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008260 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008261 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8262 OpLoc,
8263 true,
8264 (Op == OO_Exclaim ||
8265 Op == OO_AmpAmp ||
8266 Op == OO_PipePipe),
8267 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008268 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8269 CandidateTypes[ArgIdx].hasNonRecordTypes();
8270 HasArithmeticOrEnumeralCandidateType =
8271 HasArithmeticOrEnumeralCandidateType ||
8272 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008273 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008274
Chandler Carruth00a38332010-12-13 01:44:01 +00008275 // Exit early when no non-record types have been added to the candidate set
8276 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008277 //
8278 // We can't exit early for !, ||, or &&, since there we have always have
8279 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008280 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008281 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008282 return;
8283
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008285 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008286 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008287 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008288 CandidateTypes, CandidateSet);
8289
8290 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008291 switch (Op) {
8292 case OO_None:
8293 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008294 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008295
Chandler Carruth5184de02010-12-12 08:51:33 +00008296 case OO_New:
8297 case OO_Delete:
8298 case OO_Array_New:
8299 case OO_Array_Delete:
8300 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008301 llvm_unreachable(
8302 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008303
8304 case OO_Comma:
8305 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008306 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008307 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008308 // -- For the operator ',', the unary operator '&', the
8309 // operator '->', or the operator 'co_await', the
8310 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008311 break;
8312
8313 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008314 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008315 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008316 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008317
8318 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008319 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008320 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008321 } else {
8322 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8323 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8324 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008325 break;
8326
Chandler Carruth5184de02010-12-12 08:51:33 +00008327 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008328 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008329 OpBuilder.addUnaryStarPointerOverloads();
8330 else
8331 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8332 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008333
Chandler Carruth5184de02010-12-12 08:51:33 +00008334 case OO_Slash:
8335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008336 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008337
8338 case OO_PlusPlus:
8339 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008340 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8341 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008342 break;
8343
Douglas Gregor84605ae2009-08-24 13:43:27 +00008344 case OO_EqualEqual:
8345 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008347 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008348
Douglas Gregora11693b2008-11-12 17:17:38 +00008349 case OO_Less:
8350 case OO_Greater:
8351 case OO_LessEqual:
8352 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008353 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008354 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8355 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008356
Douglas Gregora11693b2008-11-12 17:17:38 +00008357 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008358 case OO_Caret:
8359 case OO_Pipe:
8360 case OO_LessLess:
8361 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008362 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008363 break;
8364
Chandler Carruth5184de02010-12-12 08:51:33 +00008365 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008366 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008367 // C++ [over.match.oper]p3:
8368 // -- For the operator ',', the unary operator '&', or the
8369 // operator '->', the built-in candidates set is empty.
8370 break;
8371
8372 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8373 break;
8374
8375 case OO_Tilde:
8376 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8377 break;
8378
Douglas Gregora11693b2008-11-12 17:17:38 +00008379 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008380 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008381 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008382
8383 case OO_PlusEqual:
8384 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008385 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008386 // Fall through.
8387
8388 case OO_StarEqual:
8389 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008390 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008391 break;
8392
8393 case OO_PercentEqual:
8394 case OO_LessLessEqual:
8395 case OO_GreaterGreaterEqual:
8396 case OO_AmpEqual:
8397 case OO_CaretEqual:
8398 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008399 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008400 break;
8401
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008402 case OO_Exclaim:
8403 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008404 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008405
Douglas Gregora11693b2008-11-12 17:17:38 +00008406 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008407 case OO_PipePipe:
8408 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008409 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008410
8411 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008412 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008413 break;
8414
8415 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008416 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008417 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008418
8419 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008420 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008421 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8422 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008423 }
8424}
8425
Douglas Gregore254f902009-02-04 00:32:51 +00008426/// \brief Add function candidates found via argument-dependent lookup
8427/// to the set of overloading candidates.
8428///
8429/// This routine performs argument-dependent name lookup based on the
8430/// given function name (which may also be an operator name) and adds
8431/// all of the overload candidates found by ADL to the overload
8432/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008433void
Douglas Gregore254f902009-02-04 00:32:51 +00008434Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008435 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008436 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008437 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008438 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008439 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008440 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008441
John McCall91f61fc2010-01-26 06:04:06 +00008442 // FIXME: This approach for uniquing ADL results (and removing
8443 // redundant candidates from the set) relies on pointer-equality,
8444 // which means we need to key off the canonical decl. However,
8445 // always going back to the canonical decl might not get us the
8446 // right set of default arguments. What default arguments are
8447 // we supposed to consider on ADL candidates, anyway?
8448
Douglas Gregorcabea402009-09-22 15:41:20 +00008449 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008450 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008451
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008452 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008453 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8454 CandEnd = CandidateSet.end();
8455 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008456 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008457 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008458 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008459 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008460 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008461
8462 // For each of the ADL candidates we found, add it to the overload
8463 // set.
John McCall8fe68082010-01-26 07:16:45 +00008464 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008465 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008466 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008467 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008468 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008469
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008470 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8471 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008472 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008473 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008474 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008475 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008476 }
Douglas Gregore254f902009-02-04 00:32:51 +00008477}
8478
George Burgess IV2a6150d2015-10-16 01:17:38 +00008479// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8480// Cand2 for overloading. This function assumes that all of the enable_if attrs
8481// on Cand1 and Cand2 have conditions that evaluate to true.
8482//
8483// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8484// Cand1's first N enable_if attributes have precisely the same conditions as
8485// Cand2's first N enable_if attributes (where N = the number of enable_if
8486// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8487static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8488 const FunctionDecl *Cand2) {
8489
8490 // FIXME: The next several lines are just
8491 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8492 // instead of reverse order which is how they're stored in the AST.
8493 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8494 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8495
8496 // Candidate 1 is better if it has strictly more attributes and
8497 // the common sequence is identical.
8498 if (Cand1Attrs.size() <= Cand2Attrs.size())
8499 return false;
8500
8501 auto Cand1I = Cand1Attrs.begin();
8502 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8503 for (auto &Cand2A : Cand2Attrs) {
8504 Cand1ID.clear();
8505 Cand2ID.clear();
8506
8507 auto &Cand1A = *Cand1I++;
8508 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8509 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8510 if (Cand1ID != Cand2ID)
8511 return false;
8512 }
8513
8514 return true;
8515}
8516
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008517/// isBetterOverloadCandidate - Determines whether the first overload
8518/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008519bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8520 const OverloadCandidate &Cand2,
8521 SourceLocation Loc,
8522 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008523 // Define viable functions to be better candidates than non-viable
8524 // functions.
8525 if (!Cand2.Viable)
8526 return Cand1.Viable;
8527 else if (!Cand1.Viable)
8528 return false;
8529
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008530 // C++ [over.match.best]p1:
8531 //
8532 // -- if F is a static member function, ICS1(F) is defined such
8533 // that ICS1(F) is neither better nor worse than ICS1(G) for
8534 // any function G, and, symmetrically, ICS1(G) is neither
8535 // better nor worse than ICS1(F).
8536 unsigned StartArg = 0;
8537 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8538 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008539
Douglas Gregord3cb3562009-07-07 23:38:56 +00008540 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008541 // A viable function F1 is defined to be a better function than another
8542 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008543 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008544 unsigned NumArgs = Cand1.NumConversions;
8545 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008546 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008547 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008548 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008549 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008550 Cand2.Conversions[ArgIdx])) {
8551 case ImplicitConversionSequence::Better:
8552 // Cand1 has a better conversion sequence.
8553 HasBetterConversion = true;
8554 break;
8555
8556 case ImplicitConversionSequence::Worse:
8557 // Cand1 can't be better than Cand2.
8558 return false;
8559
8560 case ImplicitConversionSequence::Indistinguishable:
8561 // Do nothing.
8562 break;
8563 }
8564 }
8565
Mike Stump11289f42009-09-09 15:08:12 +00008566 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008567 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008568 if (HasBetterConversion)
8569 return true;
8570
Douglas Gregora1f013e2008-11-07 22:36:19 +00008571 // -- the context is an initialization by user-defined conversion
8572 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8573 // from the return type of F1 to the destination type (i.e.,
8574 // the type of the entity being initialized) is a better
8575 // conversion sequence than the standard conversion sequence
8576 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008577 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008578 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008579 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008580 // First check whether we prefer one of the conversion functions over the
8581 // other. This only distinguishes the results in non-standard, extension
8582 // cases such as the conversion from a lambda closure type to a function
8583 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008584 ImplicitConversionSequence::CompareKind Result =
8585 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8586 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008587 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008588 Cand1.FinalConversion,
8589 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008590
Richard Smithec2748a2014-05-17 04:36:39 +00008591 if (Result != ImplicitConversionSequence::Indistinguishable)
8592 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008593
8594 // FIXME: Compare kind of reference binding if conversion functions
8595 // convert to a reference type used in direct reference binding, per
8596 // C++14 [over.match.best]p1 section 2 bullet 3.
8597 }
8598
8599 // -- F1 is a non-template function and F2 is a function template
8600 // specialization, or, if not that,
8601 bool Cand1IsSpecialization = Cand1.Function &&
8602 Cand1.Function->getPrimaryTemplate();
8603 bool Cand2IsSpecialization = Cand2.Function &&
8604 Cand2.Function->getPrimaryTemplate();
8605 if (Cand1IsSpecialization != Cand2IsSpecialization)
8606 return Cand2IsSpecialization;
8607
8608 // -- F1 and F2 are function template specializations, and the function
8609 // template for F1 is more specialized than the template for F2
8610 // according to the partial ordering rules described in 14.5.5.2, or,
8611 // if not that,
8612 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8613 if (FunctionTemplateDecl *BetterTemplate
8614 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8615 Cand2.Function->getPrimaryTemplate(),
8616 Loc,
8617 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8618 : TPOC_Call,
8619 Cand1.ExplicitCallArguments,
8620 Cand2.ExplicitCallArguments))
8621 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008622 }
8623
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008624 // Check for enable_if value-based overload resolution.
8625 if (Cand1.Function && Cand2.Function &&
8626 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008627 Cand2.Function->hasAttr<EnableIfAttr>()))
8628 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008629
Artem Belevich94a55e82015-09-22 17:22:59 +00008630 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8631 Cand1.Function && Cand2.Function) {
8632 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8633 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8634 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8635 }
8636
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008637 bool HasPS1 = Cand1.Function != nullptr &&
8638 functionHasPassObjectSizeParams(Cand1.Function);
8639 bool HasPS2 = Cand2.Function != nullptr &&
8640 functionHasPassObjectSizeParams(Cand2.Function);
8641 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008642}
8643
Richard Smith2dbe4042015-11-04 19:26:32 +00008644/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008645/// name lookup and overload resolution. This applies when the same internal/no
8646/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008647/// the same header). In such a case, we don't consider the declarations to
8648/// declare the same entity, but we also don't want lookups with both
8649/// declarations visible to be ambiguous in some cases (this happens when using
8650/// a modularized libstdc++).
8651bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8652 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008653 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8654 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8655 if (!VA || !VB)
8656 return false;
8657
8658 // The declarations must be declaring the same name as an internal linkage
8659 // entity in different modules.
8660 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8661 VB->getDeclContext()->getRedeclContext()) ||
8662 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8663 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8664 VA->isExternallyVisible() || VB->isExternallyVisible())
8665 return false;
8666
8667 // Check that the declarations appear to be equivalent.
8668 //
8669 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8670 // For constants and functions, we should check the initializer or body is
8671 // the same. For non-constant variables, we shouldn't allow it at all.
8672 if (Context.hasSameType(VA->getType(), VB->getType()))
8673 return true;
8674
8675 // Enum constants within unnamed enumerations will have different types, but
8676 // may still be similar enough to be interchangeable for our purposes.
8677 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8678 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8679 // Only handle anonymous enums. If the enumerations were named and
8680 // equivalent, they would have been merged to the same type.
8681 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8682 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8683 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8684 !Context.hasSameType(EnumA->getIntegerType(),
8685 EnumB->getIntegerType()))
8686 return false;
8687 // Allow this only if the value is the same for both enumerators.
8688 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8689 }
8690 }
8691
8692 // Nothing else is sufficiently similar.
8693 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008694}
8695
8696void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8697 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8698 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8699
8700 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8701 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8702 << !M << (M ? M->getFullModuleName() : "");
8703
8704 for (auto *E : Equiv) {
8705 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8706 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8707 << !M << (M ? M->getFullModuleName() : "");
8708 }
Richard Smith896c66e2015-10-21 07:13:52 +00008709}
8710
Mike Stump11289f42009-09-09 15:08:12 +00008711/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008712/// within an overload candidate set.
8713///
James Dennettffad8b72012-06-22 08:10:18 +00008714/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008715/// which overload resolution occurs.
8716///
James Dennettffad8b72012-06-22 08:10:18 +00008717/// \param Best If overload resolution was successful or found a deleted
8718/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008719///
8720/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008721OverloadingResult
8722OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008723 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008724 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008725 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8726 std::transform(begin(), end(), std::back_inserter(Candidates),
8727 [](OverloadCandidate &Cand) { return &Cand; });
8728
8729 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8730 // but accepted by both clang and NVCC. However during a particular
8731 // compilation mode only one call variant is viable. We need to
8732 // exclude non-viable overload candidates from consideration based
8733 // only on their host/device attributes. Specifically, if one
8734 // candidate call is WrongSide and the other is SameSide, we ignore
8735 // the WrongSide candidate.
8736 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads) {
8737 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8738 bool ContainsSameSideCandidate =
8739 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8740 return Cand->Function &&
8741 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8742 Sema::CFP_SameSide;
8743 });
8744 if (ContainsSameSideCandidate) {
8745 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8746 return Cand->Function &&
8747 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8748 Sema::CFP_WrongSide;
8749 };
8750 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8751 IsWrongSideCandidate),
8752 Candidates.end());
8753 }
8754 }
8755
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008756 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008757 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008758 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008759 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008760 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008761 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008762 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008763
8764 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008765 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008766 return OR_No_Viable_Function;
8767
Richard Smith2dbe4042015-11-04 19:26:32 +00008768 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008769
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008770 // Make sure that this function is better than every other viable
8771 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008772 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008773 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008774 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008775 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008776 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008777 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8778 Cand->Function)) {
8779 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008780 continue;
8781 }
8782
John McCall5c32be02010-08-24 20:38:10 +00008783 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008784 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008785 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008786 }
Mike Stump11289f42009-09-09 15:08:12 +00008787
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008788 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008789 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008790 (Best->Function->isDeleted() ||
8791 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008792 return OR_Deleted;
8793
Richard Smith2dbe4042015-11-04 19:26:32 +00008794 if (!EquivalentCands.empty())
8795 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8796 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008797
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008798 return OR_Success;
8799}
8800
John McCall53262c92010-01-12 02:15:36 +00008801namespace {
8802
8803enum OverloadCandidateKind {
8804 oc_function,
8805 oc_method,
8806 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008807 oc_function_template,
8808 oc_method_template,
8809 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008810 oc_implicit_default_constructor,
8811 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008812 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008813 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008814 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008815 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008816};
8817
John McCalle1ac8d12010-01-13 00:25:19 +00008818OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8819 FunctionDecl *Fn,
8820 std::string &Description) {
8821 bool isTemplate = false;
8822
8823 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8824 isTemplate = true;
8825 Description = S.getTemplateArgumentBindingsText(
8826 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8827 }
John McCallfd0b2f82010-01-06 09:43:14 +00008828
8829 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008830 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008831 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008832
Sebastian Redl08905022011-02-05 19:23:19 +00008833 if (Ctor->getInheritedConstructor())
8834 return oc_implicit_inherited_constructor;
8835
Alexis Hunt119c10e2011-05-25 23:16:36 +00008836 if (Ctor->isDefaultConstructor())
8837 return oc_implicit_default_constructor;
8838
8839 if (Ctor->isMoveConstructor())
8840 return oc_implicit_move_constructor;
8841
8842 assert(Ctor->isCopyConstructor() &&
8843 "unexpected sort of implicit constructor");
8844 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008845 }
8846
8847 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8848 // This actually gets spelled 'candidate function' for now, but
8849 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008850 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008851 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008852
Alexis Hunt119c10e2011-05-25 23:16:36 +00008853 if (Meth->isMoveAssignmentOperator())
8854 return oc_implicit_move_assignment;
8855
Douglas Gregor12695102012-02-10 08:36:38 +00008856 if (Meth->isCopyAssignmentOperator())
8857 return oc_implicit_copy_assignment;
8858
8859 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8860 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008861 }
8862
John McCalle1ac8d12010-01-13 00:25:19 +00008863 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008864}
8865
Larisse Voufo98b20f12013-07-19 23:00:19 +00008866void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008867 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8868 if (!Ctor) return;
8869
8870 Ctor = Ctor->getInheritedConstructor();
8871 if (!Ctor) return;
8872
8873 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8874}
8875
John McCall53262c92010-01-12 02:15:36 +00008876} // end anonymous namespace
8877
George Burgess IV5f21c712015-10-12 19:57:04 +00008878static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8879 const FunctionDecl *FD) {
8880 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8881 bool AlwaysTrue;
8882 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8883 return false;
8884 if (!AlwaysTrue)
8885 return false;
8886 }
8887 return true;
8888}
8889
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008890/// \brief Returns true if we can take the address of the function.
8891///
8892/// \param Complain - If true, we'll emit a diagnostic
8893/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8894/// we in overload resolution?
8895/// \param Loc - The location of the statement we're complaining about. Ignored
8896/// if we're not complaining, or if we're in overload resolution.
8897static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8898 bool Complain,
8899 bool InOverloadResolution,
8900 SourceLocation Loc) {
8901 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8902 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008903 if (InOverloadResolution)
8904 S.Diag(FD->getLocStart(),
8905 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8906 else
8907 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8908 }
8909 return false;
8910 }
8911
8912 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8913 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8914 if (I == FD->param_end())
8915 return true;
8916
8917 if (Complain) {
8918 // Add one to ParamNo because it's user-facing
8919 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8920 if (InOverloadResolution)
8921 S.Diag(FD->getLocation(),
8922 diag::note_ovl_candidate_has_pass_object_size_params)
8923 << ParamNo;
8924 else
8925 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8926 << FD << ParamNo;
8927 }
8928 return false;
8929}
8930
8931static bool checkAddressOfCandidateIsAvailable(Sema &S,
8932 const FunctionDecl *FD) {
8933 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8934 /*InOverloadResolution=*/true,
8935 /*Loc=*/SourceLocation());
8936}
8937
8938bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8939 bool Complain,
8940 SourceLocation Loc) {
8941 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8942 /*InOverloadResolution=*/false,
8943 Loc);
8944}
8945
John McCall53262c92010-01-12 02:15:36 +00008946// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008947void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8948 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008949 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8950 return;
8951
John McCalle1ac8d12010-01-13 00:25:19 +00008952 std::string FnDesc;
8953 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008954 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8955 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008956
8957 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008958 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008959 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008960}
8961
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008962// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008963// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008964void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8965 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008966 assert(OverloadedExpr->getType() == Context.OverloadTy);
8967
8968 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8969 OverloadExpr *OvlExpr = Ovl.Expression;
8970
8971 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8972 IEnd = OvlExpr->decls_end();
8973 I != IEnd; ++I) {
8974 if (FunctionTemplateDecl *FunTmpl =
8975 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008976 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8977 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008978 } else if (FunctionDecl *Fun
8979 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008980 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008981 }
8982 }
8983}
8984
John McCall0d1da222010-01-12 00:44:57 +00008985/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8986/// "lead" diagnostic; it will be given two arguments, the source and
8987/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008988void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8989 Sema &S,
8990 SourceLocation CaretLoc,
8991 const PartialDiagnostic &PDiag) const {
8992 S.Diag(CaretLoc, PDiag)
8993 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008994 // FIXME: The note limiting machinery is borrowed from
8995 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8996 // refactoring here.
8997 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8998 unsigned CandsShown = 0;
8999 AmbiguousConversionSequence::const_iterator I, E;
9000 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9001 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9002 break;
9003 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00009004 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00009005 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009006 if (I != E)
9007 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009008}
9009
Richard Smith17c00b42014-11-12 01:24:00 +00009010static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009011 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009012 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9013 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009014 assert(Cand->Function && "for now, candidate must be a function");
9015 FunctionDecl *Fn = Cand->Function;
9016
9017 // There's a conversion slot for the object argument if this is a
9018 // non-constructor method. Note that 'I' corresponds the
9019 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009020 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009021 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009022 if (I == 0)
9023 isObjectArgument = true;
9024 else
9025 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009026 }
9027
John McCalle1ac8d12010-01-13 00:25:19 +00009028 std::string FnDesc;
9029 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9030
John McCall6a61b522010-01-13 09:16:55 +00009031 Expr *FromExpr = Conv.Bad.FromExpr;
9032 QualType FromTy = Conv.Bad.getFromType();
9033 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009034
John McCallfb7ad0f2010-02-02 02:42:52 +00009035 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009036 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009037 Expr *E = FromExpr->IgnoreParens();
9038 if (isa<UnaryOperator>(E))
9039 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009040 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009041
9042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9043 << (unsigned) FnKind << FnDesc
9044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9045 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009046 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00009047 return;
9048 }
9049
John McCall6d174642010-01-23 08:10:49 +00009050 // Do some hand-waving analysis to see if the non-viability is due
9051 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009052 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9053 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9054 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9055 CToTy = RT->getPointeeType();
9056 else {
9057 // TODO: detect and diagnose the full richness of const mismatches.
9058 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009059 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9060 CFromTy = FromPT->getPointeeType();
9061 CToTy = ToPT->getPointeeType();
9062 }
John McCall47000992010-01-14 03:28:57 +00009063 }
9064
9065 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9066 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009067 Qualifiers FromQs = CFromTy.getQualifiers();
9068 Qualifiers ToQs = CToTy.getQualifiers();
9069
9070 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9072 << (unsigned) FnKind << FnDesc
9073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9074 << FromTy
9075 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9076 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009077 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009078 return;
9079 }
9080
John McCall31168b02011-06-15 23:02:42 +00009081 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009083 << (unsigned) FnKind << FnDesc
9084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9085 << FromTy
9086 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9087 << (unsigned) isObjectArgument << I+1;
9088 MaybeEmitInheritedConstructorNote(S, Fn);
9089 return;
9090 }
9091
Douglas Gregoraec25842011-04-26 23:16:46 +00009092 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9094 << (unsigned) FnKind << FnDesc
9095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9096 << FromTy
9097 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9098 << (unsigned) isObjectArgument << I+1;
9099 MaybeEmitInheritedConstructorNote(S, Fn);
9100 return;
9101 }
9102
John McCall47000992010-01-14 03:28:57 +00009103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9104 assert(CVR && "unexpected qualifiers mismatch");
9105
9106 if (isObjectArgument) {
9107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9108 << (unsigned) FnKind << FnDesc
9109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9110 << FromTy << (CVR - 1);
9111 } else {
9112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9113 << (unsigned) FnKind << FnDesc
9114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9115 << FromTy << (CVR - 1) << I+1;
9116 }
Sebastian Redl08905022011-02-05 19:23:19 +00009117 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009118 return;
9119 }
9120
Sebastian Redla72462c2011-09-24 17:48:32 +00009121 // Special diagnostic for failure to convert an initializer list, since
9122 // telling the user that it has type void is not useful.
9123 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9125 << (unsigned) FnKind << FnDesc
9126 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9127 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9128 MaybeEmitInheritedConstructorNote(S, Fn);
9129 return;
9130 }
9131
John McCall6d174642010-01-23 08:10:49 +00009132 // Diagnose references or pointers to incomplete types differently,
9133 // since it's far from impossible that the incompleteness triggered
9134 // the failure.
9135 QualType TempFromTy = FromTy.getNonReferenceType();
9136 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9137 TempFromTy = PTy->getPointeeType();
9138 if (TempFromTy->isIncompleteType()) {
9139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9140 << (unsigned) FnKind << FnDesc
9141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9142 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009143 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009144 return;
9145 }
9146
Douglas Gregor56f2e342010-06-30 23:01:39 +00009147 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009148 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009149 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9150 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9151 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9152 FromPtrTy->getPointeeType()) &&
9153 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9154 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009155 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009156 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009157 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009158 }
9159 } else if (const ObjCObjectPointerType *FromPtrTy
9160 = FromTy->getAs<ObjCObjectPointerType>()) {
9161 if (const ObjCObjectPointerType *ToPtrTy
9162 = ToTy->getAs<ObjCObjectPointerType>())
9163 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9164 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9165 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9166 FromPtrTy->getPointeeType()) &&
9167 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009168 BaseToDerivedConversion = 2;
9169 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009170 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9171 !FromTy->isIncompleteType() &&
9172 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009173 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009174 BaseToDerivedConversion = 3;
9175 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9176 ToTy.getNonReferenceType().getCanonicalType() ==
9177 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9179 << (unsigned) FnKind << FnDesc
9180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9181 << (unsigned) isObjectArgument << I + 1;
9182 MaybeEmitInheritedConstructorNote(S, Fn);
9183 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009184 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009186
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009187 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009188 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009189 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009190 << (unsigned) FnKind << FnDesc
9191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009192 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009193 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009194 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009195 return;
9196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009197
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009198 if (isa<ObjCObjectPointerType>(CFromTy) &&
9199 isa<PointerType>(CToTy)) {
9200 Qualifiers FromQs = CFromTy.getQualifiers();
9201 Qualifiers ToQs = CToTy.getQualifiers();
9202 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9204 << (unsigned) FnKind << FnDesc
9205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9206 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9207 MaybeEmitInheritedConstructorNote(S, Fn);
9208 return;
9209 }
9210 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009211
9212 if (TakingCandidateAddress &&
9213 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9214 return;
9215
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009216 // Emit the generic diagnostic and, optionally, add the hints to it.
9217 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9218 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009219 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009220 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9221 << (unsigned) (Cand->Fix.Kind);
9222
9223 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009224 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9225 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009226 FDiag << *HI;
9227 S.Diag(Fn->getLocation(), FDiag);
9228
Sebastian Redl08905022011-02-05 19:23:19 +00009229 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009230}
9231
Larisse Voufo98b20f12013-07-19 23:00:19 +00009232/// Additional arity mismatch diagnosis specific to a function overload
9233/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9234/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009235static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9236 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009237 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009238 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009239
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009240 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009241 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009242 // right number of arguments, because only overloaded operators have
9243 // the weird behavior of overloading member and non-member functions.
9244 // Just don't report anything.
9245 if (Fn->isInvalidDecl() &&
9246 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009247 return true;
9248
9249 if (NumArgs < MinParams) {
9250 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9251 (Cand->FailureKind == ovl_fail_bad_deduction &&
9252 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9253 } else {
9254 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9255 (Cand->FailureKind == ovl_fail_bad_deduction &&
9256 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9257 }
9258
9259 return false;
9260}
9261
9262/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009263static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009264 assert(isa<FunctionDecl>(D) &&
9265 "The templated declaration should at least be a function"
9266 " when diagnosing bad template argument deduction due to too many"
9267 " or too few arguments");
9268
9269 FunctionDecl *Fn = cast<FunctionDecl>(D);
9270
9271 // TODO: treat calls to a missing default constructor as a special case
9272 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9273 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009274
John McCall6a61b522010-01-13 09:16:55 +00009275 // at least / at most / exactly
9276 unsigned mode, modeCount;
9277 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009278 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9279 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009280 mode = 0; // "at least"
9281 else
9282 mode = 2; // "exactly"
9283 modeCount = MinParams;
9284 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009285 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009286 mode = 1; // "at most"
9287 else
9288 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009289 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009290 }
9291
9292 std::string Description;
9293 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9294
Richard Smith10ff50d2012-05-11 05:16:41 +00009295 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009297 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9298 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009299 else
9300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009301 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9302 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009303 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009304}
9305
Larisse Voufo98b20f12013-07-19 23:00:19 +00009306/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009307static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9308 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009309 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9310 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9311}
Larisse Voufo47c08452013-07-19 22:53:23 +00009312
Richard Smith17c00b42014-11-12 01:24:00 +00009313static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9315 return FD->getDescribedFunctionTemplate();
9316 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9317 return RD->getDescribedClassTemplate();
9318
9319 llvm_unreachable("Unsupported: Getting the described template declaration"
9320 " for bad deduction diagnosis");
9321}
9322
9323/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009324static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9325 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009326 unsigned NumArgs,
9327 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009328 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009329 NamedDecl *ParamD;
9330 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9331 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9332 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009333 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009334 case Sema::TDK_Success:
9335 llvm_unreachable("TDK_success while diagnosing bad deduction");
9336
9337 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009338 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009339 S.Diag(Templated->getLocation(),
9340 diag::note_ovl_candidate_incomplete_deduction)
9341 << ParamD->getDeclName();
9342 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009343 return;
9344 }
9345
John McCall42d7d192010-08-05 09:05:08 +00009346 case Sema::TDK_Underqualified: {
9347 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9348 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9349
Larisse Voufo98b20f12013-07-19 23:00:19 +00009350 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009351
9352 // Param will have been canonicalized, but it should just be a
9353 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009354 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009355 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009356 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009357 assert(S.Context.hasSameType(Param, NonCanonParam));
9358
9359 // Arg has also been canonicalized, but there's nothing we can do
9360 // about that. It also doesn't matter as much, because it won't
9361 // have any template parameters in it (because deduction isn't
9362 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009363 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009364
Larisse Voufo98b20f12013-07-19 23:00:19 +00009365 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9366 << ParamD->getDeclName() << Arg << NonCanonParam;
9367 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009368 return;
9369 }
9370
9371 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009372 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009373 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009374 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009375 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009376 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009377 which = 1;
9378 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009379 which = 2;
9380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009381
Larisse Voufo98b20f12013-07-19 23:00:19 +00009382 S.Diag(Templated->getLocation(),
9383 diag::note_ovl_candidate_inconsistent_deduction)
9384 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9385 << *DeductionFailure.getSecondArg();
9386 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009387 return;
9388 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009389
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009390 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009391 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009392 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009393 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009394 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009395 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009396 else {
9397 int index = 0;
9398 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9399 index = TTP->getIndex();
9400 else if (NonTypeTemplateParmDecl *NTTP
9401 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9402 index = NTTP->getIndex();
9403 else
9404 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009405 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009406 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009407 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009408 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009409 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009410 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009411
Douglas Gregor02eb4832010-05-08 18:13:28 +00009412 case Sema::TDK_TooManyArguments:
9413 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009414 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009415 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009416
9417 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009418 S.Diag(Templated->getLocation(),
9419 diag::note_ovl_candidate_instantiation_depth);
9420 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009421 return;
9422
9423 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009424 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009425 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009426 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009427 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009428 TemplateArgString = " ";
9429 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009430 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009431 }
9432
Richard Smith6f8d2c62012-05-09 05:17:00 +00009433 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009434 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009435 if (PDiag && PDiag->second.getDiagID() ==
9436 diag::err_typename_nested_not_found_enable_if) {
9437 // FIXME: Use the source range of the condition, and the fully-qualified
9438 // name of the enable_if template. These are both present in PDiag.
9439 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9440 << "'enable_if'" << TemplateArgString;
9441 return;
9442 }
9443
Richard Smith9ca64612012-05-07 09:03:25 +00009444 // Format the SFINAE diagnostic into the argument string.
9445 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9446 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009447 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009448 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009449 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009450 SFINAEArgString = ": ";
9451 R = SourceRange(PDiag->first, PDiag->first);
9452 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9453 }
9454
Larisse Voufo98b20f12013-07-19 23:00:19 +00009455 S.Diag(Templated->getLocation(),
9456 diag::note_ovl_candidate_substitution_failure)
9457 << TemplateArgString << SFINAEArgString << R;
9458 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009459 return;
9460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009461
Richard Smith8c6eeb92013-01-31 04:03:12 +00009462 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009463 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9464 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009465 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009466 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009467 return;
9468 }
9469
Richard Smith9b534542015-12-31 02:02:54 +00009470 case Sema::TDK_DeducedMismatch: {
9471 // Format the template argument list into the argument string.
9472 SmallString<128> TemplateArgString;
9473 if (TemplateArgumentList *Args =
9474 DeductionFailure.getTemplateArgumentList()) {
9475 TemplateArgString = " ";
9476 TemplateArgString += S.getTemplateArgumentBindingsText(
9477 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9478 }
9479
9480 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9481 << (*DeductionFailure.getCallArgIndex() + 1)
9482 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9483 << TemplateArgString;
9484 break;
9485 }
9486
Richard Trieue3732352013-04-08 21:11:40 +00009487 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009488 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009489 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9490 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009491 if (FirstTA.getKind() == TemplateArgument::Template &&
9492 SecondTA.getKind() == TemplateArgument::Template) {
9493 TemplateName FirstTN = FirstTA.getAsTemplate();
9494 TemplateName SecondTN = SecondTA.getAsTemplate();
9495 if (FirstTN.getKind() == TemplateName::Template &&
9496 SecondTN.getKind() == TemplateName::Template) {
9497 if (FirstTN.getAsTemplateDecl()->getName() ==
9498 SecondTN.getAsTemplateDecl()->getName()) {
9499 // FIXME: This fixes a bad diagnostic where both templates are named
9500 // the same. This particular case is a bit difficult since:
9501 // 1) It is passed as a string to the diagnostic printer.
9502 // 2) The diagnostic printer only attempts to find a better
9503 // name for types, not decls.
9504 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009505 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009506 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9507 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9508 return;
9509 }
9510 }
9511 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009512
9513 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9514 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9515 return;
9516
Faisal Vali2b391ab2013-09-26 19:54:12 +00009517 // FIXME: For generic lambda parameters, check if the function is a lambda
9518 // call operator, and if so, emit a prettier and more informative
9519 // diagnostic that mentions 'auto' and lambda in addition to
9520 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009521 S.Diag(Templated->getLocation(),
9522 diag::note_ovl_candidate_non_deduced_mismatch)
9523 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009524 return;
Richard Trieue3732352013-04-08 21:11:40 +00009525 }
John McCall8b9ed552010-02-01 18:53:26 +00009526 // TODO: diagnose these individually, then kill off
9527 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009528 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009529 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9530 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009531 return;
9532 }
9533}
9534
Larisse Voufo98b20f12013-07-19 23:00:19 +00009535/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009536static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009537 unsigned NumArgs,
9538 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009539 unsigned TDK = Cand->DeductionFailure.Result;
9540 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9541 if (CheckArityMismatch(S, Cand, NumArgs))
9542 return;
9543 }
9544 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009545 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009546}
9547
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009548/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009549static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009550 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9551 FunctionDecl *Callee = Cand->Function;
9552
9553 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9554 CalleeTarget = S.IdentifyCUDATarget(Callee);
9555
9556 std::string FnDesc;
9557 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9558
9559 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009560 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9561
9562 // This could be an implicit constructor for which we could not infer the
9563 // target due to a collsion. Diagnose that case.
9564 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9565 if (Meth != nullptr && Meth->isImplicit()) {
9566 CXXRecordDecl *ParentClass = Meth->getParent();
9567 Sema::CXXSpecialMember CSM;
9568
9569 switch (FnKind) {
9570 default:
9571 return;
9572 case oc_implicit_default_constructor:
9573 CSM = Sema::CXXDefaultConstructor;
9574 break;
9575 case oc_implicit_copy_constructor:
9576 CSM = Sema::CXXCopyConstructor;
9577 break;
9578 case oc_implicit_move_constructor:
9579 CSM = Sema::CXXMoveConstructor;
9580 break;
9581 case oc_implicit_copy_assignment:
9582 CSM = Sema::CXXCopyAssignment;
9583 break;
9584 case oc_implicit_move_assignment:
9585 CSM = Sema::CXXMoveAssignment;
9586 break;
9587 };
9588
9589 bool ConstRHS = false;
9590 if (Meth->getNumParams()) {
9591 if (const ReferenceType *RT =
9592 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9593 ConstRHS = RT->getPointeeType().isConstQualified();
9594 }
9595 }
9596
9597 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9598 /* ConstRHS */ ConstRHS,
9599 /* Diagnose */ true);
9600 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009601}
9602
Richard Smith17c00b42014-11-12 01:24:00 +00009603static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009604 FunctionDecl *Callee = Cand->Function;
9605 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9606
9607 S.Diag(Callee->getLocation(),
9608 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9609 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9610}
9611
John McCall8b9ed552010-02-01 18:53:26 +00009612/// Generates a 'note' diagnostic for an overload candidate. We've
9613/// already generated a primary error at the call site.
9614///
9615/// It really does need to be a single diagnostic with its caret
9616/// pointed at the candidate declaration. Yes, this creates some
9617/// major challenges of technical writing. Yes, this makes pointing
9618/// out problems with specific arguments quite awkward. It's still
9619/// better than generating twenty screens of text for every failed
9620/// overload.
9621///
9622/// It would be great to be able to express per-candidate problems
9623/// more richly for those diagnostic clients that cared, but we'd
9624/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009625static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009626 unsigned NumArgs,
9627 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009628 FunctionDecl *Fn = Cand->Function;
9629
John McCall12f97bc2010-01-08 04:41:39 +00009630 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009631 if (Cand->Viable && (Fn->isDeleted() ||
9632 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009633 std::string FnDesc;
9634 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009635
9636 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009637 << FnKind << FnDesc
9638 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009639 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009640 return;
John McCall12f97bc2010-01-08 04:41:39 +00009641 }
9642
John McCalle1ac8d12010-01-13 00:25:19 +00009643 // We don't really have anything else to say about viable candidates.
9644 if (Cand->Viable) {
9645 S.NoteOverloadCandidate(Fn);
9646 return;
9647 }
John McCall0d1da222010-01-12 00:44:57 +00009648
John McCall6a61b522010-01-13 09:16:55 +00009649 switch (Cand->FailureKind) {
9650 case ovl_fail_too_many_arguments:
9651 case ovl_fail_too_few_arguments:
9652 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009653
John McCall6a61b522010-01-13 09:16:55 +00009654 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009655 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009656
John McCall578a1f82014-12-14 01:46:53 +00009657 case ovl_fail_illegal_constructor: {
9658 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9659 << (Fn->getPrimaryTemplate() ? 1 : 0);
9660 MaybeEmitInheritedConstructorNote(S, Fn);
9661 return;
9662 }
9663
John McCallfe796dd2010-01-23 05:17:32 +00009664 case ovl_fail_trivial_conversion:
9665 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009666 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009667 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009668
John McCall65eb8792010-02-25 01:37:24 +00009669 case ovl_fail_bad_conversion: {
9670 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009671 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009672 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009673 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009674
John McCall6a61b522010-01-13 09:16:55 +00009675 // FIXME: this currently happens when we're called from SemaInit
9676 // when user-conversion overload fails. Figure out how to handle
9677 // those conditions and diagnose them well.
9678 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009679 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009680
9681 case ovl_fail_bad_target:
9682 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009683
9684 case ovl_fail_enable_if:
9685 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009686
9687 case ovl_fail_addr_not_available: {
9688 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9689 (void)Available;
9690 assert(!Available);
9691 break;
9692 }
John McCall65eb8792010-02-25 01:37:24 +00009693 }
John McCalld3224162010-01-08 00:58:21 +00009694}
9695
Richard Smith17c00b42014-11-12 01:24:00 +00009696static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009697 // Desugar the type of the surrogate down to a function type,
9698 // retaining as many typedefs as possible while still showing
9699 // the function type (and, therefore, its parameter types).
9700 QualType FnType = Cand->Surrogate->getConversionType();
9701 bool isLValueReference = false;
9702 bool isRValueReference = false;
9703 bool isPointer = false;
9704 if (const LValueReferenceType *FnTypeRef =
9705 FnType->getAs<LValueReferenceType>()) {
9706 FnType = FnTypeRef->getPointeeType();
9707 isLValueReference = true;
9708 } else if (const RValueReferenceType *FnTypeRef =
9709 FnType->getAs<RValueReferenceType>()) {
9710 FnType = FnTypeRef->getPointeeType();
9711 isRValueReference = true;
9712 }
9713 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9714 FnType = FnTypePtr->getPointeeType();
9715 isPointer = true;
9716 }
9717 // Desugar down to a function type.
9718 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9719 // Reconstruct the pointer/reference as appropriate.
9720 if (isPointer) FnType = S.Context.getPointerType(FnType);
9721 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9722 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9723
9724 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9725 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009726 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009727}
9728
Richard Smith17c00b42014-11-12 01:24:00 +00009729static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9730 SourceLocation OpLoc,
9731 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009732 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009733 std::string TypeStr("operator");
9734 TypeStr += Opc;
9735 TypeStr += "(";
9736 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009737 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009738 TypeStr += ")";
9739 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9740 } else {
9741 TypeStr += ", ";
9742 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9743 TypeStr += ")";
9744 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9745 }
9746}
9747
Richard Smith17c00b42014-11-12 01:24:00 +00009748static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9749 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009750 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009751 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9752 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009753 if (ICS.isBad()) break; // all meaningless after first invalid
9754 if (!ICS.isAmbiguous()) continue;
9755
John McCall5c32be02010-08-24 20:38:10 +00009756 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009757 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009758 }
9759}
9760
Larisse Voufo98b20f12013-07-19 23:00:19 +00009761static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009762 if (Cand->Function)
9763 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009764 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009765 return Cand->Surrogate->getLocation();
9766 return SourceLocation();
9767}
9768
Larisse Voufo98b20f12013-07-19 23:00:19 +00009769static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009770 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009771 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009772 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009773
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009774 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009775 case Sema::TDK_Incomplete:
9776 return 1;
9777
9778 case Sema::TDK_Underqualified:
9779 case Sema::TDK_Inconsistent:
9780 return 2;
9781
9782 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009783 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009784 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009785 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009786 return 3;
9787
9788 case Sema::TDK_InstantiationDepth:
9789 case Sema::TDK_FailedOverloadResolution:
9790 return 4;
9791
9792 case Sema::TDK_InvalidExplicitArguments:
9793 return 5;
9794
9795 case Sema::TDK_TooManyArguments:
9796 case Sema::TDK_TooFewArguments:
9797 return 6;
9798 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009799 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009800}
9801
Richard Smith17c00b42014-11-12 01:24:00 +00009802namespace {
John McCallad2587a2010-01-12 00:48:53 +00009803struct CompareOverloadCandidatesForDisplay {
9804 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009805 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009806 size_t NumArgs;
9807
Richard Smith0f59cb32015-12-18 21:45:41 +00009808 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009809 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009810
9811 bool operator()(const OverloadCandidate *L,
9812 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009813 // Fast-path this check.
9814 if (L == R) return false;
9815
John McCall12f97bc2010-01-08 04:41:39 +00009816 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009817 if (L->Viable) {
9818 if (!R->Viable) return true;
9819
9820 // TODO: introduce a tri-valued comparison for overload
9821 // candidates. Would be more worthwhile if we had a sort
9822 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009823 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9824 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009825 } else if (R->Viable)
9826 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009827
John McCall3712d9e2010-01-15 23:32:50 +00009828 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009829
John McCall3712d9e2010-01-15 23:32:50 +00009830 // Criteria by which we can sort non-viable candidates:
9831 if (!L->Viable) {
9832 // 1. Arity mismatches come after other candidates.
9833 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009834 L->FailureKind == ovl_fail_too_few_arguments) {
9835 if (R->FailureKind == ovl_fail_too_many_arguments ||
9836 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009837 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9838 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9839 if (LDist == RDist) {
9840 if (L->FailureKind == R->FailureKind)
9841 // Sort non-surrogates before surrogates.
9842 return !L->IsSurrogate && R->IsSurrogate;
9843 // Sort candidates requiring fewer parameters than there were
9844 // arguments given after candidates requiring more parameters
9845 // than there were arguments given.
9846 return L->FailureKind == ovl_fail_too_many_arguments;
9847 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009848 return LDist < RDist;
9849 }
John McCall3712d9e2010-01-15 23:32:50 +00009850 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009851 }
John McCall3712d9e2010-01-15 23:32:50 +00009852 if (R->FailureKind == ovl_fail_too_many_arguments ||
9853 R->FailureKind == ovl_fail_too_few_arguments)
9854 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009855
John McCallfe796dd2010-01-23 05:17:32 +00009856 // 2. Bad conversions come first and are ordered by the number
9857 // of bad conversions and quality of good conversions.
9858 if (L->FailureKind == ovl_fail_bad_conversion) {
9859 if (R->FailureKind != ovl_fail_bad_conversion)
9860 return true;
9861
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009862 // The conversion that can be fixed with a smaller number of changes,
9863 // comes first.
9864 unsigned numLFixes = L->Fix.NumConversionsFixed;
9865 unsigned numRFixes = R->Fix.NumConversionsFixed;
9866 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9867 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009868 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009869 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009870 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009871
John McCallfe796dd2010-01-23 05:17:32 +00009872 // If there's any ordering between the defined conversions...
9873 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009874 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009875
9876 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009877 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009878 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009879 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009880 L->Conversions[I],
9881 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009882 case ImplicitConversionSequence::Better:
9883 leftBetter++;
9884 break;
9885
9886 case ImplicitConversionSequence::Worse:
9887 leftBetter--;
9888 break;
9889
9890 case ImplicitConversionSequence::Indistinguishable:
9891 break;
9892 }
9893 }
9894 if (leftBetter > 0) return true;
9895 if (leftBetter < 0) return false;
9896
9897 } else if (R->FailureKind == ovl_fail_bad_conversion)
9898 return false;
9899
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009900 if (L->FailureKind == ovl_fail_bad_deduction) {
9901 if (R->FailureKind != ovl_fail_bad_deduction)
9902 return true;
9903
9904 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9905 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009906 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009907 } else if (R->FailureKind == ovl_fail_bad_deduction)
9908 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009909
John McCall3712d9e2010-01-15 23:32:50 +00009910 // TODO: others?
9911 }
9912
9913 // Sort everything else by location.
9914 SourceLocation LLoc = GetLocationForCandidate(L);
9915 SourceLocation RLoc = GetLocationForCandidate(R);
9916
9917 // Put candidates without locations (e.g. builtins) at the end.
9918 if (LLoc.isInvalid()) return false;
9919 if (RLoc.isInvalid()) return true;
9920
9921 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009922 }
9923};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009924}
John McCall12f97bc2010-01-08 04:41:39 +00009925
John McCallfe796dd2010-01-23 05:17:32 +00009926/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009927/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009928static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9929 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009930 assert(!Cand->Viable);
9931
9932 // Don't do anything on failures other than bad conversion.
9933 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9934
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009935 // We only want the FixIts if all the arguments can be corrected.
9936 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009937 // Use a implicit copy initialization to check conversion fixes.
9938 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009939
John McCallfe796dd2010-01-23 05:17:32 +00009940 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009941 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009942 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009943 while (true) {
9944 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9945 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009946 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009947 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009948 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009949 }
John McCallfe796dd2010-01-23 05:17:32 +00009950 }
9951
9952 if (ConvIdx == ConvCount)
9953 return;
9954
John McCall65eb8792010-02-25 01:37:24 +00009955 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9956 "remaining conversion is initialized?");
9957
Douglas Gregoradc7a702010-04-16 17:45:54 +00009958 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009959 // operation somehow.
9960 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009961
9962 const FunctionProtoType* Proto;
9963 unsigned ArgIdx = ConvIdx;
9964
9965 if (Cand->IsSurrogate) {
9966 QualType ConvType
9967 = Cand->Surrogate->getConversionType().getNonReferenceType();
9968 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9969 ConvType = ConvPtrType->getPointeeType();
9970 Proto = ConvType->getAs<FunctionProtoType>();
9971 ArgIdx--;
9972 } else if (Cand->Function) {
9973 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9974 if (isa<CXXMethodDecl>(Cand->Function) &&
9975 !isa<CXXConstructorDecl>(Cand->Function))
9976 ArgIdx--;
9977 } else {
9978 // Builtin binary operator with a bad first conversion.
9979 assert(ConvCount <= 3);
9980 for (; ConvIdx != ConvCount; ++ConvIdx)
9981 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009982 = TryCopyInitialization(S, Args[ConvIdx],
9983 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009984 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009985 /*InOverloadResolution*/ true,
9986 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009987 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009988 return;
9989 }
9990
9991 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009992 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009993 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009994 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009995 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9996 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9997 /*InOverloadResolution=*/true,
9998 /*AllowObjCWritebackConversion=*/
9999 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010000 // Store the FixIt in the candidate if it exists.
10001 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010002 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010003 }
John McCallfe796dd2010-01-23 05:17:32 +000010004 else
10005 Cand->Conversions[ConvIdx].setEllipsis();
10006 }
10007}
10008
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010009/// PrintOverloadCandidates - When overload resolution fails, prints
10010/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010011/// set.
John McCall5c32be02010-08-24 20:38:10 +000010012void OverloadCandidateSet::NoteCandidates(Sema &S,
10013 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010014 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +000010015 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +000010016 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +000010017 // Sort the candidates by viability and position. Sorting directly would
10018 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010019 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010020 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10021 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +000010022 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010023 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010024 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010025 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010026 if (Cand->Function || Cand->IsSurrogate)
10027 Cands.push_back(Cand);
10028 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10029 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010030 }
10031 }
10032
John McCallad2587a2010-01-12 00:48:53 +000010033 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010034 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010035
John McCall0d1da222010-01-12 00:44:57 +000010036 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010037
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010038 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010039 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010040 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010041 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10042 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010043
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010044 // Set an arbitrary limit on the number of candidate functions we'll spam
10045 // the user with. FIXME: This limit should depend on details of the
10046 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010047 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010048 break;
10049 }
10050 ++CandsShown;
10051
John McCalld3224162010-01-08 00:58:21 +000010052 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010053 NoteFunctionCandidate(S, Cand, Args.size(),
10054 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010055 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010056 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010057 else {
10058 assert(Cand->Viable &&
10059 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010060 // Generally we only see ambiguities including viable builtin
10061 // operators if overload resolution got screwed up by an
10062 // ambiguous user-defined conversion.
10063 //
10064 // FIXME: It's quite possible for different conversions to see
10065 // different ambiguities, though.
10066 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010067 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010068 ReportedAmbiguousConversions = true;
10069 }
John McCalld3224162010-01-08 00:58:21 +000010070
John McCall0d1da222010-01-12 00:44:57 +000010071 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010072 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010073 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010074 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010075
10076 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010077 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010078}
10079
Larisse Voufo98b20f12013-07-19 23:00:19 +000010080static SourceLocation
10081GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10082 return Cand->Specialization ? Cand->Specialization->getLocation()
10083 : SourceLocation();
10084}
10085
Richard Smith17c00b42014-11-12 01:24:00 +000010086namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010087struct CompareTemplateSpecCandidatesForDisplay {
10088 Sema &S;
10089 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10090
10091 bool operator()(const TemplateSpecCandidate *L,
10092 const TemplateSpecCandidate *R) {
10093 // Fast-path this check.
10094 if (L == R)
10095 return false;
10096
10097 // Assuming that both candidates are not matches...
10098
10099 // Sort by the ranking of deduction failures.
10100 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10101 return RankDeductionFailure(L->DeductionFailure) <
10102 RankDeductionFailure(R->DeductionFailure);
10103
10104 // Sort everything else by location.
10105 SourceLocation LLoc = GetLocationForCandidate(L);
10106 SourceLocation RLoc = GetLocationForCandidate(R);
10107
10108 // Put candidates without locations (e.g. builtins) at the end.
10109 if (LLoc.isInvalid())
10110 return false;
10111 if (RLoc.isInvalid())
10112 return true;
10113
10114 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10115 }
10116};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010117}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010118
10119/// Diagnose a template argument deduction failure.
10120/// We are treating these failures as overload failures due to bad
10121/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010122void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10123 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010124 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010125 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010126}
10127
10128void TemplateSpecCandidateSet::destroyCandidates() {
10129 for (iterator i = begin(), e = end(); i != e; ++i) {
10130 i->DeductionFailure.Destroy();
10131 }
10132}
10133
10134void TemplateSpecCandidateSet::clear() {
10135 destroyCandidates();
10136 Candidates.clear();
10137}
10138
10139/// NoteCandidates - When no template specialization match is found, prints
10140/// diagnostic messages containing the non-matching specializations that form
10141/// the candidate set.
10142/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10143/// OCD == OCD_AllCandidates and Cand->Viable == false.
10144void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10145 // Sort the candidates by position (assuming no candidate is a match).
10146 // Sorting directly would be prohibitive, so we make a set of pointers
10147 // and sort those.
10148 SmallVector<TemplateSpecCandidate *, 32> Cands;
10149 Cands.reserve(size());
10150 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10151 if (Cand->Specialization)
10152 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010153 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010154 // in general, want to list every possible builtin candidate.
10155 }
10156
10157 std::sort(Cands.begin(), Cands.end(),
10158 CompareTemplateSpecCandidatesForDisplay(S));
10159
10160 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10161 // for generalization purposes (?).
10162 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10163
10164 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10165 unsigned CandsShown = 0;
10166 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10167 TemplateSpecCandidate *Cand = *I;
10168
10169 // Set an arbitrary limit on the number of candidates we'll spam
10170 // the user with. FIXME: This limit should depend on details of the
10171 // candidate list.
10172 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10173 break;
10174 ++CandsShown;
10175
10176 assert(Cand->Specialization &&
10177 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010178 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010179 }
10180
10181 if (I != E)
10182 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10183}
10184
Douglas Gregorb491ed32011-02-19 21:32:49 +000010185// [PossiblyAFunctionType] --> [Return]
10186// NonFunctionType --> NonFunctionType
10187// R (A) --> R(A)
10188// R (*)(A) --> R (A)
10189// R (&)(A) --> R (A)
10190// R (S::*)(A) --> R (A)
10191QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10192 QualType Ret = PossiblyAFunctionType;
10193 if (const PointerType *ToTypePtr =
10194 PossiblyAFunctionType->getAs<PointerType>())
10195 Ret = ToTypePtr->getPointeeType();
10196 else if (const ReferenceType *ToTypeRef =
10197 PossiblyAFunctionType->getAs<ReferenceType>())
10198 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010199 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010200 PossiblyAFunctionType->getAs<MemberPointerType>())
10201 Ret = MemTypePtr->getPointeeType();
10202 Ret =
10203 Context.getCanonicalType(Ret).getUnqualifiedType();
10204 return Ret;
10205}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010206
Richard Smith17c00b42014-11-12 01:24:00 +000010207namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010208// A helper class to help with address of function resolution
10209// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010210class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010211 Sema& S;
10212 Expr* SourceExpr;
10213 const QualType& TargetType;
10214 QualType TargetFunctionType; // Extracted function type from target type
10215
10216 bool Complain;
10217 //DeclAccessPair& ResultFunctionAccessPair;
10218 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010219
Douglas Gregorb491ed32011-02-19 21:32:49 +000010220 bool TargetTypeIsNonStaticMemberFunction;
10221 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010222 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010223 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010224
Douglas Gregorb491ed32011-02-19 21:32:49 +000010225 OverloadExpr::FindResult OvlExprInfo;
10226 OverloadExpr *OvlExpr;
10227 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010228 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010229 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010230
Douglas Gregorb491ed32011-02-19 21:32:49 +000010231public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010232 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10233 const QualType &TargetType, bool Complain)
10234 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10235 Complain(Complain), Context(S.getASTContext()),
10236 TargetTypeIsNonStaticMemberFunction(
10237 !!TargetType->getAs<MemberPointerType>()),
10238 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010239 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010240 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010241 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10242 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010243 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010244 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010245
David Majnemera4f7c7a2013-08-01 06:13:59 +000010246 if (TargetFunctionType->isFunctionType()) {
10247 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10248 if (!UME->isImplicitAccess() &&
10249 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10250 StaticMemberFunctionFromBoundPointer = true;
10251 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10252 DeclAccessPair dap;
10253 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10254 OvlExpr, false, &dap)) {
10255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10256 if (!Method->isStatic()) {
10257 // If the target type is a non-function type and the function found
10258 // is a non-static member function, pretend as if that was the
10259 // target, it's the only possible type to end up with.
10260 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010261
David Majnemera4f7c7a2013-08-01 06:13:59 +000010262 // And skip adding the function if its not in the proper form.
10263 // We'll diagnose this due to an empty set of functions.
10264 if (!OvlExprInfo.HasFormOfMemberPointer)
10265 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010266 }
10267
David Majnemera4f7c7a2013-08-01 06:13:59 +000010268 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010269 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010270 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010271 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010272
10273 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010274 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010275
Douglas Gregorb491ed32011-02-19 21:32:49 +000010276 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10277 // C++ [over.over]p4:
10278 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010279 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010280 if (FoundNonTemplateFunction)
10281 EliminateAllTemplateMatches();
10282 else
10283 EliminateAllExceptMostSpecializedTemplate();
10284 }
10285 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010286
10287 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10288 Matches.size() > 1)
10289 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010290 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010291
10292 bool hasComplained() const { return HasComplained; }
10293
Douglas Gregorb491ed32011-02-19 21:32:49 +000010294private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010295 // Is A considered a better overload candidate for the desired type than B?
10296 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10297 return hasBetterEnableIfAttrs(S, A, B);
10298 }
10299
10300 // Returns true if we've eliminated any (read: all but one) candidates, false
10301 // otherwise.
10302 bool eliminiateSuboptimalOverloadCandidates() {
10303 // Same algorithm as overload resolution -- one pass to pick the "best",
10304 // another pass to be sure that nothing is better than the best.
10305 auto Best = Matches.begin();
10306 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10307 if (isBetterCandidate(I->second, Best->second))
10308 Best = I;
10309
10310 const FunctionDecl *BestFn = Best->second;
10311 auto IsBestOrInferiorToBest = [this, BestFn](
10312 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10313 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10314 };
10315
10316 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10317 // option, so we can potentially give the user a better error
10318 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10319 return false;
10320 Matches[0] = *Best;
10321 Matches.resize(1);
10322 return true;
10323 }
10324
Douglas Gregorb491ed32011-02-19 21:32:49 +000010325 bool isTargetTypeAFunction() const {
10326 return TargetFunctionType->isFunctionType();
10327 }
10328
10329 // [ToType] [Return]
10330
10331 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10332 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10333 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10334 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10335 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10336 }
10337
10338 // return true if any matching specializations were found
10339 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10340 const DeclAccessPair& CurAccessFunPair) {
10341 if (CXXMethodDecl *Method
10342 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10343 // Skip non-static function templates when converting to pointer, and
10344 // static when converting to member pointer.
10345 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10346 return false;
10347 }
10348 else if (TargetTypeIsNonStaticMemberFunction)
10349 return false;
10350
10351 // C++ [over.over]p2:
10352 // If the name is a function template, template argument deduction is
10353 // done (14.8.2.2), and if the argument deduction succeeds, the
10354 // resulting template argument list is used to generate a single
10355 // function template specialization, which is added to the set of
10356 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010357 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010358 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010359 if (Sema::TemplateDeductionResult Result
10360 = S.DeduceTemplateArguments(FunctionTemplate,
10361 &OvlExplicitTemplateArgs,
10362 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010363 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010364 // Make a note of the failed deduction for diagnostics.
10365 FailedCandidates.addCandidate()
10366 .set(FunctionTemplate->getTemplatedDecl(),
10367 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010368 return false;
10369 }
10370
Douglas Gregor19a41f12013-04-17 08:45:07 +000010371 // Template argument deduction ensures that we have an exact match or
10372 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010373 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010374 assert(S.isSameOrCompatibleFunctionType(
10375 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010376 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010377
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010378 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010379 return false;
10380
Douglas Gregorb491ed32011-02-19 21:32:49 +000010381 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10382 return true;
10383 }
10384
10385 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10386 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010388 // Skip non-static functions when converting to pointer, and static
10389 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010390 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10391 return false;
10392 }
10393 else if (TargetTypeIsNonStaticMemberFunction)
10394 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010395
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010396 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010397 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010398 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010399 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010400 return false;
10401
Richard Smith2a7d4812013-05-04 07:00:32 +000010402 // If any candidate has a placeholder return type, trigger its deduction
10403 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010404 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010405 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010406 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10407 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010408 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010409 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010410
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010411 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010412 return false;
10413
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010414 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010415 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10416 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010417 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010418 ResultTy) ||
10419 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10420 Matches.push_back(std::make_pair(
10421 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010422 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010423 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010424 }
Mike Stump11289f42009-09-09 15:08:12 +000010425 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010426
10427 return false;
10428 }
10429
10430 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10431 bool Ret = false;
10432
10433 // If the overload expression doesn't have the form of a pointer to
10434 // member, don't try to convert it to a pointer-to-member type.
10435 if (IsInvalidFormOfPointerToMemberFunction())
10436 return false;
10437
10438 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10439 E = OvlExpr->decls_end();
10440 I != E; ++I) {
10441 // Look through any using declarations to find the underlying function.
10442 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10443
10444 // C++ [over.over]p3:
10445 // Non-member functions and static member functions match
10446 // targets of type "pointer-to-function" or "reference-to-function."
10447 // Nonstatic member functions match targets of
10448 // type "pointer-to-member-function."
10449 // Note that according to DR 247, the containing class does not matter.
10450 if (FunctionTemplateDecl *FunctionTemplate
10451 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10452 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10453 Ret = true;
10454 }
10455 // If we have explicit template arguments supplied, skip non-templates.
10456 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10457 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10458 Ret = true;
10459 }
10460 assert(Ret || Matches.empty());
10461 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010462 }
10463
Douglas Gregorb491ed32011-02-19 21:32:49 +000010464 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010465 // [...] and any given function template specialization F1 is
10466 // eliminated if the set contains a second function template
10467 // specialization whose function template is more specialized
10468 // than the function template of F1 according to the partial
10469 // ordering rules of 14.5.5.2.
10470
10471 // The algorithm specified above is quadratic. We instead use a
10472 // two-pass algorithm (similar to the one used to identify the
10473 // best viable function in an overload set) that identifies the
10474 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010475
10476 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10477 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10478 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010479
Larisse Voufo98b20f12013-07-19 23:00:19 +000010480 // TODO: It looks like FailedCandidates does not serve much purpose
10481 // here, since the no_viable diagnostic has index 0.
10482 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010483 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010484 SourceExpr->getLocStart(), S.PDiag(),
10485 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10486 .second->getDeclName(),
10487 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10488 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010489
Douglas Gregorb491ed32011-02-19 21:32:49 +000010490 if (Result != MatchesCopy.end()) {
10491 // Make it the first and only element
10492 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10493 Matches[0].second = cast<FunctionDecl>(*Result);
10494 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010495 } else
10496 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010498
Douglas Gregorb491ed32011-02-19 21:32:49 +000010499 void EliminateAllTemplateMatches() {
10500 // [...] any function template specializations in the set are
10501 // eliminated if the set also contains a non-template function, [...]
10502 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010503 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010504 ++I;
10505 else {
10506 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010507 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010508 }
10509 }
10510 }
10511
Artem Belevich94a55e82015-09-22 17:22:59 +000010512 void EliminateSuboptimalCudaMatches() {
10513 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10514 }
10515
Douglas Gregorb491ed32011-02-19 21:32:49 +000010516public:
10517 void ComplainNoMatchesFound() const {
10518 assert(Matches.empty());
10519 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10520 << OvlExpr->getName() << TargetFunctionType
10521 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010522 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010523 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10524 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010525 else {
10526 // We have some deduction failure messages. Use them to diagnose
10527 // the function templates, and diagnose the non-template candidates
10528 // normally.
10529 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10530 IEnd = OvlExpr->decls_end();
10531 I != IEnd; ++I)
10532 if (FunctionDecl *Fun =
10533 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010534 if (!functionHasPassObjectSizeParams(Fun))
10535 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10536 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010537 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10538 }
10539 }
10540
Douglas Gregorb491ed32011-02-19 21:32:49 +000010541 bool IsInvalidFormOfPointerToMemberFunction() const {
10542 return TargetTypeIsNonStaticMemberFunction &&
10543 !OvlExprInfo.HasFormOfMemberPointer;
10544 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010545
Douglas Gregorb491ed32011-02-19 21:32:49 +000010546 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10547 // TODO: Should we condition this on whether any functions might
10548 // have matched, or is it more appropriate to do that in callers?
10549 // TODO: a fixit wouldn't hurt.
10550 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10551 << TargetType << OvlExpr->getSourceRange();
10552 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010553
10554 bool IsStaticMemberFunctionFromBoundPointer() const {
10555 return StaticMemberFunctionFromBoundPointer;
10556 }
10557
10558 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10559 S.Diag(OvlExpr->getLocStart(),
10560 diag::err_invalid_form_pointer_member_function)
10561 << OvlExpr->getSourceRange();
10562 }
10563
Douglas Gregorb491ed32011-02-19 21:32:49 +000010564 void ComplainOfInvalidConversion() const {
10565 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10566 << OvlExpr->getName() << TargetType;
10567 }
10568
10569 void ComplainMultipleMatchesFound() const {
10570 assert(Matches.size() > 1);
10571 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10572 << OvlExpr->getName()
10573 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010574 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10575 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010576 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010577
10578 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10579
Douglas Gregorb491ed32011-02-19 21:32:49 +000010580 int getNumMatches() const { return Matches.size(); }
10581
10582 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010583 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010584 return Matches[0].second;
10585 }
10586
10587 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010588 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010589 return &Matches[0].first;
10590 }
10591};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010592}
Richard Smith17c00b42014-11-12 01:24:00 +000010593
Douglas Gregorb491ed32011-02-19 21:32:49 +000010594/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10595/// an overloaded function (C++ [over.over]), where @p From is an
10596/// expression with overloaded function type and @p ToType is the type
10597/// we're trying to resolve to. For example:
10598///
10599/// @code
10600/// int f(double);
10601/// int f(int);
10602///
10603/// int (*pfd)(double) = f; // selects f(double)
10604/// @endcode
10605///
10606/// This routine returns the resulting FunctionDecl if it could be
10607/// resolved, and NULL otherwise. When @p Complain is true, this
10608/// routine will emit diagnostics if there is an error.
10609FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010610Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10611 QualType TargetType,
10612 bool Complain,
10613 DeclAccessPair &FoundResult,
10614 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010615 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010616
10617 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10618 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010619 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010620 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010621 bool ShouldComplain = Complain && !Resolver.hasComplained();
10622 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010623 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10624 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10625 else
10626 Resolver.ComplainNoMatchesFound();
10627 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010628 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010629 Resolver.ComplainMultipleMatchesFound();
10630 else if (NumMatches == 1) {
10631 Fn = Resolver.getMatchingFunctionDecl();
10632 assert(Fn);
10633 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010634 if (Complain) {
10635 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10636 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10637 else
10638 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10639 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010640 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010641
10642 if (pHadMultipleCandidates)
10643 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010644 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010645}
10646
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010647/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010648/// resolve that overloaded function expression down to a single function.
10649///
10650/// This routine can only resolve template-ids that refer to a single function
10651/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010652/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010653/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010654///
10655/// If no template-ids are found, no diagnostics are emitted and NULL is
10656/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010657FunctionDecl *
10658Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10659 bool Complain,
10660 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010661 // C++ [over.over]p1:
10662 // [...] [Note: any redundant set of parentheses surrounding the
10663 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010664 // C++ [over.over]p1:
10665 // [...] The overloaded function name can be preceded by the &
10666 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010667
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010668 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010669 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010670 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010671
10672 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010673 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010674 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010675
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010676 // Look through all of the overloaded functions, searching for one
10677 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010678 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010679 for (UnresolvedSetIterator I = ovl->decls_begin(),
10680 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010681 // C++0x [temp.arg.explicit]p3:
10682 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010683 // where deduction is not done, if a template argument list is
10684 // specified and it, along with any default template arguments,
10685 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010686 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010687 FunctionTemplateDecl *FunctionTemplate
10688 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010689
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010690 // C++ [over.over]p2:
10691 // If the name is a function template, template argument deduction is
10692 // done (14.8.2.2), and if the argument deduction succeeds, the
10693 // resulting template argument list is used to generate a single
10694 // function template specialization, which is added to the set of
10695 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010696 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010697 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010698 if (TemplateDeductionResult Result
10699 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010700 Specialization, Info,
10701 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010702 // Make a note of the failed deduction for diagnostics.
10703 // TODO: Actually use the failed-deduction info?
10704 FailedCandidates.addCandidate()
10705 .set(FunctionTemplate->getTemplatedDecl(),
10706 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010707 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010708 }
10709
John McCall0009fcc2011-04-26 20:42:42 +000010710 assert(Specialization && "no specialization and no error?");
10711
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010712 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010713 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010714 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010715 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10716 << ovl->getName();
10717 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010718 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010719 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010720 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010721
John McCall0009fcc2011-04-26 20:42:42 +000010722 Matched = Specialization;
10723 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010725
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010726 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010727 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010728 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010729 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010730
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010731 return Matched;
10732}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010733
Douglas Gregor1beec452011-03-12 01:48:56 +000010734
10735
10736
John McCall50a2c2c2011-10-11 23:14:30 +000010737// Resolve and fix an overloaded expression that can be resolved
10738// because it identifies a single function template specialization.
10739//
Douglas Gregor1beec452011-03-12 01:48:56 +000010740// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010741//
10742// Return true if it was logically possible to so resolve the
10743// expression, regardless of whether or not it succeeded. Always
10744// returns true if 'complain' is set.
10745bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10746 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010747 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010748 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010749 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010750 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010751
John McCall50a2c2c2011-10-11 23:14:30 +000010752 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010753
John McCall0009fcc2011-04-26 20:42:42 +000010754 DeclAccessPair found;
10755 ExprResult SingleFunctionExpression;
10756 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10757 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010758 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010759 SrcExpr = ExprError();
10760 return true;
10761 }
John McCall0009fcc2011-04-26 20:42:42 +000010762
10763 // It is only correct to resolve to an instance method if we're
10764 // resolving a form that's permitted to be a pointer to member.
10765 // Otherwise we'll end up making a bound member expression, which
10766 // is illegal in all the contexts we resolve like this.
10767 if (!ovl.HasFormOfMemberPointer &&
10768 isa<CXXMethodDecl>(fn) &&
10769 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010770 if (!complain) return false;
10771
10772 Diag(ovl.Expression->getExprLoc(),
10773 diag::err_bound_member_function)
10774 << 0 << ovl.Expression->getSourceRange();
10775
10776 // TODO: I believe we only end up here if there's a mix of
10777 // static and non-static candidates (otherwise the expression
10778 // would have 'bound member' type, not 'overload' type).
10779 // Ideally we would note which candidate was chosen and why
10780 // the static candidates were rejected.
10781 SrcExpr = ExprError();
10782 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010783 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010784
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010785 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010786 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010787 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010788
10789 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010790 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010791 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010792 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010793 if (SingleFunctionExpression.isInvalid()) {
10794 SrcExpr = ExprError();
10795 return true;
10796 }
10797 }
John McCall0009fcc2011-04-26 20:42:42 +000010798 }
10799
10800 if (!SingleFunctionExpression.isUsable()) {
10801 if (complain) {
10802 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10803 << ovl.Expression->getName()
10804 << DestTypeForComplaining
10805 << OpRangeForComplaining
10806 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010807 NoteAllOverloadCandidates(SrcExpr.get());
10808
10809 SrcExpr = ExprError();
10810 return true;
10811 }
10812
10813 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010814 }
10815
John McCall50a2c2c2011-10-11 23:14:30 +000010816 SrcExpr = SingleFunctionExpression;
10817 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010818}
10819
Douglas Gregorcabea402009-09-22 15:41:20 +000010820/// \brief Add a single candidate to the overload set.
10821static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010822 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010823 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010824 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010825 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010826 bool PartialOverloading,
10827 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010828 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010829 if (isa<UsingShadowDecl>(Callee))
10830 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10831
Douglas Gregorcabea402009-09-22 15:41:20 +000010832 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010833 if (ExplicitTemplateArgs) {
10834 assert(!KnownValid && "Explicit template arguments?");
10835 return;
10836 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010837 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10838 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010839 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010840 return;
John McCalld14a8642009-11-21 08:51:07 +000010841 }
10842
10843 if (FunctionTemplateDecl *FuncTemplate
10844 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010845 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010846 ExplicitTemplateArgs, Args, CandidateSet,
10847 /*SuppressUsedConversions=*/false,
10848 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010849 return;
10850 }
10851
Richard Smith95ce4f62011-06-26 22:19:54 +000010852 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010853}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010854
Douglas Gregorcabea402009-09-22 15:41:20 +000010855/// \brief Add the overload candidates named by callee and/or found by argument
10856/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010857void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010858 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010859 OverloadCandidateSet &CandidateSet,
10860 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010861
10862#ifndef NDEBUG
10863 // Verify that ArgumentDependentLookup is consistent with the rules
10864 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010865 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010866 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10867 // and let Y be the lookup set produced by argument dependent
10868 // lookup (defined as follows). If X contains
10869 //
10870 // -- a declaration of a class member, or
10871 //
10872 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010873 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010874 //
10875 // -- a declaration that is neither a function or a function
10876 // template
10877 //
10878 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010879
John McCall57500772009-12-16 12:17:52 +000010880 if (ULE->requiresADL()) {
10881 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10882 E = ULE->decls_end(); I != E; ++I) {
10883 assert(!(*I)->getDeclContext()->isRecord());
10884 assert(isa<UsingShadowDecl>(*I) ||
10885 !(*I)->getDeclContext()->isFunctionOrMethod());
10886 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010887 }
10888 }
10889#endif
10890
John McCall57500772009-12-16 12:17:52 +000010891 // It would be nice to avoid this copy.
10892 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010893 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010894 if (ULE->hasExplicitTemplateArgs()) {
10895 ULE->copyTemplateArgumentsInto(TABuffer);
10896 ExplicitTemplateArgs = &TABuffer;
10897 }
10898
10899 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10900 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010901 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10902 CandidateSet, PartialOverloading,
10903 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010904
John McCall57500772009-12-16 12:17:52 +000010905 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010906 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010907 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010908 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010909}
John McCalld681c392009-12-16 08:11:27 +000010910
Richard Smith0603bbb2013-06-12 22:56:54 +000010911/// Determine whether a declaration with the specified name could be moved into
10912/// a different namespace.
10913static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10914 switch (Name.getCXXOverloadedOperator()) {
10915 case OO_New: case OO_Array_New:
10916 case OO_Delete: case OO_Array_Delete:
10917 return false;
10918
10919 default:
10920 return true;
10921 }
10922}
10923
Richard Smith998a5912011-06-05 22:42:48 +000010924/// Attempt to recover from an ill-formed use of a non-dependent name in a
10925/// template, where the non-dependent name was declared after the template
10926/// was defined. This is common in code written for a compilers which do not
10927/// correctly implement two-stage name lookup.
10928///
10929/// Returns true if a viable candidate was found and a diagnostic was issued.
10930static bool
10931DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10932 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010933 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010934 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010935 ArrayRef<Expr *> Args,
10936 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010937 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10938 return false;
10939
10940 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010941 if (DC->isTransparentContext())
10942 continue;
10943
Richard Smith998a5912011-06-05 22:42:48 +000010944 SemaRef.LookupQualifiedName(R, DC);
10945
10946 if (!R.empty()) {
10947 R.suppressDiagnostics();
10948
10949 if (isa<CXXRecordDecl>(DC)) {
10950 // Don't diagnose names we find in classes; we get much better
10951 // diagnostics for these from DiagnoseEmptyLookup.
10952 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010953 if (DoDiagnoseEmptyLookup)
10954 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010955 return false;
10956 }
10957
Richard Smith100b24a2014-04-17 01:52:14 +000010958 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010959 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10960 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010961 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010962 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010963
10964 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010965 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010966 // No viable functions. Don't bother the user with notes for functions
10967 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010968 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010969 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010970 }
Richard Smith998a5912011-06-05 22:42:48 +000010971
10972 // Find the namespaces where ADL would have looked, and suggest
10973 // declaring the function there instead.
10974 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10975 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010976 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010977 AssociatedNamespaces,
10978 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010979 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010980 if (canBeDeclaredInNamespace(R.getLookupName())) {
10981 DeclContext *Std = SemaRef.getStdNamespace();
10982 for (Sema::AssociatedNamespaceSet::iterator
10983 it = AssociatedNamespaces.begin(),
10984 end = AssociatedNamespaces.end(); it != end; ++it) {
10985 // Never suggest declaring a function within namespace 'std'.
10986 if (Std && Std->Encloses(*it))
10987 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010988
Richard Smith0603bbb2013-06-12 22:56:54 +000010989 // Never suggest declaring a function within a namespace with a
10990 // reserved name, like __gnu_cxx.
10991 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10992 if (NS &&
10993 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10994 continue;
10995
10996 SuggestedNamespaces.insert(*it);
10997 }
Richard Smith998a5912011-06-05 22:42:48 +000010998 }
10999
11000 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11001 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011002 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011003 SemaRef.Diag(Best->Function->getLocation(),
11004 diag::note_not_found_by_two_phase_lookup)
11005 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011006 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011007 SemaRef.Diag(Best->Function->getLocation(),
11008 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011009 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011010 } else {
11011 // FIXME: It would be useful to list the associated namespaces here,
11012 // but the diagnostics infrastructure doesn't provide a way to produce
11013 // a localized representation of a list of items.
11014 SemaRef.Diag(Best->Function->getLocation(),
11015 diag::note_not_found_by_two_phase_lookup)
11016 << R.getLookupName() << 2;
11017 }
11018
11019 // Try to recover by calling this function.
11020 return true;
11021 }
11022
11023 R.clear();
11024 }
11025
11026 return false;
11027}
11028
11029/// Attempt to recover from ill-formed use of a non-dependent operator in a
11030/// template, where the non-dependent operator was declared after the template
11031/// was defined.
11032///
11033/// Returns true if a viable candidate was found and a diagnostic was issued.
11034static bool
11035DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11036 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011037 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011038 DeclarationName OpName =
11039 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11040 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11041 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011042 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011043 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011044}
11045
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011046namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011047class BuildRecoveryCallExprRAII {
11048 Sema &SemaRef;
11049public:
11050 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11051 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11052 SemaRef.IsBuildingRecoveryCallExpr = true;
11053 }
11054
11055 ~BuildRecoveryCallExprRAII() {
11056 SemaRef.IsBuildingRecoveryCallExpr = false;
11057 }
11058};
11059
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011060}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011061
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011062static std::unique_ptr<CorrectionCandidateCallback>
11063MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11064 bool HasTemplateArgs, bool AllowTypoCorrection) {
11065 if (!AllowTypoCorrection)
11066 return llvm::make_unique<NoTypoCorrectionCCC>();
11067 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11068 HasTemplateArgs, ME);
11069}
11070
John McCalld681c392009-12-16 08:11:27 +000011071/// Attempts to recover from a call where no functions were found.
11072///
11073/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011074static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011075BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011076 UnresolvedLookupExpr *ULE,
11077 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011078 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011079 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011080 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011081 // Do not try to recover if it is already building a recovery call.
11082 // This stops infinite loops for template instantiations like
11083 //
11084 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11085 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11086 //
11087 if (SemaRef.IsBuildingRecoveryCallExpr)
11088 return ExprError();
11089 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011090
11091 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011092 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011093 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011094
John McCall57500772009-12-16 12:17:52 +000011095 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011096 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011097 if (ULE->hasExplicitTemplateArgs()) {
11098 ULE->copyTemplateArgumentsInto(TABuffer);
11099 ExplicitTemplateArgs = &TABuffer;
11100 }
11101
John McCalld681c392009-12-16 08:11:27 +000011102 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11103 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011104 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011105 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011106 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011107 ExplicitTemplateArgs, Args,
11108 &DoDiagnoseEmptyLookup) &&
11109 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11110 S, SS, R,
11111 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11112 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11113 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011114 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011115
John McCall57500772009-12-16 12:17:52 +000011116 assert(!R.empty() && "lookup results empty despite recovery");
11117
11118 // Build an implicit member call if appropriate. Just drop the
11119 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011120 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011121 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011122 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11123 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011124 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011125 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011126 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011127 else
11128 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11129
11130 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011131 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011132
11133 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011134 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011135 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011136 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011137 MultiExprArg(Args.data(), Args.size()),
11138 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011139}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011140
Sam Panzer0f384432012-08-21 00:52:01 +000011141/// \brief Constructs and populates an OverloadedCandidateSet from
11142/// the given function.
11143/// \returns true when an the ExprResult output parameter has been set.
11144bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11145 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011146 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011147 SourceLocation RParenLoc,
11148 OverloadCandidateSet *CandidateSet,
11149 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011150#ifndef NDEBUG
11151 if (ULE->requiresADL()) {
11152 // To do ADL, we must have found an unqualified name.
11153 assert(!ULE->getQualifier() && "qualified name with ADL");
11154
11155 // We don't perform ADL for implicit declarations of builtins.
11156 // Verify that this was correctly set up.
11157 FunctionDecl *F;
11158 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11159 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11160 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011161 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011162
John McCall57500772009-12-16 12:17:52 +000011163 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011164 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011165 }
John McCall57500772009-12-16 12:17:52 +000011166#endif
11167
John McCall4124c492011-10-17 18:40:02 +000011168 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011169 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011170 *Result = ExprError();
11171 return true;
11172 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011173
John McCall57500772009-12-16 12:17:52 +000011174 // Add the functions denoted by the callee to the set of candidate
11175 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011176 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011177
Hans Wennborgb2747382015-06-12 21:23:23 +000011178 if (getLangOpts().MSVCCompat &&
11179 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011180 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11181
11182 OverloadCandidateSet::iterator Best;
11183 if (CandidateSet->empty() ||
11184 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11185 OR_No_Viable_Function) {
11186 // In Microsoft mode, if we are inside a template class member function then
11187 // create a type dependent CallExpr. The goal is to postpone name lookup
11188 // to instantiation time to be able to search into type dependent base
11189 // classes.
11190 CallExpr *CE = new (Context) CallExpr(
11191 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011192 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011193 CE->setValueDependent(true);
11194 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011195 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011196 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011197 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011198 }
John McCalld681c392009-12-16 08:11:27 +000011199
Hans Wennborg64937c62015-06-11 21:21:57 +000011200 if (CandidateSet->empty())
11201 return false;
11202
John McCall4124c492011-10-17 18:40:02 +000011203 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011204 return false;
11205}
John McCall4124c492011-10-17 18:40:02 +000011206
Sam Panzer0f384432012-08-21 00:52:01 +000011207/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11208/// the completed call expression. If overload resolution fails, emits
11209/// diagnostics and returns ExprError()
11210static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11211 UnresolvedLookupExpr *ULE,
11212 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011213 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011214 SourceLocation RParenLoc,
11215 Expr *ExecConfig,
11216 OverloadCandidateSet *CandidateSet,
11217 OverloadCandidateSet::iterator *Best,
11218 OverloadingResult OverloadResult,
11219 bool AllowTypoCorrection) {
11220 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011221 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011222 RParenLoc, /*EmptyLookup=*/true,
11223 AllowTypoCorrection);
11224
11225 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011226 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011227 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011228 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011229 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11230 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011231 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011232 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11233 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011234 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011235
Richard Smith998a5912011-06-05 22:42:48 +000011236 case OR_No_Viable_Function: {
11237 // Try to recover by looking for viable functions which the user might
11238 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011239 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011240 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011241 /*EmptyLookup=*/false,
11242 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011243 if (!Recovery.isInvalid())
11244 return Recovery;
11245
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011246 // If the user passes in a function that we can't take the address of, we
11247 // generally end up emitting really bad error messages. Here, we attempt to
11248 // emit better ones.
11249 for (const Expr *Arg : Args) {
11250 if (!Arg->getType()->isFunctionType())
11251 continue;
11252 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11253 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11254 if (FD &&
11255 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11256 Arg->getExprLoc()))
11257 return ExprError();
11258 }
11259 }
11260
11261 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11262 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011263 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011264 break;
Richard Smith998a5912011-06-05 22:42:48 +000011265 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011266
11267 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011268 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011269 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011270 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011271 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011272
Sam Panzer0f384432012-08-21 00:52:01 +000011273 case OR_Deleted: {
11274 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11275 << (*Best)->Function->isDeleted()
11276 << ULE->getName()
11277 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11278 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011279 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011280
Sam Panzer0f384432012-08-21 00:52:01 +000011281 // We emitted an error for the unvailable/deleted function call but keep
11282 // the call in the AST.
11283 FunctionDecl *FDecl = (*Best)->Function;
11284 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011285 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11286 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011287 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011288 }
11289
Douglas Gregorb412e172010-07-25 18:17:45 +000011290 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011291 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011292}
11293
George Burgess IV7204ed92016-01-07 02:26:57 +000011294static void markUnaddressableCandidatesUnviable(Sema &S,
11295 OverloadCandidateSet &CS) {
11296 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11297 if (I->Viable &&
11298 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11299 I->Viable = false;
11300 I->FailureKind = ovl_fail_addr_not_available;
11301 }
11302 }
11303}
11304
Sam Panzer0f384432012-08-21 00:52:01 +000011305/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11306/// (which eventually refers to the declaration Func) and the call
11307/// arguments Args/NumArgs, attempt to resolve the function call down
11308/// to a specific function. If overload resolution succeeds, returns
11309/// the call expression produced by overload resolution.
11310/// Otherwise, emits diagnostics and returns ExprError.
11311ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11312 UnresolvedLookupExpr *ULE,
11313 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011314 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011315 SourceLocation RParenLoc,
11316 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011317 bool AllowTypoCorrection,
11318 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011319 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11320 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011321 ExprResult result;
11322
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011323 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11324 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011325 return result;
11326
George Burgess IV7204ed92016-01-07 02:26:57 +000011327 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11328 // functions that aren't addressible are considered unviable.
11329 if (CalleesAddressIsTaken)
11330 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11331
Sam Panzer0f384432012-08-21 00:52:01 +000011332 OverloadCandidateSet::iterator Best;
11333 OverloadingResult OverloadResult =
11334 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11335
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011336 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011337 RParenLoc, ExecConfig, &CandidateSet,
11338 &Best, OverloadResult,
11339 AllowTypoCorrection);
11340}
11341
John McCall4c4c1df2010-01-26 03:27:55 +000011342static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011343 return Functions.size() > 1 ||
11344 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11345}
11346
Douglas Gregor084d8552009-03-13 23:49:33 +000011347/// \brief Create a unary operation that may resolve to an overloaded
11348/// operator.
11349///
11350/// \param OpLoc The location of the operator itself (e.g., '*').
11351///
Craig Toppera92ffb02015-12-10 08:51:49 +000011352/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011353///
James Dennett18348b62012-06-22 08:52:37 +000011354/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011355/// considered by overload resolution. The caller needs to build this
11356/// set based on the context using, e.g.,
11357/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11358/// set should not contain any member functions; those will be added
11359/// by CreateOverloadedUnaryOp().
11360///
James Dennett91738ff2012-06-22 10:32:46 +000011361/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011362ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011363Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011364 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011365 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011366 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11367 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11368 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011369 // TODO: provide better source location info.
11370 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011371
John McCall4124c492011-10-17 18:40:02 +000011372 if (checkPlaceholderForOverload(*this, Input))
11373 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011374
Craig Topperc3ec1492014-05-26 06:22:03 +000011375 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011376 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011377
Douglas Gregor084d8552009-03-13 23:49:33 +000011378 // For post-increment and post-decrement, add the implicit '0' as
11379 // the second argument, so that we know this is a post-increment or
11380 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011381 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011382 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011383 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11384 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011385 NumArgs = 2;
11386 }
11387
Richard Smithe54c3072013-05-05 15:51:06 +000011388 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11389
Douglas Gregor084d8552009-03-13 23:49:33 +000011390 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011391 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011392 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11393 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011394
Craig Topperc3ec1492014-05-26 06:22:03 +000011395 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011396 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011397 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011398 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011399 /*ADL*/ true, IsOverloaded(Fns),
11400 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011401 return new (Context)
11402 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11403 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011404 }
11405
11406 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011407 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011408
11409 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011410 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011411
11412 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011413 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011414
John McCall4c4c1df2010-01-26 03:27:55 +000011415 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011416 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011417 /*ExplicitTemplateArgs*/nullptr,
11418 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011419
Douglas Gregor084d8552009-03-13 23:49:33 +000011420 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011421 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011422
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011423 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11424
Douglas Gregor084d8552009-03-13 23:49:33 +000011425 // Perform overload resolution.
11426 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011427 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011428 case OR_Success: {
11429 // We found a built-in operator or an overloaded operator.
11430 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011431
Douglas Gregor084d8552009-03-13 23:49:33 +000011432 if (FnDecl) {
11433 // We matched an overloaded operator. Build a call to that
11434 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011435
Douglas Gregor084d8552009-03-13 23:49:33 +000011436 // Convert the arguments.
11437 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011438 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011439
John Wiegley01296292011-04-08 18:41:53 +000011440 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011441 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011442 Best->FoundDecl, Method);
11443 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011444 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011445 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011446 } else {
11447 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011448 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011449 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011450 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011451 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011452 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011453 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011454 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011455 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011456 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011457 }
11458
Douglas Gregor084d8552009-03-13 23:49:33 +000011459 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011460 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011461 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011462 if (FnExpr.isInvalid())
11463 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011464
Richard Smithc1564702013-11-15 02:58:23 +000011465 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011466 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011467 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11468 ResultTy = ResultTy.getNonLValueExprType(Context);
11469
Eli Friedman030eee42009-11-18 03:58:17 +000011470 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011471 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011472 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011473 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011474
Alp Toker314cc812014-01-25 16:55:45 +000011475 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011476 return ExprError();
11477
John McCallb268a282010-08-23 23:25:46 +000011478 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011479 } else {
11480 // We matched a built-in operator. Convert the arguments, then
11481 // break out so that we will build the appropriate built-in
11482 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011483 ExprResult InputRes =
11484 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11485 Best->Conversions[0], AA_Passing);
11486 if (InputRes.isInvalid())
11487 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011488 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011489 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011490 }
John Wiegley01296292011-04-08 18:41:53 +000011491 }
11492
11493 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011494 // This is an erroneous use of an operator which can be overloaded by
11495 // a non-member function. Check for non-member operators which were
11496 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011497 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011498 // FIXME: Recover by calling the found function.
11499 return ExprError();
11500
John Wiegley01296292011-04-08 18:41:53 +000011501 // No viable function; fall through to handling this as a
11502 // built-in operator, which will produce an error message for us.
11503 break;
11504
11505 case OR_Ambiguous:
11506 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11507 << UnaryOperator::getOpcodeStr(Opc)
11508 << Input->getType()
11509 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011510 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011511 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11512 return ExprError();
11513
11514 case OR_Deleted:
11515 Diag(OpLoc, diag::err_ovl_deleted_oper)
11516 << Best->Function->isDeleted()
11517 << UnaryOperator::getOpcodeStr(Opc)
11518 << getDeletedOrUnavailableSuffix(Best->Function)
11519 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011520 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011521 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011522 return ExprError();
11523 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011524
11525 // Either we found no viable overloaded operator or we matched a
11526 // built-in operator. In either case, fall through to trying to
11527 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011528 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011529}
11530
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011531/// \brief Create a binary operation that may resolve to an overloaded
11532/// operator.
11533///
11534/// \param OpLoc The location of the operator itself (e.g., '+').
11535///
Craig Toppera92ffb02015-12-10 08:51:49 +000011536/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011537///
James Dennett18348b62012-06-22 08:52:37 +000011538/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011539/// considered by overload resolution. The caller needs to build this
11540/// set based on the context using, e.g.,
11541/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11542/// set should not contain any member functions; those will be added
11543/// by CreateOverloadedBinOp().
11544///
11545/// \param LHS Left-hand argument.
11546/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011547ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011548Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011549 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011550 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011551 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011552 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011553 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011554
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011555 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11556 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11557
11558 // If either side is type-dependent, create an appropriate dependent
11559 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011560 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011561 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011562 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011563 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011564 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011565 return new (Context) BinaryOperator(
11566 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11567 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011568
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011569 return new (Context) CompoundAssignOperator(
11570 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11571 Context.DependentTy, Context.DependentTy, OpLoc,
11572 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011573 }
John McCall4c4c1df2010-01-26 03:27:55 +000011574
11575 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011576 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011577 // TODO: provide better source location info in DNLoc component.
11578 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011579 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011580 = UnresolvedLookupExpr::Create(Context, NamingClass,
11581 NestedNameSpecifierLoc(), OpNameInfo,
11582 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011583 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011584 return new (Context)
11585 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11586 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011587 }
11588
John McCall4124c492011-10-17 18:40:02 +000011589 // Always do placeholder-like conversions on the RHS.
11590 if (checkPlaceholderForOverload(*this, Args[1]))
11591 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011592
John McCall526ab472011-10-25 17:37:35 +000011593 // Do placeholder-like conversion on the LHS; note that we should
11594 // not get here with a PseudoObject LHS.
11595 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011596 if (checkPlaceholderForOverload(*this, Args[0]))
11597 return ExprError();
11598
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011599 // If this is the assignment operator, we only perform overload resolution
11600 // if the left-hand side is a class or enumeration type. This is actually
11601 // a hack. The standard requires that we do overload resolution between the
11602 // various built-in candidates, but as DR507 points out, this can lead to
11603 // problems. So we do it this way, which pretty much follows what GCC does.
11604 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011605 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011606 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011607
John McCalle26a8722010-12-04 08:14:53 +000011608 // If this is the .* operator, which is not overloadable, just
11609 // create a built-in binary operator.
11610 if (Opc == BO_PtrMemD)
11611 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11612
Douglas Gregor084d8552009-03-13 23:49:33 +000011613 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011614 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011615
11616 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011617 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011618
11619 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011620 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011621
Richard Smith0daabd72014-09-23 20:31:39 +000011622 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11623 // performed for an assignment operator (nor for operator[] nor operator->,
11624 // which don't get here).
11625 if (Opc != BO_Assign)
11626 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11627 /*ExplicitTemplateArgs*/ nullptr,
11628 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011629
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011630 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011631 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011632
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011633 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11634
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011635 // Perform overload resolution.
11636 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011637 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011638 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011639 // We found a built-in operator or an overloaded operator.
11640 FunctionDecl *FnDecl = Best->Function;
11641
11642 if (FnDecl) {
11643 // We matched an overloaded operator. Build a call to that
11644 // operator.
11645
11646 // Convert the arguments.
11647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011648 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011649 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011650
Chandler Carruth8e543b32010-12-12 08:17:55 +000011651 ExprResult Arg1 =
11652 PerformCopyInitialization(
11653 InitializedEntity::InitializeParameter(Context,
11654 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011655 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011656 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011657 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011658
John Wiegley01296292011-04-08 18:41:53 +000011659 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011660 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011661 Best->FoundDecl, Method);
11662 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011663 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011664 Args[0] = Arg0.getAs<Expr>();
11665 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011666 } else {
11667 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011668 ExprResult Arg0 = PerformCopyInitialization(
11669 InitializedEntity::InitializeParameter(Context,
11670 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011671 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011672 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011673 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011674
Chandler Carruth8e543b32010-12-12 08:17:55 +000011675 ExprResult Arg1 =
11676 PerformCopyInitialization(
11677 InitializedEntity::InitializeParameter(Context,
11678 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011679 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011680 if (Arg1.isInvalid())
11681 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011682 Args[0] = LHS = Arg0.getAs<Expr>();
11683 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011684 }
11685
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011686 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011687 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011688 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011689 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011690 if (FnExpr.isInvalid())
11691 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011692
Richard Smithc1564702013-11-15 02:58:23 +000011693 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011694 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011695 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11696 ResultTy = ResultTy.getNonLValueExprType(Context);
11697
John McCallb268a282010-08-23 23:25:46 +000011698 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011699 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011700 Args, ResultTy, VK, OpLoc,
11701 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011702
Alp Toker314cc812014-01-25 16:55:45 +000011703 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011704 FnDecl))
11705 return ExprError();
11706
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011707 ArrayRef<const Expr *> ArgsArray(Args, 2);
11708 // Cut off the implicit 'this'.
11709 if (isa<CXXMethodDecl>(FnDecl))
11710 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011711
11712 // Check for a self move.
11713 if (Op == OO_Equal)
11714 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11715
Douglas Gregorb4866e82015-06-19 18:13:19 +000011716 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011717 TheCall->getSourceRange(), VariadicDoesNotApply);
11718
John McCallb268a282010-08-23 23:25:46 +000011719 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011720 } else {
11721 // We matched a built-in operator. Convert the arguments, then
11722 // break out so that we will build the appropriate built-in
11723 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011724 ExprResult ArgsRes0 =
11725 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11726 Best->Conversions[0], AA_Passing);
11727 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011728 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011729 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011730
John Wiegley01296292011-04-08 18:41:53 +000011731 ExprResult ArgsRes1 =
11732 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11733 Best->Conversions[1], AA_Passing);
11734 if (ArgsRes1.isInvalid())
11735 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011736 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011737 break;
11738 }
11739 }
11740
Douglas Gregor66950a32009-09-30 21:46:01 +000011741 case OR_No_Viable_Function: {
11742 // C++ [over.match.oper]p9:
11743 // If the operator is the operator , [...] and there are no
11744 // viable functions, then the operator is assumed to be the
11745 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011746 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011747 break;
11748
Chandler Carruth8e543b32010-12-12 08:17:55 +000011749 // For class as left operand for assignment or compound assigment
11750 // operator do not fall through to handling in built-in, but report that
11751 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011752 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011753 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011754 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011755 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11756 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011757 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011758 if (Args[0]->getType()->isIncompleteType()) {
11759 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11760 << Args[0]->getType()
11761 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11762 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011763 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011764 // This is an erroneous use of an operator which can be overloaded by
11765 // a non-member function. Check for non-member operators which were
11766 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011767 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011768 // FIXME: Recover by calling the found function.
11769 return ExprError();
11770
Douglas Gregor66950a32009-09-30 21:46:01 +000011771 // No viable function; try to create a built-in operation, which will
11772 // produce an error. Then, show the non-viable candidates.
11773 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011775 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011776 "C++ binary operator overloading is missing candidates!");
11777 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011778 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011779 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011780 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011781 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011782
11783 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011784 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011785 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011786 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011787 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011788 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011789 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011790 return ExprError();
11791
11792 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011793 if (isImplicitlyDeleted(Best->Function)) {
11794 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11795 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011796 << Context.getRecordType(Method->getParent())
11797 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011798
Richard Smithde1a4872012-12-28 12:23:24 +000011799 // The user probably meant to call this special member. Just
11800 // explain why it's deleted.
11801 NoteDeletedFunction(Method);
11802 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011803 } else {
11804 Diag(OpLoc, diag::err_ovl_deleted_oper)
11805 << Best->Function->isDeleted()
11806 << BinaryOperator::getOpcodeStr(Opc)
11807 << getDeletedOrUnavailableSuffix(Best->Function)
11808 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11809 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011810 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011811 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011812 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011813 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011814
Douglas Gregor66950a32009-09-30 21:46:01 +000011815 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011816 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011817}
11818
John McCalldadc5752010-08-24 06:29:42 +000011819ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011820Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11821 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011822 Expr *Base, Expr *Idx) {
11823 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011824 DeclarationName OpName =
11825 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11826
11827 // If either side is type-dependent, create an appropriate dependent
11828 // expression.
11829 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11830
Craig Topperc3ec1492014-05-26 06:22:03 +000011831 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011832 // CHECKME: no 'operator' keyword?
11833 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11834 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011835 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011836 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011837 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011838 /*ADL*/ true, /*Overloaded*/ false,
11839 UnresolvedSetIterator(),
11840 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011841 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011842
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011843 return new (Context)
11844 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11845 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011846 }
11847
John McCall4124c492011-10-17 18:40:02 +000011848 // Handle placeholders on both operands.
11849 if (checkPlaceholderForOverload(*this, Args[0]))
11850 return ExprError();
11851 if (checkPlaceholderForOverload(*this, Args[1]))
11852 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011853
Sebastian Redladba46e2009-10-29 20:17:01 +000011854 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011855 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011856
11857 // Subscript can only be overloaded as a member function.
11858
11859 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011860 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011861
11862 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011863 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011864
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011865 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11866
Sebastian Redladba46e2009-10-29 20:17:01 +000011867 // Perform overload resolution.
11868 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011869 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011870 case OR_Success: {
11871 // We found a built-in operator or an overloaded operator.
11872 FunctionDecl *FnDecl = Best->Function;
11873
11874 if (FnDecl) {
11875 // We matched an overloaded operator. Build a call to that
11876 // operator.
11877
John McCalla0296f72010-03-19 07:35:19 +000011878 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011879
Sebastian Redladba46e2009-10-29 20:17:01 +000011880 // Convert the arguments.
11881 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011882 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011883 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011884 Best->FoundDecl, Method);
11885 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011886 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011887 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011888
Anders Carlssona68e51e2010-01-29 18:37:50 +000011889 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011890 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011891 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011892 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011893 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011894 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011895 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011896 if (InputInit.isInvalid())
11897 return ExprError();
11898
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011899 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011900
Sebastian Redladba46e2009-10-29 20:17:01 +000011901 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011902 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11903 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011904 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011905 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011906 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011907 OpLocInfo.getLoc(),
11908 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011909 if (FnExpr.isInvalid())
11910 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011911
Richard Smithc1564702013-11-15 02:58:23 +000011912 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011913 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011914 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11915 ResultTy = ResultTy.getNonLValueExprType(Context);
11916
John McCallb268a282010-08-23 23:25:46 +000011917 CXXOperatorCallExpr *TheCall =
11918 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011919 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011920 ResultTy, VK, RLoc,
11921 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011922
Alp Toker314cc812014-01-25 16:55:45 +000011923 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011924 return ExprError();
11925
John McCallb268a282010-08-23 23:25:46 +000011926 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011927 } else {
11928 // We matched a built-in operator. Convert the arguments, then
11929 // break out so that we will build the appropriate built-in
11930 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011931 ExprResult ArgsRes0 =
11932 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11933 Best->Conversions[0], AA_Passing);
11934 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011935 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011936 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011937
11938 ExprResult ArgsRes1 =
11939 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11940 Best->Conversions[1], AA_Passing);
11941 if (ArgsRes1.isInvalid())
11942 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011943 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011944
11945 break;
11946 }
11947 }
11948
11949 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011950 if (CandidateSet.empty())
11951 Diag(LLoc, diag::err_ovl_no_oper)
11952 << Args[0]->getType() << /*subscript*/ 0
11953 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11954 else
11955 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11956 << Args[0]->getType()
11957 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011959 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011960 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011961 }
11962
11963 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011964 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011965 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011966 << Args[0]->getType() << Args[1]->getType()
11967 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011968 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011969 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011970 return ExprError();
11971
11972 case OR_Deleted:
11973 Diag(LLoc, diag::err_ovl_deleted_oper)
11974 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011975 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011976 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011977 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011978 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011979 return ExprError();
11980 }
11981
11982 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011983 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011984}
11985
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011986/// BuildCallToMemberFunction - Build a call to a member
11987/// function. MemExpr is the expression that refers to the member
11988/// function (and includes the object parameter), Args/NumArgs are the
11989/// arguments to the function call (not including the object
11990/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011991/// expression refers to a non-static member function or an overloaded
11992/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011993ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011994Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011995 SourceLocation LParenLoc,
11996 MultiExprArg Args,
11997 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011998 assert(MemExprE->getType() == Context.BoundMemberTy ||
11999 MemExprE->getType() == Context.OverloadTy);
12000
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012001 // Dig out the member expression. This holds both the object
12002 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012003 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012004
John McCall0009fcc2011-04-26 20:42:42 +000012005 // Determine whether this is a call to a pointer-to-member function.
12006 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12007 assert(op->getType() == Context.BoundMemberTy);
12008 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12009
12010 QualType fnType =
12011 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12012
12013 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12014 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012015 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012016
12017 // Check that the object type isn't more qualified than the
12018 // member function we're calling.
12019 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12020
12021 QualType objectType = op->getLHS()->getType();
12022 if (op->getOpcode() == BO_PtrMemI)
12023 objectType = objectType->castAs<PointerType>()->getPointeeType();
12024 Qualifiers objectQuals = objectType.getQualifiers();
12025
12026 Qualifiers difference = objectQuals - funcQuals;
12027 difference.removeObjCGCAttr();
12028 difference.removeAddressSpace();
12029 if (difference) {
12030 std::string qualsString = difference.getAsString();
12031 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12032 << fnType.getUnqualifiedType()
12033 << qualsString
12034 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12035 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012036
John McCall0009fcc2011-04-26 20:42:42 +000012037 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012038 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012039 resultType, valueKind, RParenLoc);
12040
Alp Toker314cc812014-01-25 16:55:45 +000012041 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012042 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012043 return ExprError();
12044
Craig Topperc3ec1492014-05-26 06:22:03 +000012045 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012046 return ExprError();
12047
Richard Trieu9be9c682013-06-22 02:30:38 +000012048 if (CheckOtherCall(call, proto))
12049 return ExprError();
12050
John McCall0009fcc2011-04-26 20:42:42 +000012051 return MaybeBindToTemporary(call);
12052 }
12053
David Majnemerced8bdf2015-02-25 17:36:15 +000012054 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12055 return new (Context)
12056 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12057
John McCall4124c492011-10-17 18:40:02 +000012058 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012059 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012060 return ExprError();
12061
John McCall10eae182009-11-30 22:42:35 +000012062 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012063 CXXMethodDecl *Method = nullptr;
12064 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12065 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012066 if (isa<MemberExpr>(NakedMemExpr)) {
12067 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012068 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012069 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012070 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012071 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012072 } else {
12073 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012074 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012075
John McCall6e9f8f62009-12-03 04:06:58 +000012076 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012077 Expr::Classification ObjectClassification
12078 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12079 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012080
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012081 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012082 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12083 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012084
John McCall2d74de92009-12-01 22:10:20 +000012085 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012086 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012087 if (UnresExpr->hasExplicitTemplateArgs()) {
12088 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12089 TemplateArgs = &TemplateArgsBuffer;
12090 }
12091
John McCall10eae182009-11-30 22:42:35 +000012092 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12093 E = UnresExpr->decls_end(); I != E; ++I) {
12094
John McCall6e9f8f62009-12-03 04:06:58 +000012095 NamedDecl *Func = *I;
12096 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12097 if (isa<UsingShadowDecl>(Func))
12098 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12099
Douglas Gregor02824322011-01-26 19:30:28 +000012100
Francois Pichet64225792011-01-18 05:04:39 +000012101 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012102 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012103 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012104 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012105 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012106 // If explicit template arguments were provided, we can't call a
12107 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012108 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012109 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012110
John McCalla0296f72010-03-19 07:35:19 +000012111 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012112 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012113 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012114 } else {
John McCall10eae182009-11-30 22:42:35 +000012115 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012116 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012117 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012118 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012119 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012120 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012121 }
Mike Stump11289f42009-09-09 15:08:12 +000012122
John McCall10eae182009-11-30 22:42:35 +000012123 DeclarationName DeclName = UnresExpr->getMemberName();
12124
John McCall4124c492011-10-17 18:40:02 +000012125 UnbridgedCasts.restore();
12126
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012127 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012128 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012129 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012130 case OR_Success:
12131 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012132 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012133 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012134 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12135 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012136 // If FoundDecl is different from Method (such as if one is a template
12137 // and the other a specialization), make sure DiagnoseUseOfDecl is
12138 // called on both.
12139 // FIXME: This would be more comprehensively addressed by modifying
12140 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12141 // being used.
12142 if (Method != FoundDecl.getDecl() &&
12143 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12144 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012145 break;
12146
12147 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012148 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012149 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012150 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012151 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012152 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012153 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012154
12155 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012156 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012157 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012158 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012159 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012160 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012161
12162 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012163 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012164 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012165 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012166 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012167 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012168 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012169 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012170 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012171 }
12172
John McCall16df1e52010-03-30 21:47:33 +000012173 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012174
John McCall2d74de92009-12-01 22:10:20 +000012175 // If overload resolution picked a static member, build a
12176 // non-member call based on that function.
12177 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012178 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12179 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012180 }
12181
John McCall10eae182009-11-30 22:42:35 +000012182 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012183 }
12184
Alp Toker314cc812014-01-25 16:55:45 +000012185 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012186 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12187 ResultType = ResultType.getNonLValueExprType(Context);
12188
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012189 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012190 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012191 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012192 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012193
Eli Bendersky291a57e2014-09-25 23:59:08 +000012194 // (CUDA B.1): Check for invalid calls between targets.
12195 if (getLangOpts().CUDA) {
12196 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12197 if (CheckCUDATarget(Caller, Method)) {
12198 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12199 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12200 << IdentifyCUDATarget(Caller);
12201 return ExprError();
12202 }
12203 }
12204 }
12205
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012206 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012207 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012208 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012209 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012210
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012211 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012212 // We only need to do this if there was actually an overload; otherwise
12213 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012214 if (!Method->isStatic()) {
12215 ExprResult ObjectArg =
12216 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12217 FoundDecl, Method);
12218 if (ObjectArg.isInvalid())
12219 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012220 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012221 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012222
12223 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012224 const FunctionProtoType *Proto =
12225 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012226 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012227 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012228 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012229
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012230 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012231
Richard Smith55ce3522012-06-25 20:30:08 +000012232 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012233 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012234
George Burgess IVaea6ade2015-09-25 17:53:16 +000012235 // In the case the method to call was not selected by the overloading
12236 // resolution process, we still need to handle the enable_if attribute. Do
12237 // that here, so it will not hide previous -- and more relevant -- errors
12238 if (isa<MemberExpr>(NakedMemExpr)) {
12239 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12240 Diag(MemExprE->getLocStart(),
12241 diag::err_ovl_no_viable_member_function_in_call)
12242 << Method << Method->getSourceRange();
12243 Diag(Method->getLocation(),
12244 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12245 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12246 return ExprError();
12247 }
12248 }
12249
Anders Carlsson47061ee2011-05-06 14:25:31 +000012250 if ((isa<CXXConstructorDecl>(CurContext) ||
12251 isa<CXXDestructorDecl>(CurContext)) &&
12252 TheCall->getMethodDecl()->isPure()) {
12253 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12254
Davide Italianoccb37382015-07-14 23:36:10 +000012255 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12256 MemExpr->performsVirtualDispatch(getLangOpts())) {
12257 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012258 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12259 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12260 << MD->getParent()->getDeclName();
12261
12262 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012263 if (getLangOpts().AppleKext)
12264 Diag(MemExpr->getLocStart(),
12265 diag::note_pure_qualified_call_kext)
12266 << MD->getParent()->getDeclName()
12267 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012268 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012269 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012270
12271 if (CXXDestructorDecl *DD =
12272 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12273 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12274 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() ||
12275 getLangOpts().AppleKext;
12276 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12277 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12278 MemExpr->getMemberLoc());
12279 }
12280
John McCallb268a282010-08-23 23:25:46 +000012281 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012282}
12283
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012284/// BuildCallToObjectOfClassType - Build a call to an object of class
12285/// type (C++ [over.call.object]), which can end up invoking an
12286/// overloaded function call operator (@c operator()) or performing a
12287/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012288ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012289Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012290 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012291 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012292 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012293 if (checkPlaceholderForOverload(*this, Obj))
12294 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012295 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012296
12297 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012298 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012299 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012300
Nico Weberb58e51c2014-11-19 05:21:39 +000012301 assert(Object.get()->getType()->isRecordType() &&
12302 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012303 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012304
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012305 // C++ [over.call.object]p1:
12306 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012307 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012308 // candidate functions includes at least the function call
12309 // operators of T. The function call operators of T are obtained by
12310 // ordinary lookup of the name operator() in the context of
12311 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012312 OverloadCandidateSet CandidateSet(LParenLoc,
12313 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012314 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012315
John Wiegley01296292011-04-08 18:41:53 +000012316 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012317 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012318 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012319
John McCall27b18f82009-11-17 02:14:36 +000012320 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12321 LookupQualifiedName(R, Record->getDecl());
12322 R.suppressDiagnostics();
12323
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012324 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012325 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012326 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012327 Object.get()->Classify(Context),
12328 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012329 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012331
Douglas Gregorab7897a2008-11-19 22:57:39 +000012332 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012333 // In addition, for each (non-explicit in C++0x) conversion function
12334 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012335 //
12336 // operator conversion-type-id () cv-qualifier;
12337 //
12338 // where cv-qualifier is the same cv-qualification as, or a
12339 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012340 // denotes the type "pointer to function of (P1,...,Pn) returning
12341 // R", or the type "reference to pointer to function of
12342 // (P1,...,Pn) returning R", or the type "reference to function
12343 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012344 // is also considered as a candidate function. Similarly,
12345 // surrogate call functions are added to the set of candidate
12346 // functions for each conversion function declared in an
12347 // accessible base class provided the function is not hidden
12348 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012349 const auto &Conversions =
12350 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12351 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012352 NamedDecl *D = *I;
12353 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12354 if (isa<UsingShadowDecl>(D))
12355 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012356
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012357 // Skip over templated conversion functions; they aren't
12358 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012359 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012360 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012361
John McCall6e9f8f62009-12-03 04:06:58 +000012362 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012363 if (!Conv->isExplicit()) {
12364 // Strip the reference type (if any) and then the pointer type (if
12365 // any) to get down to what might be a function type.
12366 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12367 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12368 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012369
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012370 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12371 {
12372 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012373 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012374 }
12375 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012376 }
Mike Stump11289f42009-09-09 15:08:12 +000012377
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12379
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012380 // Perform overload resolution.
12381 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012382 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012383 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012384 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012385 // Overload resolution succeeded; we'll build the appropriate call
12386 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012387 break;
12388
12389 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012390 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012391 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012392 << Object.get()->getType() << /*call*/ 1
12393 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012394 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012395 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012396 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012397 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012398 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012399 break;
12400
12401 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012402 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012403 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012404 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012405 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012406 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012407
12408 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012409 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012410 diag::err_ovl_deleted_object_call)
12411 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012412 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012413 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012414 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012416 break;
Mike Stump11289f42009-09-09 15:08:12 +000012417 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012418
Douglas Gregorb412e172010-07-25 18:17:45 +000012419 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012420 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012421
John McCall4124c492011-10-17 18:40:02 +000012422 UnbridgedCasts.restore();
12423
Craig Topperc3ec1492014-05-26 06:22:03 +000012424 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012425 // Since there is no function declaration, this is one of the
12426 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012427 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012428 = cast<CXXConversionDecl>(
12429 Best->Conversions[0].UserDefined.ConversionFunction);
12430
Craig Topperc3ec1492014-05-26 06:22:03 +000012431 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12432 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012433 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12434 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012435 assert(Conv == Best->FoundDecl.getDecl() &&
12436 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012437 // We selected one of the surrogate functions that converts the
12438 // object parameter to a function pointer. Perform the conversion
12439 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012440
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012441 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012442 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012443 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12444 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012445 if (Call.isInvalid())
12446 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012447 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012448 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12449 CK_UserDefinedConversion, Call.get(),
12450 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012451
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012452 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012453 }
12454
Craig Topperc3ec1492014-05-26 06:22:03 +000012455 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012456
Douglas Gregorab7897a2008-11-19 22:57:39 +000012457 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12458 // that calls this method, using Object for the implicit object
12459 // parameter and passing along the remaining arguments.
12460 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012461
12462 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012463 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012464 return ExprError();
12465
Chandler Carruth8e543b32010-12-12 08:17:55 +000012466 const FunctionProtoType *Proto =
12467 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012468
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012469 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012470
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012471 DeclarationNameInfo OpLocInfo(
12472 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12473 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012474 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012475 HadMultipleCandidates,
12476 OpLocInfo.getLoc(),
12477 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012478 if (NewFn.isInvalid())
12479 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012480
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012481 // Build the full argument list for the method call (the implicit object
12482 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012483 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012484 MethodArgs[0] = Object.get();
12485 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12486
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012487 // Once we've built TheCall, all of the expressions are properly
12488 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012489 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012490 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12491 ResultTy = ResultTy.getNonLValueExprType(Context);
12492
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012493 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012494 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012495 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12496 ResultTy, VK, RParenLoc, false);
12497 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012498
Alp Toker314cc812014-01-25 16:55:45 +000012499 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012500 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012501
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012502 // We may have default arguments. If so, we need to allocate more
12503 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012504 if (Args.size() < NumParams)
12505 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012506
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012507 bool IsError = false;
12508
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012509 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012510 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012511 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012512 Best->FoundDecl, Method);
12513 if (ObjRes.isInvalid())
12514 IsError = true;
12515 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012516 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012517 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012518
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012519 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012520 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012521 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012522 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012523 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012524
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012525 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012526
John McCalldadc5752010-08-24 06:29:42 +000012527 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012528 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012529 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012530 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012531 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012532
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012533 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012534 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012535 } else {
John McCalldadc5752010-08-24 06:29:42 +000012536 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012537 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12538 if (DefArg.isInvalid()) {
12539 IsError = true;
12540 break;
12541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012542
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012543 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012544 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012545
12546 TheCall->setArg(i + 1, Arg);
12547 }
12548
12549 // If this is a variadic call, handle args passed through "...".
12550 if (Proto->isVariadic()) {
12551 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012552 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012553 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12554 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012555 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012556 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012557 }
12558 }
12559
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012560 if (IsError) return true;
12561
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012562 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012563
Richard Smith55ce3522012-06-25 20:30:08 +000012564 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012565 return true;
12566
John McCalle172be52010-08-24 06:09:16 +000012567 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012568}
12569
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012570/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012571/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012572/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012573ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012574Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12575 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012576 assert(Base->getType()->isRecordType() &&
12577 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012578
John McCall4124c492011-10-17 18:40:02 +000012579 if (checkPlaceholderForOverload(*this, Base))
12580 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012581
John McCallbc077cf2010-02-08 23:07:23 +000012582 SourceLocation Loc = Base->getExprLoc();
12583
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012584 // C++ [over.ref]p1:
12585 //
12586 // [...] An expression x->m is interpreted as (x.operator->())->m
12587 // for a class object x of type T if T::operator->() exists and if
12588 // the operator is selected as the best match function by the
12589 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012590 DeclarationName OpName =
12591 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012592 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012593 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012594
John McCallbc077cf2010-02-08 23:07:23 +000012595 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012596 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012597 return ExprError();
12598
John McCall27b18f82009-11-17 02:14:36 +000012599 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12600 LookupQualifiedName(R, BaseRecord->getDecl());
12601 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012602
12603 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012604 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012605 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012606 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012607 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012608
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012609 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12610
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012611 // Perform overload resolution.
12612 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012613 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012614 case OR_Success:
12615 // Overload resolution succeeded; we'll build the call below.
12616 break;
12617
12618 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012619 if (CandidateSet.empty()) {
12620 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012621 if (NoArrowOperatorFound) {
12622 // Report this specific error to the caller instead of emitting a
12623 // diagnostic, as requested.
12624 *NoArrowOperatorFound = true;
12625 return ExprError();
12626 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012627 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12628 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012629 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012630 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012631 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012632 }
12633 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012634 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012635 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012636 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012637 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012638
12639 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012640 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12641 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012642 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012643 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012644
12645 case OR_Deleted:
12646 Diag(OpLoc, diag::err_ovl_deleted_oper)
12647 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012648 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012649 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012650 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012652 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012653 }
12654
Craig Topperc3ec1492014-05-26 06:22:03 +000012655 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012656
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012657 // Convert the object parameter.
12658 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012659 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012660 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012661 Best->FoundDecl, Method);
12662 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012663 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012664 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012665
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012666 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012667 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012668 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012669 if (FnExpr.isInvalid())
12670 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012671
Alp Toker314cc812014-01-25 16:55:45 +000012672 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012673 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12674 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012675 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012676 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012677 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012678
Alp Toker314cc812014-01-25 16:55:45 +000012679 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012680 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012681
12682 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012683}
12684
Richard Smithbcc22fc2012-03-09 08:00:36 +000012685/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12686/// a literal operator described by the provided lookup results.
12687ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12688 DeclarationNameInfo &SuffixInfo,
12689 ArrayRef<Expr*> Args,
12690 SourceLocation LitEndLoc,
12691 TemplateArgumentListInfo *TemplateArgs) {
12692 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012693
Richard Smith100b24a2014-04-17 01:52:14 +000012694 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12695 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012696 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12697 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012698
Richard Smithbcc22fc2012-03-09 08:00:36 +000012699 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12700
Richard Smithbcc22fc2012-03-09 08:00:36 +000012701 // Perform overload resolution. This will usually be trivial, but might need
12702 // to perform substitutions for a literal operator template.
12703 OverloadCandidateSet::iterator Best;
12704 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12705 case OR_Success:
12706 case OR_Deleted:
12707 break;
12708
12709 case OR_No_Viable_Function:
12710 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12711 << R.getLookupName();
12712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12713 return ExprError();
12714
12715 case OR_Ambiguous:
12716 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12717 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12718 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012719 }
12720
Richard Smithbcc22fc2012-03-09 08:00:36 +000012721 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012722 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12723 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012724 SuffixInfo.getLoc(),
12725 SuffixInfo.getInfo());
12726 if (Fn.isInvalid())
12727 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012728
12729 // Check the argument types. This should almost always be a no-op, except
12730 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012731 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012732 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012733 ExprResult InputInit = PerformCopyInitialization(
12734 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12735 SourceLocation(), Args[ArgIdx]);
12736 if (InputInit.isInvalid())
12737 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012738 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012739 }
12740
Alp Toker314cc812014-01-25 16:55:45 +000012741 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012742 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12743 ResultTy = ResultTy.getNonLValueExprType(Context);
12744
Richard Smithc67fdd42012-03-07 08:35:16 +000012745 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012746 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012747 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012748 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12749
Alp Toker314cc812014-01-25 16:55:45 +000012750 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012751 return ExprError();
12752
Craig Topperc3ec1492014-05-26 06:22:03 +000012753 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012754 return ExprError();
12755
12756 return MaybeBindToTemporary(UDL);
12757}
12758
Sam Panzer0f384432012-08-21 00:52:01 +000012759/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12760/// given LookupResult is non-empty, it is assumed to describe a member which
12761/// will be invoked. Otherwise, the function will be found via argument
12762/// dependent lookup.
12763/// CallExpr is set to a valid expression and FRS_Success returned on success,
12764/// otherwise CallExpr is set to ExprError() and some non-success value
12765/// is returned.
12766Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012767Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12768 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012769 const DeclarationNameInfo &NameInfo,
12770 LookupResult &MemberLookup,
12771 OverloadCandidateSet *CandidateSet,
12772 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012773 Scope *S = nullptr;
12774
Sam Panzer0f384432012-08-21 00:52:01 +000012775 CandidateSet->clear();
12776 if (!MemberLookup.empty()) {
12777 ExprResult MemberRef =
12778 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12779 /*IsPtr=*/false, CXXScopeSpec(),
12780 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012781 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012782 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012783 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012784 if (MemberRef.isInvalid()) {
12785 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012786 return FRS_DiagnosticIssued;
12787 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012788 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012789 if (CallExpr->isInvalid()) {
12790 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012791 return FRS_DiagnosticIssued;
12792 }
12793 } else {
12794 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012795 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012796 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012797 NestedNameSpecifierLoc(), NameInfo,
12798 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012799 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012800
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012801 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012802 CandidateSet, CallExpr);
12803 if (CandidateSet->empty() || CandidateSetError) {
12804 *CallExpr = ExprError();
12805 return FRS_NoViableFunction;
12806 }
12807 OverloadCandidateSet::iterator Best;
12808 OverloadingResult OverloadResult =
12809 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12810
12811 if (OverloadResult == OR_No_Viable_Function) {
12812 *CallExpr = ExprError();
12813 return FRS_NoViableFunction;
12814 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012815 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012816 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012817 OverloadResult,
12818 /*AllowTypoCorrection=*/false);
12819 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12820 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012821 return FRS_DiagnosticIssued;
12822 }
12823 }
12824 return FRS_Success;
12825}
12826
12827
Douglas Gregorcd695e52008-11-10 20:40:00 +000012828/// FixOverloadedFunctionReference - E is an expression that refers to
12829/// a C++ overloaded function (possibly with some parentheses and
12830/// perhaps a '&' around it). We have resolved the overloaded function
12831/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012832/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012833Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012834 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012835 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012836 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12837 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012838 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012839 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012840
Douglas Gregor51c538b2009-11-20 19:42:02 +000012841 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012842 }
12843
Douglas Gregor51c538b2009-11-20 19:42:02 +000012844 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012845 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12846 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012847 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012848 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012849 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012850 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012851 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012852 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012853
12854 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012855 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012856 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012857 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012858 }
12859
Douglas Gregor51c538b2009-11-20 19:42:02 +000012860 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012861 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012862 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12864 if (Method->isStatic()) {
12865 // Do nothing: static member functions aren't any different
12866 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012867 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012868 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012869 // UnresolvedLookupExpr holding an overloaded member function
12870 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012871 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12872 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012873 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012874 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012875
John McCalld14a8642009-11-21 08:51:07 +000012876 assert(isa<DeclRefExpr>(SubExpr)
12877 && "fixed to something other than a decl ref");
12878 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12879 && "fixed to a member ref with no nested name qualifier");
12880
12881 // We have taken the address of a pointer to member
12882 // function. Perform the computation here so that we get the
12883 // appropriate pointer to member type.
12884 QualType ClassType
12885 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12886 QualType MemPtrType
12887 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12888
John McCall7decc9e2010-11-18 06:31:45 +000012889 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12890 VK_RValue, OK_Ordinary,
12891 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012892 }
12893 }
John McCall16df1e52010-03-30 21:47:33 +000012894 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12895 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012896 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012897 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012898
John McCalle3027922010-08-25 11:45:40 +000012899 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012900 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012901 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012902 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012903 }
John McCalld14a8642009-11-21 08:51:07 +000012904
12905 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012906 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012907 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012908 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012909 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12910 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012911 }
12912
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012913 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12914 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012915 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012916 Fn,
John McCall113bee02012-03-10 09:33:50 +000012917 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012918 ULE->getNameLoc(),
12919 Fn->getType(),
12920 VK_LValue,
12921 Found.getDecl(),
12922 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012923 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012924 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12925 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012926 }
12927
John McCall10eae182009-11-30 22:42:35 +000012928 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012929 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012930 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012931 if (MemExpr->hasExplicitTemplateArgs()) {
12932 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12933 TemplateArgs = &TemplateArgsBuffer;
12934 }
John McCall6b51f282009-11-23 01:53:49 +000012935
John McCall2d74de92009-12-01 22:10:20 +000012936 Expr *Base;
12937
John McCall7decc9e2010-11-18 06:31:45 +000012938 // If we're filling in a static method where we used to have an
12939 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012940 if (MemExpr->isImplicitAccess()) {
12941 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012942 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12943 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012944 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012945 Fn,
John McCall113bee02012-03-10 09:33:50 +000012946 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012947 MemExpr->getMemberLoc(),
12948 Fn->getType(),
12949 VK_LValue,
12950 Found.getDecl(),
12951 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012952 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012953 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12954 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012955 } else {
12956 SourceLocation Loc = MemExpr->getMemberLoc();
12957 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012958 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012959 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012960 Base = new (Context) CXXThisExpr(Loc,
12961 MemExpr->getBaseType(),
12962 /*isImplicit=*/true);
12963 }
John McCall2d74de92009-12-01 22:10:20 +000012964 } else
John McCallc3007a22010-10-26 07:05:15 +000012965 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012966
John McCall4adb38c2011-04-27 00:36:17 +000012967 ExprValueKind valueKind;
12968 QualType type;
12969 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12970 valueKind = VK_LValue;
12971 type = Fn->getType();
12972 } else {
12973 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012974 type = Context.BoundMemberTy;
12975 }
12976
12977 MemberExpr *ME = MemberExpr::Create(
12978 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12979 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12980 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12981 OK_Ordinary);
12982 ME->setHadMultipleCandidates(true);
12983 MarkMemberReferenced(ME);
12984 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012986
John McCallc3007a22010-10-26 07:05:15 +000012987 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012988}
12989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012990ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012991 DeclAccessPair Found,
12992 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012993 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012994}