blob: 645dbed21ba04923cfa6fcd0031ad4fe5511974d [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
92CompareStandardConversionSequences(Sema &S,
93 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
102CompareDerivedToBaseConversions(Sema &S,
103 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:
261 case CK_FloatingToIntegral:
262 case CK_FloatingToBoolean:
263 case CK_FloatingCast:
264 Converted = ICE->getSubExpr();
265 continue;
266
267 default:
268 return Converted;
269 }
270 }
271
272 return Converted;
273}
274
275/// Check if this standard conversion sequence represents a narrowing
276/// conversion, according to C++11 [dcl.init.list]p7.
277///
278/// \param Ctx The AST context.
279/// \param Converted The result of applying this standard conversion sequence.
280/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
281/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000282/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
283/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000284NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000285StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
286 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000287 APValue &ConstantValue,
288 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000289 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000290
291 // C++11 [dcl.init.list]p7:
292 // A narrowing conversion is an implicit conversion ...
293 QualType FromType = getToType(0);
294 QualType ToType = getToType(1);
295 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000296 // 'bool' is an integral type; dispatch to the right place to handle it.
297 case ICK_Boolean_Conversion:
298 if (FromType->isRealFloatingType())
299 goto FloatingIntegralConversion;
300 if (FromType->isIntegralOrUnscopedEnumerationType())
301 goto IntegralConversion;
302 // Boolean conversions can be from pointers and pointers to members
303 // [conv.bool], and those aren't considered narrowing conversions.
304 return NK_Not_Narrowing;
305
Richard Smith66e05fe2012-01-18 05:21:49 +0000306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000313 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000366 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000378 case ICK_Integral_Conversion:
379 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 assert(FromType->isIntegralOrUnscopedEnumerationType());
381 assert(ToType->isIntegralOrUnscopedEnumerationType());
382 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
383 const unsigned FromWidth = Ctx.getIntWidth(FromType);
384 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
385 const unsigned ToWidth = Ctx.getIntWidth(ToType);
386
387 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000388 (FromWidth == ToWidth && FromSigned != ToSigned) ||
389 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 // Not all values of FromType can be represented in ToType.
391 llvm::APSInt InitializerValue;
392 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000393 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
394 // Such conversions on variables are always narrowing.
395 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000396 }
397 bool Narrowing = false;
398 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000399 // Negative -> unsigned is narrowing. Otherwise, more bits is never
400 // narrowing.
401 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000402 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000403 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 // Add a bit to the InitializerValue so we don't have to worry about
405 // signed vs. unsigned comparisons.
406 InitializerValue = InitializerValue.extend(
407 InitializerValue.getBitWidth() + 1);
408 // Convert the initializer to and from the target width and signed-ness.
409 llvm::APSInt ConvertedValue = InitializerValue;
410 ConvertedValue = ConvertedValue.trunc(ToWidth);
411 ConvertedValue.setIsSigned(ToSigned);
412 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
413 ConvertedValue.setIsSigned(InitializerValue.isSigned());
414 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000415 if (ConvertedValue != InitializerValue)
416 Narrowing = true;
417 }
418 if (Narrowing) {
419 ConstantType = Initializer->getType();
420 ConstantValue = APValue(InitializerValue);
421 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000422 }
423 }
424 return NK_Not_Narrowing;
425 }
426
427 default:
428 // Other kinds of conversions are not narrowings.
429 return NK_Not_Narrowing;
430 }
431}
432
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000433/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000434/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000435void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000436 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000437 bool PrintedSomething = false;
438 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000440 PrintedSomething = true;
441 }
442
443 if (Second != ICK_Identity) {
444 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000446 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448
449 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000451 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000453 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000455 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 PrintedSomething = true;
457 }
458
459 if (Third != ICK_Identity) {
460 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000464 PrintedSomething = true;
465 }
466
467 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 }
470}
471
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000472/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000474void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000475 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000477 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000480 if (ConversionFunction)
481 OS << '\'' << *ConversionFunction << '\'';
482 else
483 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000486 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 }
488}
489
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000494 if (isStdInitializerListElement())
495 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 switch (ConversionKind) {
497 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000499 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
501 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 break;
505 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 break;
John McCall0d1da222010-01-12 00:44:57 +0000508 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000510 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000512 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 break;
514 }
515
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000516 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517}
518
John McCall0d1da222010-01-12 00:44:57 +0000519void AmbiguousConversionSequence::construct() {
520 new (&conversions()) ConversionSet();
521}
522
523void AmbiguousConversionSequence::destruct() {
524 conversions().~ConversionSet();
525}
526
527void
528AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
529 FromTypePtr = O.FromTypePtr;
530 ToTypePtr = O.ToTypePtr;
531 new (&conversions()) ConversionSet(O.conversions());
532}
533
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000535 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000536 // template argument information.
537 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000538 TemplateArgument FirstArg;
539 TemplateArgument SecondArg;
540 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000541 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000542 // template parameter and template argument information.
543 struct DFIParamWithArguments : DFIArguments {
544 TemplateParameter Param;
545 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000546}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548/// \brief Convert from Sema's representation of template deduction information
549/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000550DeductionFailureInfo
551clang::MakeDeductionFailureInfo(ASTContext &Context,
552 Sema::TemplateDeductionResult TDK,
553 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000554 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000556 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000557 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 switch (TDK) {
559 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000560 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000562 case Sema::TDK_TooManyArguments:
563 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000567 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568 Result.Data = Info.Param.getOpaqueValue();
569 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Richard Smith44ecdbd2013-01-31 05:19:49 +0000571 case Sema::TDK_NonDeducedMismatch: {
572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIArguments *Saved = new (Context) DFIArguments;
574 Saved->FirstArg = Info.FirstArg;
575 Saved->SecondArg = Info.SecondArg;
576 Result.Data = Saved;
577 break;
578 }
579
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000581 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000582 // FIXME: Should allocate from normal heap so that we can free this later.
583 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 Saved->Param = Info.Param;
585 Saved->FirstArg = Info.FirstArg;
586 Saved->SecondArg = Info.SecondArg;
587 Result.Data = Saved;
588 break;
589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000592 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000593 if (Info.hasSFINAEDiagnostic()) {
594 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
595 SourceLocation(), PartialDiagnostic::NullDiagnostic());
596 Info.takeSFINAEDiagnostic(*Diag);
597 Result.HasDiagnostic = true;
598 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000599 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000601 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000602 Result.Data = Info.Expression;
603 break;
604
Richard Smith44ecdbd2013-01-31 05:19:49 +0000605 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 return Result;
610}
John McCall0d1da222010-01-12 00:44:57 +0000611
Larisse Voufo98b20f12013-07-19 23:00:19 +0000612void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
614 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000615 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 case Sema::TDK_InstantiationDepth:
617 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000618 case Sema::TDK_TooManyArguments:
619 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000620 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000621 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000624 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000625 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000627 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000628 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000630
631 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000632 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000633 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000634 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
635 Diag->~PartialDiagnosticAt();
636 HasDiagnostic = false;
637 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000638 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor461761d2010-05-08 18:20:53 +0000640 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000641 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 break;
643 }
644}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
Larisse Voufo98b20f12013-07-19 23:00:19 +0000646PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000647 if (HasDiagnostic)
648 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000650}
651
Larisse Voufo98b20f12013-07-19 23:00:19 +0000652TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000655 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000659 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_NonDeducedMismatch:
661 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000662 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000665 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667
668 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000669 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000671
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000673 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000674 break;
675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000676
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 return TemplateParameter();
678}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000679
Larisse Voufo98b20f12013-07-19 23:00:19 +0000680TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000681 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000682 case Sema::TDK_Success:
683 case Sema::TDK_Invalid:
684 case Sema::TDK_InstantiationDepth:
685 case Sema::TDK_TooManyArguments:
686 case Sema::TDK_TooFewArguments:
687 case Sema::TDK_Incomplete:
688 case Sema::TDK_InvalidExplicitArguments:
689 case Sema::TDK_Inconsistent:
690 case Sema::TDK_Underqualified:
691 case Sema::TDK_NonDeducedMismatch:
692 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000693 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000694
Richard Smith44ecdbd2013-01-31 05:19:49 +0000695 case Sema::TDK_SubstitutionFailure:
696 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000697
Richard Smith44ecdbd2013-01-31 05:19:49 +0000698 // Unhandled
699 case Sema::TDK_MiscellaneousDeductionFailure:
700 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000701 }
702
Craig Topperc3ec1492014-05-26 06:22:03 +0000703 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000704}
705
Larisse Voufo98b20f12013-07-19 23:00:19 +0000706const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
708 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000709 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 case Sema::TDK_InstantiationDepth:
711 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000714 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000715 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000716 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000717 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000720 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000721 case Sema::TDK_NonDeducedMismatch:
722 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723
Douglas Gregor461761d2010-05-08 18:20:53 +0000724 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000725 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 break;
727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Craig Topperc3ec1492014-05-26 06:22:03 +0000729 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731
Larisse Voufo98b20f12013-07-19 23:00:19 +0000732const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
734 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000735 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 case Sema::TDK_InstantiationDepth:
737 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000738 case Sema::TDK_TooManyArguments:
739 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000740 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000741 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000742 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000743 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000744
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000746 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_NonDeducedMismatch:
748 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749
Douglas Gregor461761d2010-05-08 18:20:53 +0000750 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000751 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 break;
753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756}
757
Larisse Voufo98b20f12013-07-19 23:00:19 +0000758Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000759 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
760 Sema::TDK_FailedOverloadResolution)
761 return static_cast<Expr*>(Data);
762
Craig Topperc3ec1492014-05-26 06:22:03 +0000763 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000764}
765
Benjamin Kramer97e59492012-10-09 15:52:25 +0000766void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000767 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000768 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
769 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000770 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
771 i->DeductionFailure.Destroy();
772 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000773}
774
775void OverloadCandidateSet::clear() {
776 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000777 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000778 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000779 Functions.clear();
780}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781
John McCall4124c492011-10-17 18:40:02 +0000782namespace {
783 class UnbridgedCastsSet {
784 struct Entry {
785 Expr **Addr;
786 Expr *Saved;
787 };
788 SmallVector<Entry, 2> Entries;
789
790 public:
791 void save(Sema &S, Expr *&E) {
792 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
793 Entry entry = { &E, E };
794 Entries.push_back(entry);
795 E = S.stripARCUnbridgedCast(E);
796 }
797
798 void restore() {
799 for (SmallVectorImpl<Entry>::iterator
800 i = Entries.begin(), e = Entries.end(); i != e; ++i)
801 *i->Addr = i->Saved;
802 }
803 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000804}
John McCall4124c492011-10-17 18:40:02 +0000805
806/// checkPlaceholderForOverload - Do any interesting placeholder-like
807/// preprocessing on the given expression.
808///
809/// \param unbridgedCasts a collection to which to add unbridged casts;
810/// without this, they will be immediately diagnosed as errors
811///
812/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000813static bool
814checkPlaceholderForOverload(Sema &S, Expr *&E,
815 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000816 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
817 // We can't handle overloaded expressions here because overload
818 // resolution might reasonably tweak them.
819 if (placeholder->getKind() == BuiltinType::Overload) return false;
820
821 // If the context potentially accepts unbridged ARC casts, strip
822 // the unbridged cast and add it to the collection for later restoration.
823 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
824 unbridgedCasts) {
825 unbridgedCasts->save(S, E);
826 return false;
827 }
828
829 // Go ahead and check everything else.
830 ExprResult result = S.CheckPlaceholderExpr(E);
831 if (result.isInvalid())
832 return true;
833
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000834 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000835 return false;
836 }
837
838 // Nothing to do.
839 return false;
840}
841
842/// checkArgPlaceholdersForOverload - Check a set of call operands for
843/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000844static bool checkArgPlaceholdersForOverload(Sema &S,
845 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000846 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000847 for (unsigned i = 0, e = Args.size(); i != e; ++i)
848 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000849 return true;
850
851 return false;
852}
853
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000855// overload of the declarations in Old. This routine returns false if
856// New and Old cannot be overloaded, e.g., if New has the same
857// signature as some function in Old (C++ 1.3.10) or if the Old
858// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000859// it does return false, MatchedDecl will point to the decl that New
860// cannot be overloaded with. This decl may be a UsingShadowDecl on
861// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862//
863// Example: Given the following input:
864//
865// void f(int, float); // #1
866// void f(int, int); // #2
867// int f(int, int); // #3
868//
869// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000870// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000871//
John McCall3d988d92009-12-02 08:47:38 +0000872// When we process #2, Old contains only the FunctionDecl for #1. By
873// comparing the parameter types, we see that #1 and #2 are overloaded
874// (since they have different signatures), so this routine returns
875// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000876//
John McCall3d988d92009-12-02 08:47:38 +0000877// When we process #3, Old is an overload set containing #1 and #2. We
878// compare the signatures of #3 to #1 (they're overloaded, so we do
879// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
880// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881// signature), IsOverload returns false and MatchedDecl will be set to
882// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000883//
884// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
885// into a class by a using declaration. The rules for whether to hide
886// shadow declarations ignore some properties which otherwise figure
887// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000888Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000889Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
890 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000891 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000892 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000893 NamedDecl *OldD = *I;
894
895 bool OldIsUsingDecl = false;
896 if (isa<UsingShadowDecl>(OldD)) {
897 OldIsUsingDecl = true;
898
899 // We can always introduce two using declarations into the same
900 // context, even if they have identical signatures.
901 if (NewIsUsingDecl) continue;
902
903 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
904 }
905
Richard Smithf091e122015-09-15 01:28:55 +0000906 // A using-declaration does not conflict with another declaration
907 // if one of them is hidden.
908 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
909 continue;
910
John McCalle9cccd82010-06-16 08:42:20 +0000911 // If either declaration was introduced by a using declaration,
912 // we'll need to use slightly different rules for matching.
913 // Essentially, these rules are the normal rules, except that
914 // function templates hide function templates with different
915 // return types or template parameter lists.
916 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000917 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
918 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000919
Alp Tokera2794f92014-01-22 07:29:52 +0000920 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000921 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
922 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
923 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
924 continue;
925 }
926
Alp Tokera2794f92014-01-22 07:29:52 +0000927 if (!isa<FunctionTemplateDecl>(OldD) &&
928 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000929 continue;
930
John McCalldaa3d6b2009-12-09 03:35:25 +0000931 Match = *I;
932 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000933 }
John McCalla8987a2942010-11-10 03:01:53 +0000934 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000935 // We can overload with these, which can show up when doing
936 // redeclaration checks for UsingDecls.
937 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000938 } else if (isa<TagDecl>(OldD)) {
939 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000940 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
941 // Optimistically assume that an unresolved using decl will
942 // overload; if it doesn't, we'll have to diagnose during
943 // template instantiation.
944 } else {
John McCall1f82f242009-11-18 22:49:29 +0000945 // (C++ 13p1):
946 // Only function declarations can be overloaded; object and type
947 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000948 Match = *I;
949 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000950 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 }
John McCall1f82f242009-11-18 22:49:29 +0000952
John McCalldaa3d6b2009-12-09 03:35:25 +0000953 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000954}
955
Richard Smithac974a32013-06-30 09:48:50 +0000956bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
957 bool UseUsingDeclRules) {
958 // C++ [basic.start.main]p2: This function shall not be overloaded.
959 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000960 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000961
David Majnemerc729b0b2013-09-16 22:44:20 +0000962 // MSVCRT user defined entry points cannot be overloaded.
963 if (New->isMSVCRTEntryPoint())
964 return false;
965
John McCall1f82f242009-11-18 22:49:29 +0000966 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
967 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
968
969 // C++ [temp.fct]p2:
970 // A function template can be overloaded with other function templates
971 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000972 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000973 return true;
974
975 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000976 QualType OldQType = Context.getCanonicalType(Old->getType());
977 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000978
979 // Compare the signatures (C++ 1.3.10) of the two functions to
980 // determine whether they are overloads. If we find any mismatch
981 // in the signature, they are overloads.
982
983 // If either of these functions is a K&R-style function (no
984 // prototype), then we consider them to have matching signatures.
985 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
986 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
987 return false;
988
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000989 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
990 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000991
992 // The signature of a function includes the types of its
993 // parameters (C++ 1.3.10), which includes the presence or absence
994 // of the ellipsis; see C++ DR 357).
995 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000997 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000998 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000999 return true;
1000
1001 // C++ [temp.over.link]p4:
1002 // The signature of a function template consists of its function
1003 // signature, its return type and its template parameter list. The names
1004 // of the template parameters are significant only for establishing the
1005 // relationship between the template parameters and the rest of the
1006 // signature.
1007 //
1008 // We check the return type and template parameter lists for function
1009 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001010 //
1011 // However, we don't consider either of these when deciding whether
1012 // a member introduced by a shadow declaration is hidden.
1013 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001014 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1015 OldTemplate->getTemplateParameters(),
1016 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001017 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001018 return true;
1019
1020 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001021 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001022 //
1023 // As part of this, also check whether one of the member functions
1024 // is static, in which case they are not overloads (C++
1025 // 13.1p2). While not part of the definition of the signature,
1026 // this check is important to determine whether these functions
1027 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001028 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1029 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001030 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001031 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1032 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1033 if (!UseUsingDeclRules &&
1034 (OldMethod->getRefQualifier() == RQ_None ||
1035 NewMethod->getRefQualifier() == RQ_None)) {
1036 // C++0x [over.load]p2:
1037 // - Member function declarations with the same name and the same
1038 // parameter-type-list as well as member function template
1039 // declarations with the same name, the same parameter-type-list, and
1040 // the same template parameter lists cannot be overloaded if any of
1041 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001042 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001043 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001044 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001045 }
1046 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Richard Smith574f4f62013-01-14 05:37:29 +00001049 // We may not have applied the implicit const for a constexpr member
1050 // function yet (because we haven't yet resolved whether this is a static
1051 // or non-static member function). Add it now, on the assumption that this
1052 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001053 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001054 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001055 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001056 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001057 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001058
1059 // We do not allow overloading based off of '__restrict'.
1060 OldQuals &= ~Qualifiers::Restrict;
1061 NewQuals &= ~Qualifiers::Restrict;
1062 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001063 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001066 // Though pass_object_size is placed on parameters and takes an argument, we
1067 // consider it to be a function-level modifier for the sake of function
1068 // identity. Either the function has one or more parameters with
1069 // pass_object_size or it doesn't.
1070 if (functionHasPassObjectSizeParams(New) !=
1071 functionHasPassObjectSizeParams(Old))
1072 return true;
1073
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001074 // enable_if attributes are an order-sensitive part of the signature.
1075 for (specific_attr_iterator<EnableIfAttr>
1076 NewI = New->specific_attr_begin<EnableIfAttr>(),
1077 NewE = New->specific_attr_end<EnableIfAttr>(),
1078 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1079 OldE = Old->specific_attr_end<EnableIfAttr>();
1080 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1081 if (NewI == NewE || OldI == OldE)
1082 return true;
1083 llvm::FoldingSetNodeID NewID, OldID;
1084 NewI->getCond()->Profile(NewID, Context, true);
1085 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001086 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001087 return true;
1088 }
1089
Artem Belevich94a55e82015-09-22 17:22:59 +00001090 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1091 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1092 OldTarget = IdentifyCUDATarget(Old);
1093 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1094 return false;
1095
1096 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1097
1098 // Don't allow mixing of HD with other kinds. This guarantees that
1099 // we have only one viable function with this signature on any
1100 // side of CUDA compilation .
1101 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1102 return false;
1103
1104 // Allow overloading of functions with same signature, but
1105 // different CUDA target attributes.
1106 return NewTarget != OldTarget;
1107 }
1108
John McCall1f82f242009-11-18 22:49:29 +00001109 // The signatures match; this is not an overload.
1110 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111}
1112
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001113/// \brief Checks availability of the function depending on the current
1114/// function context. Inside an unavailable function, unavailability is ignored.
1115///
1116/// \returns true if \arg FD is unavailable and current context is inside
1117/// an available function, false otherwise.
1118bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1119 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1120}
1121
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001122/// \brief Tries a user-defined conversion from From to ToType.
1123///
1124/// Produces an implicit conversion sequence for when a standard conversion
1125/// is not an option. See TryImplicitConversion for more information.
1126static ImplicitConversionSequence
1127TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1128 bool SuppressUserConversions,
1129 bool AllowExplicit,
1130 bool InOverloadResolution,
1131 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001132 bool AllowObjCWritebackConversion,
1133 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134 ImplicitConversionSequence ICS;
1135
1136 if (SuppressUserConversions) {
1137 // We're not in the case above, so there is no conversion that
1138 // we can perform.
1139 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1140 return ICS;
1141 }
1142
1143 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001144 OverloadCandidateSet Conversions(From->getExprLoc(),
1145 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001146 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1147 Conversions, AllowExplicit,
1148 AllowObjCConversionOnExplicit)) {
1149 case OR_Success:
1150 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001151 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001152 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001153 // C++ [over.ics.user]p4:
1154 // A conversion of an expression of class type to the same class
1155 // type is given Exact Match rank, and a conversion of an
1156 // expression of class type to a base class of that type is
1157 // given Conversion rank, in spite of the fact that a copy
1158 // constructor (i.e., a user-defined conversion function) is
1159 // called for those cases.
1160 if (CXXConstructorDecl *Constructor
1161 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1162 QualType FromCanon
1163 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1164 QualType ToCanon
1165 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1166 if (Constructor->isCopyConstructor() &&
1167 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1168 // Turn this into a "standard" conversion sequence, so that it
1169 // gets ranked with standard conversion sequences.
1170 ICS.setStandard();
1171 ICS.Standard.setAsIdentityConversion();
1172 ICS.Standard.setFromType(From->getType());
1173 ICS.Standard.setAllToTypes(ToType);
1174 ICS.Standard.CopyConstructor = Constructor;
1175 if (ToCanon != FromCanon)
1176 ICS.Standard.Second = ICK_Derived_To_Base;
1177 }
1178 }
Richard Smith48372b62015-01-27 03:30:40 +00001179 break;
1180
1181 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001182 ICS.setAmbiguous();
1183 ICS.Ambiguous.setFromType(From->getType());
1184 ICS.Ambiguous.setToType(ToType);
1185 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1186 Cand != Conversions.end(); ++Cand)
1187 if (Cand->Viable)
1188 ICS.Ambiguous.addConversion(Cand->Function);
1189 break;
Richard Smith48372b62015-01-27 03:30:40 +00001190
1191 // Fall through.
1192 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001193 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001194 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001195 }
1196
1197 return ICS;
1198}
1199
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001200/// TryImplicitConversion - Attempt to perform an implicit conversion
1201/// from the given expression (Expr) to the given type (ToType). This
1202/// function returns an implicit conversion sequence that can be used
1203/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204///
1205/// void f(float f);
1206/// void g(int i) { f(i); }
1207///
1208/// this routine would produce an implicit conversion sequence to
1209/// describe the initialization of f from i, which will be a standard
1210/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1211/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1212//
1213/// Note that this routine only determines how the conversion can be
1214/// performed; it does not actually perform the conversion. As such,
1215/// it will not produce any diagnostics if no conversion is available,
1216/// but will instead return an implicit conversion sequence of kind
1217/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001218///
1219/// If @p SuppressUserConversions, then user-defined conversions are
1220/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001221/// If @p AllowExplicit, then explicit user-defined conversions are
1222/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001223///
1224/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1225/// writeback conversion, which allows __autoreleasing id* parameters to
1226/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001227static ImplicitConversionSequence
1228TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1229 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001231 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001232 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001233 bool AllowObjCWritebackConversion,
1234 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001236 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001237 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001238 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001239 return ICS;
1240 }
1241
David Blaikiebbafb8a2012-03-11 07:00:24 +00001242 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001243 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001244 return ICS;
1245 }
1246
Douglas Gregor836a7e82010-08-11 02:15:33 +00001247 // C++ [over.ics.user]p4:
1248 // A conversion of an expression of class type to the same class
1249 // type is given Exact Match rank, and a conversion of an
1250 // expression of class type to a base class of that type is
1251 // given Conversion rank, in spite of the fact that a copy/move
1252 // constructor (i.e., a user-defined conversion function) is
1253 // called for those cases.
1254 QualType FromType = From->getType();
1255 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001256 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1257 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001258 ICS.setStandard();
1259 ICS.Standard.setAsIdentityConversion();
1260 ICS.Standard.setFromType(FromType);
1261 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262
Douglas Gregor5ab11652010-04-17 22:01:05 +00001263 // We don't actually check at this point whether there is a valid
1264 // copy/move constructor, since overloading just assumes that it
1265 // exists. When we actually perform initialization, we'll find the
1266 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001267 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268
Douglas Gregor5ab11652010-04-17 22:01:05 +00001269 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001270 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001271 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001272
Douglas Gregor836a7e82010-08-11 02:15:33 +00001273 return ICS;
1274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001276 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1277 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001278 AllowObjCWritebackConversion,
1279 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001280}
1281
John McCall31168b02011-06-15 23:02:42 +00001282ImplicitConversionSequence
1283Sema::TryImplicitConversion(Expr *From, QualType ToType,
1284 bool SuppressUserConversions,
1285 bool AllowExplicit,
1286 bool InOverloadResolution,
1287 bool CStyle,
1288 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001289 return ::TryImplicitConversion(*this, From, ToType,
1290 SuppressUserConversions, AllowExplicit,
1291 InOverloadResolution, CStyle,
1292 AllowObjCWritebackConversion,
1293 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001294}
1295
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001296/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001297/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001298/// converted expression. Flavor is the kind of conversion we're
1299/// performing, used in the error message. If @p AllowExplicit,
1300/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001301ExprResult
1302Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001303 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001304 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001305 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001306}
1307
John Wiegley01296292011-04-08 18:41:53 +00001308ExprResult
1309Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001310 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001311 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001312 if (checkPlaceholderForOverload(*this, From))
1313 return ExprError();
1314
John McCall31168b02011-06-15 23:02:42 +00001315 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1316 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001317 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001318 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001319 if (getLangOpts().ObjC1)
1320 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1321 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001322 ICS = ::TryImplicitConversion(*this, From, ToType,
1323 /*SuppressUserConversions=*/false,
1324 AllowExplicit,
1325 /*InOverloadResolution=*/false,
1326 /*CStyle=*/false,
1327 AllowObjCWritebackConversion,
1328 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001329 return PerformImplicitConversion(From, ToType, ICS, Action);
1330}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331
1332/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001333/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001334bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1335 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001336 if (Context.hasSameUnqualifiedType(FromType, ToType))
1337 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338
John McCall991eb4b2010-12-21 00:44:39 +00001339 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1340 // where F adds one of the following at most once:
1341 // - a pointer
1342 // - a member pointer
1343 // - a block pointer
1344 CanQualType CanTo = Context.getCanonicalType(ToType);
1345 CanQualType CanFrom = Context.getCanonicalType(FromType);
1346 Type::TypeClass TyClass = CanTo->getTypeClass();
1347 if (TyClass != CanFrom->getTypeClass()) return false;
1348 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1349 if (TyClass == Type::Pointer) {
1350 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1351 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1352 } else if (TyClass == Type::BlockPointer) {
1353 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1354 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1355 } else if (TyClass == Type::MemberPointer) {
1356 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1357 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1358 } else {
1359 return false;
1360 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001361
John McCall991eb4b2010-12-21 00:44:39 +00001362 TyClass = CanTo->getTypeClass();
1363 if (TyClass != CanFrom->getTypeClass()) return false;
1364 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1365 return false;
1366 }
1367
1368 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1369 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1370 if (!EInfo.getNoReturn()) return false;
1371
1372 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1373 assert(QualType(FromFn, 0).isCanonical());
1374 if (QualType(FromFn, 0) != CanTo) return false;
1375
1376 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001377 return true;
1378}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379
Douglas Gregor46188682010-05-18 22:42:18 +00001380/// \brief Determine whether the conversion from FromType to ToType is a valid
1381/// vector conversion.
1382///
1383/// \param ICK Will be set to the vector conversion kind, if this is a vector
1384/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001385static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001387 // We need at least one of these types to be a vector type to have a vector
1388 // conversion.
1389 if (!ToType->isVectorType() && !FromType->isVectorType())
1390 return false;
1391
1392 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001393 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001394 return false;
1395
1396 // There are no conversions between extended vector types, only identity.
1397 if (ToType->isExtVectorType()) {
1398 // There are no conversions between extended vector types other than the
1399 // identity conversion.
1400 if (FromType->isExtVectorType())
1401 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001402
Douglas Gregor46188682010-05-18 22:42:18 +00001403 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001404 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001405 ICK = ICK_Vector_Splat;
1406 return true;
1407 }
1408 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001409
1410 // We can perform the conversion between vector types in the following cases:
1411 // 1)vector types are equivalent AltiVec and GCC vector types
1412 // 2)lax vector conversions are permitted and the vector types are of the
1413 // same size
1414 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001415 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1416 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001417 ICK = ICK_Vector_Conversion;
1418 return true;
1419 }
Douglas Gregor46188682010-05-18 22:42:18 +00001420 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001421
Douglas Gregor46188682010-05-18 22:42:18 +00001422 return false;
1423}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001424
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001425static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1426 bool InOverloadResolution,
1427 StandardConversionSequence &SCS,
1428 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001429
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001430/// IsStandardConversion - Determines whether there is a standard
1431/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1432/// expression From to the type ToType. Standard conversion sequences
1433/// only consider non-class types; for conversions that involve class
1434/// types, use TryImplicitConversion. If a conversion exists, SCS will
1435/// contain the standard conversion sequence required to perform this
1436/// conversion and this routine will return true. Otherwise, this
1437/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001438static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1439 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001440 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001441 bool CStyle,
1442 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001444
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001445 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001446 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001447 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001448 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001449 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001450
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001451 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001452 // abort early. When overloading in C, however, we do permit them.
1453 if (S.getLangOpts().CPlusPlus &&
1454 (FromType->isRecordType() || ToType->isRecordType()))
1455 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001456
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001457 // The first conversion can be an lvalue-to-rvalue conversion,
1458 // array-to-pointer conversion, or function-to-pointer conversion
1459 // (C++ 4p1).
1460
John McCall5c32be02010-08-24 20:38:10 +00001461 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001462 DeclAccessPair AccessPair;
1463 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001465 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001466 // We were able to resolve the address of the overloaded function,
1467 // so we can convert to the type of that function.
1468 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001469 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001470
1471 // we can sometimes resolve &foo<int> regardless of ToType, so check
1472 // if the type matches (identity) or we are converting to bool
1473 if (!S.Context.hasSameUnqualifiedType(
1474 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1475 QualType resultTy;
1476 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001477 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001478 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1479 // otherwise, only a boolean conversion is standard
1480 if (!ToType->isBooleanType())
1481 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483
Chandler Carruthffce2452011-03-29 08:08:18 +00001484 // Check if the "from" expression is taking the address of an overloaded
1485 // function and recompute the FromType accordingly. Take advantage of the
1486 // fact that non-static member functions *must* have such an address-of
1487 // expression.
1488 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1489 if (Method && !Method->isStatic()) {
1490 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1491 "Non-unary operator on non-static member address");
1492 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1493 == UO_AddrOf &&
1494 "Non-address-of operator on non-static member address");
1495 const Type *ClassType
1496 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1497 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001498 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1499 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1500 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001501 "Non-address-of operator for overloaded function expression");
1502 FromType = S.Context.getPointerType(FromType);
1503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001504
Douglas Gregor980fb162010-04-29 18:24:40 +00001505 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001506 assert(S.Context.hasSameType(
1507 FromType,
1508 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001509 } else {
1510 return false;
1511 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001512 }
John McCall154a2fd2011-08-30 00:57:29 +00001513 // Lvalue-to-rvalue conversion (C++11 4.1):
1514 // A glvalue (3.10) of a non-function, non-array type T can
1515 // be converted to a prvalue.
1516 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001517 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001518 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001519 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001521
Douglas Gregorc79862f2012-04-12 17:51:55 +00001522 // C11 6.3.2.1p2:
1523 // ... if the lvalue has atomic type, the value has the non-atomic version
1524 // of the type of the lvalue ...
1525 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1526 FromType = Atomic->getValueType();
1527
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528 // If T is a non-class type, the type of the rvalue is the
1529 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001530 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1531 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001532 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001533 } else if (FromType->isArrayType()) {
1534 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001535 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536
1537 // An lvalue or rvalue of type "array of N T" or "array of unknown
1538 // bound of T" can be converted to an rvalue of type "pointer to
1539 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001540 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001541
John McCall5c32be02010-08-24 20:38:10 +00001542 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001543 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001544 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545
1546 // For the purpose of ranking in overload resolution
1547 // (13.3.3.1.1), this conversion is considered an
1548 // array-to-pointer conversion followed by a qualification
1549 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001550 SCS.Second = ICK_Identity;
1551 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001552 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001553 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001554 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001555 }
John McCall086a4642010-11-24 05:12:34 +00001556 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001557 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001560 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1561 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1562 if (!S.checkAddressOfFunctionIsAvailable(FD))
1563 return false;
1564
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 // An lvalue of function type T can be converted to an rvalue of
1566 // type "pointer to T." The result is a pointer to the
1567 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001568 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001569 } else {
1570 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001571 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001573 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574
1575 // The second conversion can be an integral promotion, floating
1576 // point promotion, integral conversion, floating point conversion,
1577 // floating-integral conversion, pointer conversion,
1578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001579 // For overloading in C, this can also be a "compatible-type"
1580 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001581 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001582 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001583 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 // The unqualified versions of the types are the same: there's no
1585 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001587 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001588 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001591 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001592 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001593 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001595 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001596 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001597 SCS.Second = ICK_Complex_Promotion;
1598 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001599 } else if (ToType->isBooleanType() &&
1600 (FromType->isArithmeticType() ||
1601 FromType->isAnyPointerType() ||
1602 FromType->isBlockPointerType() ||
1603 FromType->isMemberPointerType() ||
1604 FromType->isNullPtrType())) {
1605 // Boolean conversions (C++ 4.12).
1606 SCS.Second = ICK_Boolean_Conversion;
1607 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001608 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001609 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001610 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001611 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001612 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001613 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001614 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001615 SCS.Second = ICK_Complex_Conversion;
1616 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001617 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1618 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001619 // Complex-real conversions (C99 6.3.1.7)
1620 SCS.Second = ICK_Complex_Real;
1621 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001622 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001623 // Floating point conversions (C++ 4.8).
1624 SCS.Second = ICK_Floating_Conversion;
1625 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001626 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001627 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001628 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001629 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001630 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001631 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001633 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001634 SCS.Second = ICK_Block_Pointer_Conversion;
1635 } else if (AllowObjCWritebackConversion &&
1636 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1637 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001638 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1639 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001640 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001641 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001642 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001643 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001644 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001645 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001646 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001647 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001648 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001649 SCS.Second = SecondICK;
1650 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001651 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001652 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001653 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001654 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001655 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001656 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001657 // Treat a conversion that strips "noreturn" as an identity conversion.
1658 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001659 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1660 InOverloadResolution,
1661 SCS, CStyle)) {
1662 SCS.Second = ICK_TransparentUnionConversion;
1663 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001664 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1665 CStyle)) {
1666 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001667 // appropriately.
1668 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001669 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001670 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001671 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001672 SCS.Second = ICK_Zero_Event_Conversion;
1673 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 } else {
1675 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001678 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001680 QualType CanonFrom;
1681 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001683 bool ObjCLifetimeConversion;
1684 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1685 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001686 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001687 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001689 CanonFrom = S.Context.getCanonicalType(FromType);
1690 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001691 } else {
1692 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 SCS.Third = ICK_Identity;
1694
Mike Stump11289f42009-09-09 15:08:12 +00001695 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 // [...] Any difference in top-level cv-qualification is
1697 // subsumed by the initialization itself and does not constitute
1698 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001699 CanonFrom = S.Context.getCanonicalType(FromType);
1700 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001702 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001703 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001704 FromType = ToType;
1705 CanonFrom = CanonTo;
1706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001707 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001708 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001709
George Burgess IV45461812015-10-11 20:13:20 +00001710 if (CanonFrom == CanonTo)
1711 return true;
1712
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001714 // this is a bad conversion sequence, unless we're resolving an overload in C.
1715 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001716 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717
George Burgess IV45461812015-10-11 20:13:20 +00001718 ExprResult ER = ExprResult{From};
1719 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1720 /*Diagnose=*/false,
1721 /*DiagnoseCFAudited=*/false,
1722 /*ConvertRHS=*/false);
1723 if (Conv != Sema::Compatible)
1724 return false;
1725
1726 SCS.setAllToTypes(ToType);
1727 // We need to set all three because we want this conversion to rank terribly,
1728 // and we don't know what conversions it may overlap with.
1729 SCS.First = ICK_C_Only_Conversion;
1730 SCS.Second = ICK_C_Only_Conversion;
1731 SCS.Third = ICK_C_Only_Conversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001732 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001733}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001734
1735static bool
1736IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1737 QualType &ToType,
1738 bool InOverloadResolution,
1739 StandardConversionSequence &SCS,
1740 bool CStyle) {
1741
1742 const RecordType *UT = ToType->getAsUnionType();
1743 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1744 return false;
1745 // The field to initialize within the transparent union.
1746 RecordDecl *UD = UT->getDecl();
1747 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001748 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001749 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1750 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001751 ToType = it->getType();
1752 return true;
1753 }
1754 }
1755 return false;
1756}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757
1758/// IsIntegralPromotion - Determines whether the conversion from the
1759/// expression From (whose potentially-adjusted type is FromType) to
1760/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1761/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001762bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001763 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001764 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001765 if (!To) {
1766 return false;
1767 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768
1769 // An rvalue of type char, signed char, unsigned char, short int, or
1770 // unsigned short int can be converted to an rvalue of type int if
1771 // int can represent all the values of the source type; otherwise,
1772 // the source rvalue can be converted to an rvalue of type unsigned
1773 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001774 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1775 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001776 if (// We can promote any signed, promotable integer type to an int
1777 (FromType->isSignedIntegerType() ||
1778 // We can promote any unsigned integer type whose size is
1779 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001780 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001781 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001783 }
1784
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785 return To->getKind() == BuiltinType::UInt;
1786 }
1787
Richard Smithb9c5a602012-09-13 21:18:54 +00001788 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789 // A prvalue of an unscoped enumeration type whose underlying type is not
1790 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1791 // following types that can represent all the values of the enumeration
1792 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1793 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001794 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001795 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001796 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001797 // with lowest integer conversion rank (4.13) greater than the rank of long
1798 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001799 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001800 // C++11 [conv.prom]p4:
1801 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1802 // can be converted to a prvalue of its underlying type. Moreover, if
1803 // integral promotion can be applied to its underlying type, a prvalue of an
1804 // unscoped enumeration type whose underlying type is fixed can also be
1805 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001806 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1807 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1808 // provided for a scoped enumeration.
1809 if (FromEnumType->getDecl()->isScoped())
1810 return false;
1811
Richard Smithb9c5a602012-09-13 21:18:54 +00001812 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001813 // even if that's not the promoted type. Note that the check for promoting
1814 // the underlying type is based on the type alone, and does not consider
1815 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001816 if (FromEnumType->getDecl()->isFixed()) {
1817 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1818 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001819 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001820 }
1821
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001822 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001824 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001825 return Context.hasSameUnqualifiedType(
1826 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001827 }
John McCall56774992009-12-09 09:09:27 +00001828
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001829 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1831 // to an rvalue a prvalue of the first of the following types that can
1832 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001833 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001834 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001835 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001836 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001837 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001839 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001840 // Determine whether the type we're converting from is signed or
1841 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001842 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001843 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001844
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845 // The types we'll try to promote to, in the appropriate
1846 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001847 QualType PromoteTypes[6] = {
1848 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001849 Context.LongTy, Context.UnsignedLongTy ,
1850 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001851 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001852 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001853 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1854 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001855 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001856 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1857 // We found the type that we can promote to. If this is the
1858 // type we wanted, we have a promotion. Otherwise, no
1859 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001860 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001861 }
1862 }
1863 }
1864
1865 // An rvalue for an integral bit-field (9.6) can be converted to an
1866 // rvalue of type int if int can represent all the values of the
1867 // bit-field; otherwise, it can be converted to unsigned int if
1868 // unsigned int can represent all the values of the bit-field. If
1869 // the bit-field is larger yet, no integral promotion applies to
1870 // it. If the bit-field has an enumerated type, it is treated as any
1871 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001872 // FIXME: We should delay checking of bit-fields until we actually perform the
1873 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001874 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001875 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001876 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001877 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001878 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001879 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001880 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001882 // Are we promoting to an int from a bitfield that fits in an int?
1883 if (BitWidth < ToSize ||
1884 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1885 return To->getKind() == BuiltinType::Int;
1886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001888 // Are we promoting to an unsigned int from an unsigned bitfield
1889 // that fits into an unsigned int?
1890 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1891 return To->getKind() == BuiltinType::UInt;
1892 }
Mike Stump11289f42009-09-09 15:08:12 +00001893
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001894 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001895 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001899 // An rvalue of type bool can be converted to an rvalue of type int,
1900 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001901 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001902 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001903 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001904
1905 return false;
1906}
1907
1908/// IsFloatingPointPromotion - Determines whether the conversion from
1909/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1910/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001911bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001912 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1913 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001914 /// An rvalue of type float can be converted to an rvalue of type
1915 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001916 if (FromBuiltin->getKind() == BuiltinType::Float &&
1917 ToBuiltin->getKind() == BuiltinType::Double)
1918 return true;
1919
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001920 // C99 6.3.1.5p1:
1921 // When a float is promoted to double or long double, or a
1922 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001923 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001924 (FromBuiltin->getKind() == BuiltinType::Float ||
1925 FromBuiltin->getKind() == BuiltinType::Double) &&
1926 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1927 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001928
1929 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001930 if (!getLangOpts().NativeHalfType &&
1931 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001932 ToBuiltin->getKind() == BuiltinType::Float)
1933 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001934 }
1935
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001936 return false;
1937}
1938
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001939/// \brief Determine if a conversion is a complex promotion.
1940///
1941/// A complex promotion is defined as a complex -> complex conversion
1942/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001943/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001944bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001945 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001946 if (!FromComplex)
1947 return false;
1948
John McCall9dd450b2009-09-21 23:43:11 +00001949 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001950 if (!ToComplex)
1951 return false;
1952
1953 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001954 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001955 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001956 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001957}
1958
Douglas Gregor237f96c2008-11-26 23:31:11 +00001959/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1960/// the pointer type FromPtr to a pointer to type ToPointee, with the
1961/// same type qualifiers as FromPtr has on its pointee type. ToType,
1962/// if non-empty, will be a pointer to ToType that may or may not have
1963/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001964///
Mike Stump11289f42009-09-09 15:08:12 +00001965static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001966BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001967 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001968 ASTContext &Context,
1969 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001970 assert((FromPtr->getTypeClass() == Type::Pointer ||
1971 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1972 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
John McCall31168b02011-06-15 23:02:42 +00001974 /// Conversions to 'id' subsume cv-qualifier conversions.
1975 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001976 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
1978 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001979 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001980 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001981 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001982
John McCall31168b02011-06-15 23:02:42 +00001983 if (StripObjCLifetime)
1984 Quals.removeObjCLifetime();
1985
Mike Stump11289f42009-09-09 15:08:12 +00001986 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001987 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001988 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001989 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001990 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001991
1992 // Build a pointer to ToPointee. It has the right qualifiers
1993 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001994 if (isa<ObjCObjectPointerType>(ToType))
1995 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001996 return Context.getPointerType(ToPointee);
1997 }
1998
1999 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002000 QualType QualifiedCanonToPointee
2001 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002003 if (isa<ObjCObjectPointerType>(ToType))
2004 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2005 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002006}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Mike Stump11289f42009-09-09 15:08:12 +00002008static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002009 bool InOverloadResolution,
2010 ASTContext &Context) {
2011 // Handle value-dependent integral null pointer constants correctly.
2012 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2013 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002014 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002015 return !InOverloadResolution;
2016
Douglas Gregor56751b52009-09-25 04:25:58 +00002017 return Expr->isNullPointerConstant(Context,
2018 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2019 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002020}
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002022/// IsPointerConversion - Determines whether the conversion of the
2023/// expression From, which has the (possibly adjusted) type FromType,
2024/// can be converted to the type ToType via a pointer conversion (C++
2025/// 4.10). If so, returns true and places the converted type (that
2026/// might differ from ToType in its cv-qualifiers at some level) into
2027/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002028///
Douglas Gregora29dc052008-11-27 01:19:21 +00002029/// This routine also supports conversions to and from block pointers
2030/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2031/// pointers to interfaces. FIXME: Once we've determined the
2032/// appropriate overloading rules for Objective-C, we may want to
2033/// split the Objective-C checks into a different routine; however,
2034/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002035/// conversions, so for now they live here. IncompatibleObjC will be
2036/// set if the conversion is an allowed Objective-C conversion that
2037/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002038bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002039 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002040 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002041 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002042 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002043 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2044 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002045 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002046
Mike Stump11289f42009-09-09 15:08:12 +00002047 // Conversion from a null pointer constant to any Objective-C pointer type.
2048 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002049 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002050 ConvertedType = ToType;
2051 return true;
2052 }
2053
Douglas Gregor231d1c62008-11-27 00:15:41 +00002054 // Blocks: Block pointers can be converted to void*.
2055 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002056 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002057 ConvertedType = ToType;
2058 return true;
2059 }
2060 // Blocks: A null pointer constant can be converted to a block
2061 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002062 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002063 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002064 ConvertedType = ToType;
2065 return true;
2066 }
2067
Sebastian Redl576fd422009-05-10 18:38:11 +00002068 // If the left-hand-side is nullptr_t, the right side can be a null
2069 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002070 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002071 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002072 ConvertedType = ToType;
2073 return true;
2074 }
2075
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002077 if (!ToTypePtr)
2078 return false;
2079
2080 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002081 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002082 ConvertedType = ToType;
2083 return true;
2084 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002085
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002087 // , including objective-c pointers.
2088 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002089 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002090 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002091 ConvertedType = BuildSimilarlyQualifiedPointerType(
2092 FromType->getAs<ObjCObjectPointerType>(),
2093 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002094 ToType, Context);
2095 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002096 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002097 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002098 if (!FromTypePtr)
2099 return false;
2100
2101 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002102
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002104 // pointer conversion, so don't do all of the work below.
2105 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2106 return false;
2107
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108 // An rvalue of type "pointer to cv T," where T is an object type,
2109 // can be converted to an rvalue of type "pointer to cv void" (C++
2110 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002111 if (FromPointeeType->isIncompleteOrObjectType() &&
2112 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002113 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002114 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002115 ToType, Context,
2116 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002117 return true;
2118 }
2119
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002120 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002121 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002122 ToPointeeType->isVoidType()) {
2123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2124 ToPointeeType,
2125 ToType, Context);
2126 return true;
2127 }
2128
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002129 // When we're overloading in C, we allow a special kind of pointer
2130 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002131 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002132 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002133 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002134 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002135 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002136 return true;
2137 }
2138
Douglas Gregor5c407d92008-10-23 00:40:37 +00002139 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002140 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002141 // An rvalue of type "pointer to cv D," where D is a class type,
2142 // can be converted to an rvalue of type "pointer to cv B," where
2143 // B is a base class (clause 10) of D. If B is an inaccessible
2144 // (clause 11) or ambiguous (10.2) base class of D, a program that
2145 // necessitates this conversion is ill-formed. The result of the
2146 // conversion is a pointer to the base class sub-object of the
2147 // derived class object. The null pointer value is converted to
2148 // the null pointer value of the destination type.
2149 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002150 // Note that we do not check for ambiguity or inaccessibility
2151 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002152 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002153 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002154 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002155 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002156 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002158 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002159 ToType, Context);
2160 return true;
2161 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002162
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002163 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2164 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2166 ToPointeeType,
2167 ToType, Context);
2168 return true;
2169 }
2170
Douglas Gregora119f102008-12-19 19:13:09 +00002171 return false;
2172}
Douglas Gregoraec25842011-04-26 23:16:46 +00002173
2174/// \brief Adopt the given qualifiers for the given type.
2175static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2176 Qualifiers TQs = T.getQualifiers();
2177
2178 // Check whether qualifiers already match.
2179 if (TQs == Qs)
2180 return T;
2181
2182 if (Qs.compatiblyIncludes(TQs))
2183 return Context.getQualifiedType(T, Qs);
2184
2185 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2186}
Douglas Gregora119f102008-12-19 19:13:09 +00002187
2188/// isObjCPointerConversion - Determines whether this is an
2189/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2190/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002191bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002192 QualType& ConvertedType,
2193 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002194 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002195 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
Douglas Gregoraec25842011-04-26 23:16:46 +00002197 // The set of qualifiers on the type we're converting from.
2198 Qualifiers FromQualifiers = FromType.getQualifiers();
2199
Steve Naroff7cae42b2009-07-10 23:34:53 +00002200 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002201 const ObjCObjectPointerType* ToObjCPtr =
2202 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002203 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002204 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002205
Steve Naroff7cae42b2009-07-10 23:34:53 +00002206 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002207 // If the pointee types are the same (ignoring qualifications),
2208 // then this is not a pointer conversion.
2209 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2210 FromObjCPtr->getPointeeType()))
2211 return false;
2212
Douglas Gregorab209d82015-07-07 03:58:42 +00002213 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002214 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002215 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2216 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002217 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002218 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2219 FromObjCPtr->getPointeeType()))
2220 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002222 ToObjCPtr->getPointeeType(),
2223 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002225 return true;
2226 }
2227
2228 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2229 // Okay: this is some kind of implicit downcast of Objective-C
2230 // interfaces, which is permitted. However, we're going to
2231 // complain about it.
2232 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002233 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002234 ToObjCPtr->getPointeeType(),
2235 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002237 return true;
2238 }
Mike Stump11289f42009-09-09 15:08:12 +00002239 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002240 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002241 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002242 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002243 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002245 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002246 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002247 // to a block pointer type.
2248 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002249 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002250 return true;
2251 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002252 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002254 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002255 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002256 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002257 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002258 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002259 return true;
2260 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002261 else
Douglas Gregora119f102008-12-19 19:13:09 +00002262 return false;
2263
Douglas Gregor033f56d2008-12-23 00:53:59 +00002264 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002265 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002266 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002267 else if (const BlockPointerType *FromBlockPtr =
2268 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002269 FromPointeeType = FromBlockPtr->getPointeeType();
2270 else
Douglas Gregora119f102008-12-19 19:13:09 +00002271 return false;
2272
Douglas Gregora119f102008-12-19 19:13:09 +00002273 // If we have pointers to pointers, recursively check whether this
2274 // is an Objective-C conversion.
2275 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2277 IncompatibleObjC)) {
2278 // We always complain about this conversion.
2279 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002280 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002281 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002282 return true;
2283 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002284 // Allow conversion of pointee being objective-c pointer to another one;
2285 // as in I* to id.
2286 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2287 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2288 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2289 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002290
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002291 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002292 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002293 return true;
2294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002295
Douglas Gregor033f56d2008-12-23 00:53:59 +00002296 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002297 // differences in the argument and result types are in Objective-C
2298 // pointer conversions. If so, we permit the conversion (but
2299 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002300 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002301 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002302 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002303 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002304 if (FromFunctionType && ToFunctionType) {
2305 // If the function types are exactly the same, this isn't an
2306 // Objective-C pointer conversion.
2307 if (Context.getCanonicalType(FromPointeeType)
2308 == Context.getCanonicalType(ToPointeeType))
2309 return false;
2310
2311 // Perform the quick checks that will tell us whether these
2312 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002313 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002314 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2315 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2316 return false;
2317
2318 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002319 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2320 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002321 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002322 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2323 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002324 ConvertedType, IncompatibleObjC)) {
2325 // Okay, we have an Objective-C pointer conversion.
2326 HasObjCConversion = true;
2327 } else {
2328 // Function types are too different. Abort.
2329 return false;
2330 }
Mike Stump11289f42009-09-09 15:08:12 +00002331
Douglas Gregora119f102008-12-19 19:13:09 +00002332 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002333 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002334 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002335 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2336 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002337 if (Context.getCanonicalType(FromArgType)
2338 == Context.getCanonicalType(ToArgType)) {
2339 // Okay, the types match exactly. Nothing to do.
2340 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2341 ConvertedType, IncompatibleObjC)) {
2342 // Okay, we have an Objective-C pointer conversion.
2343 HasObjCConversion = true;
2344 } else {
2345 // Argument types are too different. Abort.
2346 return false;
2347 }
2348 }
2349
2350 if (HasObjCConversion) {
2351 // We had an Objective-C conversion. Allow this pointer
2352 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002353 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002354 IncompatibleObjC = true;
2355 return true;
2356 }
2357 }
2358
Sebastian Redl72b597d2009-01-25 19:43:20 +00002359 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002360}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002361
John McCall31168b02011-06-15 23:02:42 +00002362/// \brief Determine whether this is an Objective-C writeback conversion,
2363/// used for parameter passing when performing automatic reference counting.
2364///
2365/// \param FromType The type we're converting form.
2366///
2367/// \param ToType The type we're converting to.
2368///
2369/// \param ConvertedType The type that will be produced after applying
2370/// this conversion.
2371bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2372 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002373 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002374 Context.hasSameUnqualifiedType(FromType, ToType))
2375 return false;
2376
2377 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2378 QualType ToPointee;
2379 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2380 ToPointee = ToPointer->getPointeeType();
2381 else
2382 return false;
2383
2384 Qualifiers ToQuals = ToPointee.getQualifiers();
2385 if (!ToPointee->isObjCLifetimeType() ||
2386 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002387 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002388 return false;
2389
2390 // Argument must be a pointer to __strong to __weak.
2391 QualType FromPointee;
2392 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2393 FromPointee = FromPointer->getPointeeType();
2394 else
2395 return false;
2396
2397 Qualifiers FromQuals = FromPointee.getQualifiers();
2398 if (!FromPointee->isObjCLifetimeType() ||
2399 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2400 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2401 return false;
2402
2403 // Make sure that we have compatible qualifiers.
2404 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2405 if (!ToQuals.compatiblyIncludes(FromQuals))
2406 return false;
2407
2408 // Remove qualifiers from the pointee type we're converting from; they
2409 // aren't used in the compatibility check belong, and we'll be adding back
2410 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2411 FromPointee = FromPointee.getUnqualifiedType();
2412
2413 // The unqualified form of the pointee types must be compatible.
2414 ToPointee = ToPointee.getUnqualifiedType();
2415 bool IncompatibleObjC;
2416 if (Context.typesAreCompatible(FromPointee, ToPointee))
2417 FromPointee = ToPointee;
2418 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2419 IncompatibleObjC))
2420 return false;
2421
2422 /// \brief Construct the type we're converting to, which is a pointer to
2423 /// __autoreleasing pointee.
2424 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2425 ConvertedType = Context.getPointerType(FromPointee);
2426 return true;
2427}
2428
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002429bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2430 QualType& ConvertedType) {
2431 QualType ToPointeeType;
2432 if (const BlockPointerType *ToBlockPtr =
2433 ToType->getAs<BlockPointerType>())
2434 ToPointeeType = ToBlockPtr->getPointeeType();
2435 else
2436 return false;
2437
2438 QualType FromPointeeType;
2439 if (const BlockPointerType *FromBlockPtr =
2440 FromType->getAs<BlockPointerType>())
2441 FromPointeeType = FromBlockPtr->getPointeeType();
2442 else
2443 return false;
2444 // We have pointer to blocks, check whether the only
2445 // differences in the argument and result types are in Objective-C
2446 // pointer conversions. If so, we permit the conversion.
2447
2448 const FunctionProtoType *FromFunctionType
2449 = FromPointeeType->getAs<FunctionProtoType>();
2450 const FunctionProtoType *ToFunctionType
2451 = ToPointeeType->getAs<FunctionProtoType>();
2452
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002453 if (!FromFunctionType || !ToFunctionType)
2454 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002455
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002456 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002457 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002458
2459 // Perform the quick checks that will tell us whether these
2460 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002461 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002462 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2463 return false;
2464
2465 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2466 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2467 if (FromEInfo != ToEInfo)
2468 return false;
2469
2470 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002471 if (Context.hasSameType(FromFunctionType->getReturnType(),
2472 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002473 // Okay, the types match exactly. Nothing to do.
2474 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002475 QualType RHS = FromFunctionType->getReturnType();
2476 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002477 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002478 !RHS.hasQualifiers() && LHS.hasQualifiers())
2479 LHS = LHS.getUnqualifiedType();
2480
2481 if (Context.hasSameType(RHS,LHS)) {
2482 // OK exact match.
2483 } else if (isObjCPointerConversion(RHS, LHS,
2484 ConvertedType, IncompatibleObjC)) {
2485 if (IncompatibleObjC)
2486 return false;
2487 // Okay, we have an Objective-C pointer conversion.
2488 }
2489 else
2490 return false;
2491 }
2492
2493 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002494 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002495 ArgIdx != NumArgs; ++ArgIdx) {
2496 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002497 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2498 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002499 if (Context.hasSameType(FromArgType, ToArgType)) {
2500 // Okay, the types match exactly. Nothing to do.
2501 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2502 ConvertedType, IncompatibleObjC)) {
2503 if (IncompatibleObjC)
2504 return false;
2505 // Okay, we have an Objective-C pointer conversion.
2506 } else
2507 // Argument types are too different. Abort.
2508 return false;
2509 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002510 if (LangOpts.ObjCAutoRefCount &&
2511 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2512 ToFunctionType))
2513 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002514
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002515 ConvertedType = ToType;
2516 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002517}
2518
Richard Trieucaff2472011-11-23 22:32:32 +00002519enum {
2520 ft_default,
2521 ft_different_class,
2522 ft_parameter_arity,
2523 ft_parameter_mismatch,
2524 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002525 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002526};
2527
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002528/// Attempts to get the FunctionProtoType from a Type. Handles
2529/// MemberFunctionPointers properly.
2530static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2531 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2532 return FPT;
2533
2534 if (auto *MPT = FromType->getAs<MemberPointerType>())
2535 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2536
2537 return nullptr;
2538}
2539
Richard Trieucaff2472011-11-23 22:32:32 +00002540/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2541/// function types. Catches different number of parameter, mismatch in
2542/// parameter types, and different return types.
2543void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2544 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002545 // If either type is not valid, include no extra info.
2546 if (FromType.isNull() || ToType.isNull()) {
2547 PDiag << ft_default;
2548 return;
2549 }
2550
Richard Trieucaff2472011-11-23 22:32:32 +00002551 // Get the function type from the pointers.
2552 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2553 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2554 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002555 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002556 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2557 << QualType(FromMember->getClass(), 0);
2558 return;
2559 }
2560 FromType = FromMember->getPointeeType();
2561 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002562 }
2563
Richard Trieu96ed5b62011-12-13 23:19:45 +00002564 if (FromType->isPointerType())
2565 FromType = FromType->getPointeeType();
2566 if (ToType->isPointerType())
2567 ToType = ToType->getPointeeType();
2568
2569 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002570 FromType = FromType.getNonReferenceType();
2571 ToType = ToType.getNonReferenceType();
2572
Richard Trieucaff2472011-11-23 22:32:32 +00002573 // Don't print extra info for non-specialized template functions.
2574 if (FromType->isInstantiationDependentType() &&
2575 !FromType->getAs<TemplateSpecializationType>()) {
2576 PDiag << ft_default;
2577 return;
2578 }
2579
Richard Trieu96ed5b62011-12-13 23:19:45 +00002580 // No extra info for same types.
2581 if (Context.hasSameType(FromType, ToType)) {
2582 PDiag << ft_default;
2583 return;
2584 }
2585
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002586 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2587 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002588
2589 // Both types need to be function types.
2590 if (!FromFunction || !ToFunction) {
2591 PDiag << ft_default;
2592 return;
2593 }
2594
Alp Toker9cacbab2014-01-20 20:26:09 +00002595 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2596 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2597 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002598 return;
2599 }
2600
2601 // Handle different parameter types.
2602 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002603 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002604 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002605 << ToFunction->getParamType(ArgPos)
2606 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002607 return;
2608 }
2609
2610 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002611 if (!Context.hasSameType(FromFunction->getReturnType(),
2612 ToFunction->getReturnType())) {
2613 PDiag << ft_return_type << ToFunction->getReturnType()
2614 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002615 return;
2616 }
2617
2618 unsigned FromQuals = FromFunction->getTypeQuals(),
2619 ToQuals = ToFunction->getTypeQuals();
2620 if (FromQuals != ToQuals) {
2621 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2622 return;
2623 }
2624
2625 // Unable to find a difference, so add no extra info.
2626 PDiag << ft_default;
2627}
2628
Alp Toker9cacbab2014-01-20 20:26:09 +00002629/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002630/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002631/// they have same number of arguments. If the parameters are different,
2632/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002633bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2634 const FunctionProtoType *NewType,
2635 unsigned *ArgPos) {
2636 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2637 N = NewType->param_type_begin(),
2638 E = OldType->param_type_end();
2639 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002640 if (!Context.hasSameType(O->getUnqualifiedType(),
2641 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002642 if (ArgPos)
2643 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002644 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002645 }
2646 }
2647 return true;
2648}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002649
Douglas Gregor39c16d42008-10-24 04:54:22 +00002650/// CheckPointerConversion - Check the pointer conversion from the
2651/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002652/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002653/// conversions for which IsPointerConversion has already returned
2654/// true. It returns true and produces a diagnostic if there was an
2655/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002656bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002657 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002658 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002659 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002660 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002661 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002662
John McCall8cb679e2010-11-15 09:13:47 +00002663 Kind = CK_BitCast;
2664
David Blaikie1c7c8f72012-08-08 17:33:31 +00002665 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002666 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002667 Expr::NPCK_ZeroExpression) {
2668 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2669 DiagRuntimeBehavior(From->getExprLoc(), From,
2670 PDiag(diag::warn_impcast_bool_to_null_pointer)
2671 << ToType << From->getSourceRange());
2672 else if (!isUnevaluatedContext())
2673 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2674 << ToType << From->getSourceRange();
2675 }
John McCall9320b872011-09-09 05:25:32 +00002676 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2677 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002678 QualType FromPointeeType = FromPtrType->getPointeeType(),
2679 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002680
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002683 // We must have a derived-to-base conversion. Check an
2684 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2686 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002687 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002688 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002689 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002691 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002692 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002693 }
David Majnemer6bf02822015-10-31 08:42:14 +00002694
2695 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() &&
2696 ToPointeeType->isVoidType()) {
2697 assert(getLangOpts().MSVCCompat &&
2698 "this should only be possible with MSVCCompat!");
2699 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2700 << From->getSourceRange();
2701 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002702 }
John McCall9320b872011-09-09 05:25:32 +00002703 } else if (const ObjCObjectPointerType *ToPtrType =
2704 ToType->getAs<ObjCObjectPointerType>()) {
2705 if (const ObjCObjectPointerType *FromPtrType =
2706 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002707 // Objective-C++ conversions are always okay.
2708 // FIXME: We should have a different class of conversions for the
2709 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002710 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002711 return false;
John McCall9320b872011-09-09 05:25:32 +00002712 } else if (FromType->isBlockPointerType()) {
2713 Kind = CK_BlockPointerToObjCPointerCast;
2714 } else {
2715 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002716 }
John McCall9320b872011-09-09 05:25:32 +00002717 } else if (ToType->isBlockPointerType()) {
2718 if (!FromType->isBlockPointerType())
2719 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002720 }
John McCall8cb679e2010-11-15 09:13:47 +00002721
2722 // We shouldn't fall into this case unless it's valid for other
2723 // reasons.
2724 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2725 Kind = CK_NullToPointer;
2726
Douglas Gregor39c16d42008-10-24 04:54:22 +00002727 return false;
2728}
2729
Sebastian Redl72b597d2009-01-25 19:43:20 +00002730/// IsMemberPointerConversion - Determines whether the conversion of the
2731/// expression From, which has the (possibly adjusted) type FromType, can be
2732/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2733/// If so, returns true and places the converted type (that might differ from
2734/// ToType in its cv-qualifiers at some level) into ConvertedType.
2735bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002736 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002737 bool InOverloadResolution,
2738 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002739 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002740 if (!ToTypePtr)
2741 return false;
2742
2743 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002744 if (From->isNullPointerConstant(Context,
2745 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2746 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002747 ConvertedType = ToType;
2748 return true;
2749 }
2750
2751 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002752 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002753 if (!FromTypePtr)
2754 return false;
2755
2756 // A pointer to member of B can be converted to a pointer to member of D,
2757 // where D is derived from B (C++ 4.11p2).
2758 QualType FromClass(FromTypePtr->getClass(), 0);
2759 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002760
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002761 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002762 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002763 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002764 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2765 ToClass.getTypePtr());
2766 return true;
2767 }
2768
2769 return false;
2770}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771
Sebastian Redl72b597d2009-01-25 19:43:20 +00002772/// CheckMemberPointerConversion - Check the member pointer conversion from the
2773/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002774/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002775/// for which IsMemberPointerConversion has already returned true. It returns
2776/// true and produces a diagnostic if there was an error, or returns false
2777/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002778bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002779 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002780 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002781 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002782 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002783 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002784 if (!FromPtrType) {
2785 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002787 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002788 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002789 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002790 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002791 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002792
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002793 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002794 assert(ToPtrType && "No member pointer cast has a target type "
2795 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002796
Sebastian Redled8f2002009-01-28 18:33:18 +00002797 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2798 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002799
Sebastian Redled8f2002009-01-28 18:33:18 +00002800 // FIXME: What about dependent types?
2801 assert(FromClass->isRecordType() && "Pointer into non-class.");
2802 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002803
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002804 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002805 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002806 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2807 assert(DerivationOkay &&
2808 "Should not have been called if derivation isn't OK.");
2809 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002810
Sebastian Redled8f2002009-01-28 18:33:18 +00002811 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2812 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002813 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2814 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2815 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2816 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002817 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002818
Douglas Gregor89ee6822009-02-28 01:32:25 +00002819 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002820 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2821 << FromClass << ToClass << QualType(VBase, 0)
2822 << From->getSourceRange();
2823 return true;
2824 }
2825
John McCall5b0829a2010-02-10 09:31:12 +00002826 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002827 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2828 Paths.front(),
2829 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002830
Anders Carlssond7923c62009-08-22 23:33:40 +00002831 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002832 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002833 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002834 return false;
2835}
2836
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002837/// Determine whether the lifetime conversion between the two given
2838/// qualifiers sets is nontrivial.
2839static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2840 Qualifiers ToQuals) {
2841 // Converting anything to const __unsafe_unretained is trivial.
2842 if (ToQuals.hasConst() &&
2843 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2844 return false;
2845
2846 return true;
2847}
2848
Douglas Gregor9a657932008-10-21 23:43:52 +00002849/// IsQualificationConversion - Determines whether the conversion from
2850/// an rvalue of type FromType to ToType is a qualification conversion
2851/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002852///
2853/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2854/// when the qualification conversion involves a change in the Objective-C
2855/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002856bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002858 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002859 FromType = Context.getCanonicalType(FromType);
2860 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002861 ObjCLifetimeConversion = false;
2862
Douglas Gregor9a657932008-10-21 23:43:52 +00002863 // If FromType and ToType are the same type, this is not a
2864 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002865 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002866 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002867
Douglas Gregor9a657932008-10-21 23:43:52 +00002868 // (C++ 4.4p4):
2869 // A conversion can add cv-qualifiers at levels other than the first
2870 // in multi-level pointers, subject to the following rules: [...]
2871 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002872 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002873 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002874 // Within each iteration of the loop, we check the qualifiers to
2875 // determine if this still looks like a qualification
2876 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002877 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002878 // until there are no more pointers or pointers-to-members left to
2879 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002880 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002881
Douglas Gregor90609aa2011-04-25 18:40:17 +00002882 Qualifiers FromQuals = FromType.getQualifiers();
2883 Qualifiers ToQuals = ToType.getQualifiers();
2884
John McCall31168b02011-06-15 23:02:42 +00002885 // Objective-C ARC:
2886 // Check Objective-C lifetime conversions.
2887 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2888 UnwrappedAnyPointer) {
2889 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002890 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2891 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002892 FromQuals.removeObjCLifetime();
2893 ToQuals.removeObjCLifetime();
2894 } else {
2895 // Qualification conversions cannot cast between different
2896 // Objective-C lifetime qualifiers.
2897 return false;
2898 }
2899 }
2900
Douglas Gregorf30053d2011-05-08 06:09:53 +00002901 // Allow addition/removal of GC attributes but not changing GC attributes.
2902 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2903 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2904 FromQuals.removeObjCGCAttr();
2905 ToQuals.removeObjCGCAttr();
2906 }
2907
Douglas Gregor9a657932008-10-21 23:43:52 +00002908 // -- for every j > 0, if const is in cv 1,j then const is in cv
2909 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002910 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002911 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Douglas Gregor9a657932008-10-21 23:43:52 +00002913 // -- if the cv 1,j and cv 2,j are different, then const is in
2914 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002915 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002916 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002917 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002918
Douglas Gregor9a657932008-10-21 23:43:52 +00002919 // Keep track of whether all prior cv-qualifiers in the "to" type
2920 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002921 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002922 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002923 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002924
2925 // We are left with FromType and ToType being the pointee types
2926 // after unwrapping the original FromType and ToType the same number
2927 // of types. If we unwrapped any pointers, and if FromType and
2928 // ToType have the same unqualified type (since we checked
2929 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002930 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002931}
2932
Douglas Gregorc79862f2012-04-12 17:51:55 +00002933/// \brief - Determine whether this is a conversion from a scalar type to an
2934/// atomic type.
2935///
2936/// If successful, updates \c SCS's second and third steps in the conversion
2937/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002938static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2939 bool InOverloadResolution,
2940 StandardConversionSequence &SCS,
2941 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002942 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2943 if (!ToAtomic)
2944 return false;
2945
2946 StandardConversionSequence InnerSCS;
2947 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2948 InOverloadResolution, InnerSCS,
2949 CStyle, /*AllowObjCWritebackConversion=*/false))
2950 return false;
2951
2952 SCS.Second = InnerSCS.Second;
2953 SCS.setToType(1, InnerSCS.getToType(1));
2954 SCS.Third = InnerSCS.Third;
2955 SCS.QualificationIncludesObjCLifetime
2956 = InnerSCS.QualificationIncludesObjCLifetime;
2957 SCS.setToType(2, InnerSCS.getToType(2));
2958 return true;
2959}
2960
Sebastian Redle5417162012-03-27 18:33:03 +00002961static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2962 CXXConstructorDecl *Constructor,
2963 QualType Type) {
2964 const FunctionProtoType *CtorType =
2965 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002966 if (CtorType->getNumParams() > 0) {
2967 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002968 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2969 return true;
2970 }
2971 return false;
2972}
2973
Sebastian Redl82ace982012-02-11 23:51:08 +00002974static OverloadingResult
2975IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2976 CXXRecordDecl *To,
2977 UserDefinedConversionSequence &User,
2978 OverloadCandidateSet &CandidateSet,
2979 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002980 DeclContext::lookup_result R = S.LookupConstructors(To);
2981 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002982 Con != ConEnd; ++Con) {
2983 NamedDecl *D = *Con;
2984 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2985
2986 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002987 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002988 FunctionTemplateDecl *ConstructorTmpl
2989 = dyn_cast<FunctionTemplateDecl>(D);
2990 if (ConstructorTmpl)
2991 Constructor
2992 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2993 else
2994 Constructor = cast<CXXConstructorDecl>(D);
2995
2996 bool Usable = !Constructor->isInvalidDecl() &&
2997 S.isInitListConstructor(Constructor) &&
2998 (AllowExplicit || !Constructor->isExplicit());
2999 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003000 // If the first argument is (a reference to) the target type,
3001 // suppress conversions.
3002 bool SuppressUserConversions =
3003 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00003004 if (ConstructorTmpl)
3005 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003006 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003007 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003008 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003009 else
3010 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003011 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00003012 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003013 }
3014 }
3015
3016 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3017
3018 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003019 switch (auto Result =
3020 CandidateSet.BestViableFunction(S, From->getLocStart(),
3021 Best, true)) {
3022 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003023 case OR_Success: {
3024 // Record the standard conversion we used and the conversion function.
3025 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003026 QualType ThisType = Constructor->getThisType(S.Context);
3027 // Initializer lists don't have conversions as such.
3028 User.Before.setAsIdentityConversion();
3029 User.HadMultipleCandidates = HadMultipleCandidates;
3030 User.ConversionFunction = Constructor;
3031 User.FoundConversionFunction = Best->FoundDecl;
3032 User.After.setAsIdentityConversion();
3033 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3034 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003035 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003036 }
3037
3038 case OR_No_Viable_Function:
3039 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003040 case OR_Ambiguous:
3041 return OR_Ambiguous;
3042 }
3043
3044 llvm_unreachable("Invalid OverloadResult!");
3045}
3046
Douglas Gregor576e98c2009-01-30 23:27:23 +00003047/// Determines whether there is a user-defined conversion sequence
3048/// (C++ [over.ics.user]) that converts expression From to the type
3049/// ToType. If such a conversion exists, User will contain the
3050/// user-defined conversion sequence that performs such a conversion
3051/// and this routine will return true. Otherwise, this routine returns
3052/// false and User is unspecified.
3053///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003054/// \param AllowExplicit true if the conversion should consider C++0x
3055/// "explicit" conversion functions as well as non-explicit conversion
3056/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003057///
3058/// \param AllowObjCConversionOnExplicit true if the conversion should
3059/// allow an extra Objective-C pointer conversion on uses of explicit
3060/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003061static OverloadingResult
3062IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003063 UserDefinedConversionSequence &User,
3064 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003065 bool AllowExplicit,
3066 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003067 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003068
Douglas Gregor5ab11652010-04-17 22:01:05 +00003069 // Whether we will only visit constructors.
3070 bool ConstructorsOnly = false;
3071
3072 // If the type we are conversion to is a class type, enumerate its
3073 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003074 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003075 // C++ [over.match.ctor]p1:
3076 // When objects of class type are direct-initialized (8.5), or
3077 // copy-initialized from an expression of the same or a
3078 // derived class type (8.5), overload resolution selects the
3079 // constructor. [...] For copy-initialization, the candidate
3080 // functions are all the converting constructors (12.3.1) of
3081 // that class. The argument list is the expression-list within
3082 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003083 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003084 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003085 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003086 ConstructorsOnly = true;
3087
Benjamin Kramer90633e32012-11-23 17:04:52 +00003088 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003089 // RequireCompleteType may have returned true due to some invalid decl
3090 // during template instantiation, but ToType may be complete enough now
3091 // to try to recover.
3092 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003093 // We're not going to find any constructors.
3094 } else if (CXXRecordDecl *ToRecordDecl
3095 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003096
3097 Expr **Args = &From;
3098 unsigned NumArgs = 1;
3099 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003100 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003101 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003102 OverloadingResult Result = IsInitializerListConstructorConversion(
3103 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3104 if (Result != OR_No_Viable_Function)
3105 return Result;
3106 // Never mind.
3107 CandidateSet.clear();
3108
3109 // If we're list-initializing, we pass the individual elements as
3110 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003111 Args = InitList->getInits();
3112 NumArgs = InitList->getNumInits();
3113 ListInitializing = true;
3114 }
3115
David Blaikieff7d47a2012-12-19 00:45:41 +00003116 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3117 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003118 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003119 NamedDecl *D = *Con;
3120 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3121
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003122 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003123 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003124 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003125 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003126 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003127 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003128 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3129 else
John McCalla0296f72010-03-19 07:35:19 +00003130 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003131
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003132 bool Usable = !Constructor->isInvalidDecl();
3133 if (ListInitializing)
3134 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3135 else
3136 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3137 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003138 bool SuppressUserConversions = !ConstructorsOnly;
3139 if (SuppressUserConversions && ListInitializing) {
3140 SuppressUserConversions = false;
3141 if (NumArgs == 1) {
3142 // If the first argument is (a reference to) the target type,
3143 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003144 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3145 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003146 }
3147 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003148 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003149 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003151 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003152 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003153 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003154 // Allow one user-defined conversion when user specifies a
3155 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003156 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003157 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003158 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003159 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003160 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003161 }
3162 }
3163
Douglas Gregor5ab11652010-04-17 22:01:05 +00003164 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003165 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003166 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003167 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003168 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003169 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003170 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003171 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3172 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003173 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3174 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003175 DeclAccessPair FoundDecl = I.getPair();
3176 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003177 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3178 if (isa<UsingShadowDecl>(D))
3179 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3180
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003181 CXXConversionDecl *Conv;
3182 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003183 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3184 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003185 else
John McCallda4458e2010-03-31 01:36:47 +00003186 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003187
3188 if (AllowExplicit || !Conv->isExplicit()) {
3189 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003190 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3191 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003192 CandidateSet,
3193 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003194 else
John McCall5c32be02010-08-24 20:38:10 +00003195 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003196 From, ToType, CandidateSet,
3197 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003198 }
3199 }
3200 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003201 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003202
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003203 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3204
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003205 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003206 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3207 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003208 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003209 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003210 // Record the standard conversion we used and the conversion function.
3211 if (CXXConstructorDecl *Constructor
3212 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3213 // C++ [over.ics.user]p1:
3214 // If the user-defined conversion is specified by a
3215 // constructor (12.3.1), the initial standard conversion
3216 // sequence converts the source type to the type required by
3217 // the argument of the constructor.
3218 //
3219 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003220 if (isa<InitListExpr>(From)) {
3221 // Initializer lists don't have conversions as such.
3222 User.Before.setAsIdentityConversion();
3223 } else {
3224 if (Best->Conversions[0].isEllipsis())
3225 User.EllipsisConversion = true;
3226 else {
3227 User.Before = Best->Conversions[0].Standard;
3228 User.EllipsisConversion = false;
3229 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003230 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003231 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003232 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003233 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003234 User.After.setAsIdentityConversion();
3235 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3236 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003237 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003238 }
3239 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003240 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3241 // C++ [over.ics.user]p1:
3242 //
3243 // [...] If the user-defined conversion is specified by a
3244 // conversion function (12.3.2), the initial standard
3245 // conversion sequence converts the source type to the
3246 // implicit object parameter of the conversion function.
3247 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003248 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003249 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003250 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003251 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003252
John McCall5c32be02010-08-24 20:38:10 +00003253 // C++ [over.ics.user]p2:
3254 // The second standard conversion sequence converts the
3255 // result of the user-defined conversion to the target type
3256 // for the sequence. Since an implicit conversion sequence
3257 // is an initialization, the special rules for
3258 // initialization by user-defined conversion apply when
3259 // selecting the best user-defined conversion for a
3260 // user-defined conversion sequence (see 13.3.3 and
3261 // 13.3.3.1).
3262 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003263 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003264 }
David Blaikie8a40f702012-01-17 06:56:22 +00003265 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003266
John McCall5c32be02010-08-24 20:38:10 +00003267 case OR_No_Viable_Function:
3268 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
John McCall5c32be02010-08-24 20:38:10 +00003270 case OR_Ambiguous:
3271 return OR_Ambiguous;
3272 }
3273
David Blaikie8a40f702012-01-17 06:56:22 +00003274 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003275}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003277bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003278Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003279 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003280 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3281 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003283 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003284 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003285 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003286 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3287 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003288 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003289 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003290 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003291 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003292 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003293 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003294 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003295 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003296 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003298}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003299
Douglas Gregor2837aa22012-02-22 17:32:19 +00003300/// \brief Compare the user-defined conversion functions or constructors
3301/// of two user-defined conversion sequences to determine whether any ordering
3302/// is possible.
3303static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003304compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003305 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003306 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003307 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003308
Douglas Gregor2837aa22012-02-22 17:32:19 +00003309 // Objective-C++:
3310 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003311 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003312 // respectively, always prefer the conversion to a function pointer,
3313 // because the function pointer is more lightweight and is more likely
3314 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003315 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003316 if (!Conv1)
3317 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003318
Douglas Gregor2837aa22012-02-22 17:32:19 +00003319 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3320 if (!Conv2)
3321 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003322
Douglas Gregor2837aa22012-02-22 17:32:19 +00003323 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3324 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3325 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3326 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003327 return Block1 ? ImplicitConversionSequence::Worse
3328 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003329 }
3330
3331 return ImplicitConversionSequence::Indistinguishable;
3332}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003333
3334static bool hasDeprecatedStringLiteralToCharPtrConversion(
3335 const ImplicitConversionSequence &ICS) {
3336 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3337 (ICS.isUserDefined() &&
3338 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3339}
3340
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003341/// CompareImplicitConversionSequences - Compare two implicit
3342/// conversion sequences to determine whether one is better than the
3343/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003344static ImplicitConversionSequence::CompareKind
3345CompareImplicitConversionSequences(Sema &S,
3346 const ImplicitConversionSequence& ICS1,
3347 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003348{
3349 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3350 // conversion sequences (as defined in 13.3.3.1)
3351 // -- a standard conversion sequence (13.3.3.1.1) is a better
3352 // conversion sequence than a user-defined conversion sequence or
3353 // an ellipsis conversion sequence, and
3354 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3355 // conversion sequence than an ellipsis conversion sequence
3356 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003357 //
John McCall0d1da222010-01-12 00:44:57 +00003358 // C++0x [over.best.ics]p10:
3359 // For the purpose of ranking implicit conversion sequences as
3360 // described in 13.3.3.2, the ambiguous conversion sequence is
3361 // treated as a user-defined sequence that is indistinguishable
3362 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003363
3364 // String literal to 'char *' conversion has been deprecated in C++03. It has
3365 // been removed from C++11. We still accept this conversion, if it happens at
3366 // the best viable function. Otherwise, this conversion is considered worse
3367 // than ellipsis conversion. Consider this as an extension; this is not in the
3368 // standard. For example:
3369 //
3370 // int &f(...); // #1
3371 // void f(char*); // #2
3372 // void g() { int &r = f("foo"); }
3373 //
3374 // In C++03, we pick #2 as the best viable function.
3375 // In C++11, we pick #1 as the best viable function, because ellipsis
3376 // conversion is better than string-literal to char* conversion (since there
3377 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3378 // convert arguments, #2 would be the best viable function in C++11.
3379 // If the best viable function has this conversion, a warning will be issued
3380 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3381
3382 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3383 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3384 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3385 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3386 ? ImplicitConversionSequence::Worse
3387 : ImplicitConversionSequence::Better;
3388
Douglas Gregor5ab11652010-04-17 22:01:05 +00003389 if (ICS1.getKindRank() < ICS2.getKindRank())
3390 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003391 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003392 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003393
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003394 // The following checks require both conversion sequences to be of
3395 // the same kind.
3396 if (ICS1.getKind() != ICS2.getKind())
3397 return ImplicitConversionSequence::Indistinguishable;
3398
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003399 ImplicitConversionSequence::CompareKind Result =
3400 ImplicitConversionSequence::Indistinguishable;
3401
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003402 // Two implicit conversion sequences of the same form are
3403 // indistinguishable conversion sequences unless one of the
3404 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003405
3406 // List-initialization sequence L1 is a better conversion sequence than
3407 // list-initialization sequence L2 if:
3408 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3409 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003410 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003411 // and N1 is smaller than N2.,
3412 // even if one of the other rules in this paragraph would otherwise apply.
3413 if (!ICS1.isBad()) {
3414 if (ICS1.isStdInitializerListElement() &&
3415 !ICS2.isStdInitializerListElement())
3416 return ImplicitConversionSequence::Better;
3417 if (!ICS1.isStdInitializerListElement() &&
3418 ICS2.isStdInitializerListElement())
3419 return ImplicitConversionSequence::Worse;
3420 }
3421
John McCall0d1da222010-01-12 00:44:57 +00003422 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003423 // Standard conversion sequence S1 is a better conversion sequence than
3424 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003425 Result = CompareStandardConversionSequences(S,
3426 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003427 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003428 // User-defined conversion sequence U1 is a better conversion
3429 // sequence than another user-defined conversion sequence U2 if
3430 // they contain the same user-defined conversion function or
3431 // constructor and if the second standard conversion sequence of
3432 // U1 is better than the second standard conversion sequence of
3433 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003434 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003435 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003436 Result = CompareStandardConversionSequences(S,
3437 ICS1.UserDefined.After,
3438 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003439 else
3440 Result = compareConversionFunctions(S,
3441 ICS1.UserDefined.ConversionFunction,
3442 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003443 }
3444
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003445 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003446}
3447
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003448static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3449 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3450 Qualifiers Quals;
3451 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003455 return Context.hasSameUnqualifiedType(T1, T2);
3456}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003458// Per 13.3.3.2p3, compare the given standard conversion sequences to
3459// determine if one is a proper subset of the other.
3460static ImplicitConversionSequence::CompareKind
3461compareStandardConversionSubsets(ASTContext &Context,
3462 const StandardConversionSequence& SCS1,
3463 const StandardConversionSequence& SCS2) {
3464 ImplicitConversionSequence::CompareKind Result
3465 = ImplicitConversionSequence::Indistinguishable;
3466
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003468 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003469 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3470 return ImplicitConversionSequence::Better;
3471 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3472 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003474 if (SCS1.Second != SCS2.Second) {
3475 if (SCS1.Second == ICK_Identity)
3476 Result = ImplicitConversionSequence::Better;
3477 else if (SCS2.Second == ICK_Identity)
3478 Result = ImplicitConversionSequence::Worse;
3479 else
3480 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003481 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003482 return ImplicitConversionSequence::Indistinguishable;
3483
3484 if (SCS1.Third == SCS2.Third) {
3485 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3486 : ImplicitConversionSequence::Indistinguishable;
3487 }
3488
3489 if (SCS1.Third == ICK_Identity)
3490 return Result == ImplicitConversionSequence::Worse
3491 ? ImplicitConversionSequence::Indistinguishable
3492 : ImplicitConversionSequence::Better;
3493
3494 if (SCS2.Third == ICK_Identity)
3495 return Result == ImplicitConversionSequence::Better
3496 ? ImplicitConversionSequence::Indistinguishable
3497 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003499 return ImplicitConversionSequence::Indistinguishable;
3500}
3501
Douglas Gregore696ebb2011-01-26 14:52:12 +00003502/// \brief Determine whether one of the given reference bindings is better
3503/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003504static bool
3505isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3506 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003507 // C++0x [over.ics.rank]p3b4:
3508 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3509 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003511 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003513 // reference*.
3514 //
3515 // FIXME: Rvalue references. We're going rogue with the above edits,
3516 // because the semantics in the current C++0x working paper (N3225 at the
3517 // time of this writing) break the standard definition of std::forward
3518 // and std::reference_wrapper when dealing with references to functions.
3519 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003520 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3521 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3522 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
Douglas Gregore696ebb2011-01-26 14:52:12 +00003524 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3525 SCS2.IsLvalueReference) ||
3526 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003527 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003528}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003530/// CompareStandardConversionSequences - Compare two standard
3531/// conversion sequences to determine whether one is better than the
3532/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003533static ImplicitConversionSequence::CompareKind
3534CompareStandardConversionSequences(Sema &S,
3535 const StandardConversionSequence& SCS1,
3536 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003537{
3538 // Standard conversion sequence S1 is a better conversion sequence
3539 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3540
3541 // -- S1 is a proper subsequence of S2 (comparing the conversion
3542 // sequences in the canonical form defined by 13.3.3.1.1,
3543 // excluding any Lvalue Transformation; the identity conversion
3544 // sequence is considered to be a subsequence of any
3545 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003546 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003547 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003548 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003549
3550 // -- the rank of S1 is better than the rank of S2 (by the rules
3551 // defined below), or, if not that,
3552 ImplicitConversionRank Rank1 = SCS1.getRank();
3553 ImplicitConversionRank Rank2 = SCS2.getRank();
3554 if (Rank1 < Rank2)
3555 return ImplicitConversionSequence::Better;
3556 else if (Rank2 < Rank1)
3557 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003558
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3560 // are indistinguishable unless one of the following rules
3561 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003562
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003563 // A conversion that is not a conversion of a pointer, or
3564 // pointer to member, to bool is better than another conversion
3565 // that is such a conversion.
3566 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3567 return SCS2.isPointerConversionToBool()
3568 ? ImplicitConversionSequence::Better
3569 : ImplicitConversionSequence::Worse;
3570
Douglas Gregor5c407d92008-10-23 00:40:37 +00003571 // C++ [over.ics.rank]p4b2:
3572 //
3573 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003574 // conversion of B* to A* is better than conversion of B* to
3575 // void*, and conversion of A* to void* is better than conversion
3576 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003577 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003578 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003579 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003580 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003581 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3582 // Exactly one of the conversion sequences is a conversion to
3583 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003584 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3585 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003586 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3587 // Neither conversion sequence converts to a void pointer; compare
3588 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003589 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003590 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003591 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003592 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3593 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003594 // Both conversion sequences are conversions to void
3595 // pointers. Compare the source types to determine if there's an
3596 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003597 QualType FromType1 = SCS1.getFromType();
3598 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003599
3600 // Adjust the types we're converting from via the array-to-pointer
3601 // conversion, if we need to.
3602 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003603 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003604 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003605 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003606
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003607 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3608 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003609
John McCall5c32be02010-08-24 20:38:10 +00003610 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003611 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003612 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003613 return ImplicitConversionSequence::Worse;
3614
3615 // Objective-C++: If one interface is more specific than the
3616 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003617 const ObjCObjectPointerType* FromObjCPtr1
3618 = FromType1->getAs<ObjCObjectPointerType>();
3619 const ObjCObjectPointerType* FromObjCPtr2
3620 = FromType2->getAs<ObjCObjectPointerType>();
3621 if (FromObjCPtr1 && FromObjCPtr2) {
3622 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3623 FromObjCPtr2);
3624 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3625 FromObjCPtr1);
3626 if (AssignLeft != AssignRight) {
3627 return AssignLeft? ImplicitConversionSequence::Better
3628 : ImplicitConversionSequence::Worse;
3629 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003630 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003631 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003632
3633 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3634 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003635 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003636 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003637 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003638
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003639 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003640 // Check for a better reference binding based on the kind of bindings.
3641 if (isBetterReferenceBindingKind(SCS1, SCS2))
3642 return ImplicitConversionSequence::Better;
3643 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3644 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645
Sebastian Redlb28b4072009-03-22 23:49:27 +00003646 // C++ [over.ics.rank]p3b4:
3647 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3648 // which the references refer are the same type except for
3649 // top-level cv-qualifiers, and the type to which the reference
3650 // initialized by S2 refers is more cv-qualified than the type
3651 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003652 QualType T1 = SCS1.getToType(2);
3653 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003654 T1 = S.Context.getCanonicalType(T1);
3655 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003656 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003657 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3658 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003659 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003660 // Objective-C++ ARC: If the references refer to objects with different
3661 // lifetimes, prefer bindings that don't change lifetime.
3662 if (SCS1.ObjCLifetimeConversionBinding !=
3663 SCS2.ObjCLifetimeConversionBinding) {
3664 return SCS1.ObjCLifetimeConversionBinding
3665 ? ImplicitConversionSequence::Worse
3666 : ImplicitConversionSequence::Better;
3667 }
3668
Chandler Carruth8e543b32010-12-12 08:17:55 +00003669 // If the type is an array type, promote the element qualifiers to the
3670 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003671 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003672 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003673 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003674 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003675 if (T2.isMoreQualifiedThan(T1))
3676 return ImplicitConversionSequence::Better;
3677 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003678 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003679 }
3680 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003681
Francois Pichet08d2fa02011-09-18 21:37:37 +00003682 // In Microsoft mode, prefer an integral conversion to a
3683 // floating-to-integral conversion if the integral conversion
3684 // is between types of the same size.
3685 // For example:
3686 // void f(float);
3687 // void f(int);
3688 // int main {
3689 // long a;
3690 // f(a);
3691 // }
3692 // Here, MSVC will call f(int) instead of generating a compile error
3693 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003694 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3695 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003696 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003697 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003698 return ImplicitConversionSequence::Better;
3699
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003700 return ImplicitConversionSequence::Indistinguishable;
3701}
3702
3703/// CompareQualificationConversions - Compares two standard conversion
3704/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003705/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003706static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003707CompareQualificationConversions(Sema &S,
3708 const StandardConversionSequence& SCS1,
3709 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003710 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003711 // -- S1 and S2 differ only in their qualification conversion and
3712 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3713 // cv-qualification signature of type T1 is a proper subset of
3714 // the cv-qualification signature of type T2, and S1 is not the
3715 // deprecated string literal array-to-pointer conversion (4.2).
3716 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3717 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3718 return ImplicitConversionSequence::Indistinguishable;
3719
3720 // FIXME: the example in the standard doesn't use a qualification
3721 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003722 QualType T1 = SCS1.getToType(2);
3723 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003724 T1 = S.Context.getCanonicalType(T1);
3725 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003726 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003727 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3728 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729
3730 // If the types are the same, we won't learn anything by unwrapped
3731 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003732 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003733 return ImplicitConversionSequence::Indistinguishable;
3734
Chandler Carruth607f38e2009-12-29 07:16:59 +00003735 // If the type is an array type, promote the element qualifiers to the type
3736 // for comparison.
3737 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003738 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003739 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003740 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003741
Mike Stump11289f42009-09-09 15:08:12 +00003742 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003743 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003744
3745 // Objective-C++ ARC:
3746 // Prefer qualification conversions not involving a change in lifetime
3747 // to qualification conversions that do not change lifetime.
3748 if (SCS1.QualificationIncludesObjCLifetime !=
3749 SCS2.QualificationIncludesObjCLifetime) {
3750 Result = SCS1.QualificationIncludesObjCLifetime
3751 ? ImplicitConversionSequence::Worse
3752 : ImplicitConversionSequence::Better;
3753 }
3754
John McCall5c32be02010-08-24 20:38:10 +00003755 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003756 // Within each iteration of the loop, we check the qualifiers to
3757 // determine if this still looks like a qualification
3758 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003759 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003760 // until there are no more pointers or pointers-to-members left
3761 // to unwrap. This essentially mimics what
3762 // IsQualificationConversion does, but here we're checking for a
3763 // strict subset of qualifiers.
3764 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3765 // The qualifiers are the same, so this doesn't tell us anything
3766 // about how the sequences rank.
3767 ;
3768 else if (T2.isMoreQualifiedThan(T1)) {
3769 // T1 has fewer qualifiers, so it could be the better sequence.
3770 if (Result == ImplicitConversionSequence::Worse)
3771 // Neither has qualifiers that are a subset of the other's
3772 // qualifiers.
3773 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003774
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003775 Result = ImplicitConversionSequence::Better;
3776 } else if (T1.isMoreQualifiedThan(T2)) {
3777 // T2 has fewer qualifiers, so it could be the better sequence.
3778 if (Result == ImplicitConversionSequence::Better)
3779 // Neither has qualifiers that are a subset of the other's
3780 // qualifiers.
3781 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003782
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003783 Result = ImplicitConversionSequence::Worse;
3784 } else {
3785 // Qualifiers are disjoint.
3786 return ImplicitConversionSequence::Indistinguishable;
3787 }
3788
3789 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003790 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003791 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003792 }
3793
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003794 // Check that the winning standard conversion sequence isn't using
3795 // the deprecated string literal array to pointer conversion.
3796 switch (Result) {
3797 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003798 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003799 Result = ImplicitConversionSequence::Indistinguishable;
3800 break;
3801
3802 case ImplicitConversionSequence::Indistinguishable:
3803 break;
3804
3805 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003806 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003807 Result = ImplicitConversionSequence::Indistinguishable;
3808 break;
3809 }
3810
3811 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003812}
3813
Douglas Gregor5c407d92008-10-23 00:40:37 +00003814/// CompareDerivedToBaseConversions - Compares two standard conversion
3815/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003816/// various kinds of derived-to-base conversions (C++
3817/// [over.ics.rank]p4b3). As part of these checks, we also look at
3818/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003819static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003820CompareDerivedToBaseConversions(Sema &S,
3821 const StandardConversionSequence& SCS1,
3822 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003823 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003824 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003825 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003826 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003827
3828 // Adjust the types we're converting from via the array-to-pointer
3829 // conversion, if we need to.
3830 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003831 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003832 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003833 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003834
3835 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003836 FromType1 = S.Context.getCanonicalType(FromType1);
3837 ToType1 = S.Context.getCanonicalType(ToType1);
3838 FromType2 = S.Context.getCanonicalType(FromType2);
3839 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003840
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003841 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003842 //
3843 // If class B is derived directly or indirectly from class A and
3844 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003845 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003846 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003847 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003848 SCS2.Second == ICK_Pointer_Conversion &&
3849 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3850 FromType1->isPointerType() && FromType2->isPointerType() &&
3851 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003852 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003853 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003854 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003855 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003856 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003857 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003858 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003859 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003860
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003861 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003862 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003863 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003864 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003865 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003866 return ImplicitConversionSequence::Worse;
3867 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003868
3869 // -- conversion of B* to A* is better than conversion of C* to A*,
3870 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003871 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003872 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003873 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003874 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003875 }
3876 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3877 SCS2.Second == ICK_Pointer_Conversion) {
3878 const ObjCObjectPointerType *FromPtr1
3879 = FromType1->getAs<ObjCObjectPointerType>();
3880 const ObjCObjectPointerType *FromPtr2
3881 = FromType2->getAs<ObjCObjectPointerType>();
3882 const ObjCObjectPointerType *ToPtr1
3883 = ToType1->getAs<ObjCObjectPointerType>();
3884 const ObjCObjectPointerType *ToPtr2
3885 = ToType2->getAs<ObjCObjectPointerType>();
3886
3887 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3888 // Apply the same conversion ranking rules for Objective-C pointer types
3889 // that we do for C++ pointers to class types. However, we employ the
3890 // Objective-C pseudo-subtyping relationship used for assignment of
3891 // Objective-C pointer types.
3892 bool FromAssignLeft
3893 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3894 bool FromAssignRight
3895 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3896 bool ToAssignLeft
3897 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3898 bool ToAssignRight
3899 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3900
3901 // A conversion to an a non-id object pointer type or qualified 'id'
3902 // type is better than a conversion to 'id'.
3903 if (ToPtr1->isObjCIdType() &&
3904 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3905 return ImplicitConversionSequence::Worse;
3906 if (ToPtr2->isObjCIdType() &&
3907 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3908 return ImplicitConversionSequence::Better;
3909
3910 // A conversion to a non-id object pointer type is better than a
3911 // conversion to a qualified 'id' type
3912 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3913 return ImplicitConversionSequence::Worse;
3914 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3915 return ImplicitConversionSequence::Better;
3916
3917 // A conversion to an a non-Class object pointer type or qualified 'Class'
3918 // type is better than a conversion to 'Class'.
3919 if (ToPtr1->isObjCClassType() &&
3920 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3921 return ImplicitConversionSequence::Worse;
3922 if (ToPtr2->isObjCClassType() &&
3923 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3924 return ImplicitConversionSequence::Better;
3925
3926 // A conversion to a non-Class object pointer type is better than a
3927 // conversion to a qualified 'Class' type.
3928 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3929 return ImplicitConversionSequence::Worse;
3930 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3931 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003932
Douglas Gregor058d3de2011-01-31 18:51:41 +00003933 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3934 if (S.Context.hasSameType(FromType1, FromType2) &&
3935 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3936 (ToAssignLeft != ToAssignRight))
3937 return ToAssignLeft? ImplicitConversionSequence::Worse
3938 : ImplicitConversionSequence::Better;
3939
3940 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3941 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3942 (FromAssignLeft != FromAssignRight))
3943 return FromAssignLeft? ImplicitConversionSequence::Better
3944 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003945 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003946 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003947
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003948 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003949 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3950 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3951 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003953 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003955 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003957 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003959 ToType2->getAs<MemberPointerType>();
3960 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3961 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3962 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3963 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3964 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3965 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3966 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3967 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003968 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003969 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003970 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003971 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003972 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003973 return ImplicitConversionSequence::Better;
3974 }
3975 // conversion of B::* to C::* is better than conversion of A::* to C::*
3976 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003977 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003978 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003979 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003980 return ImplicitConversionSequence::Worse;
3981 }
3982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Douglas Gregor5ab11652010-04-17 22:01:05 +00003984 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003985 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003986 // -- binding of an expression of type C to a reference of type
3987 // B& is better than binding an expression of type C to a
3988 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003989 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3990 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3991 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003992 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003993 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003994 return ImplicitConversionSequence::Worse;
3995 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003996
Douglas Gregor2fe98832008-11-03 19:09:14 +00003997 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003998 // -- binding of an expression of type B to a reference of type
3999 // A& is better than binding an expression of type C to a
4000 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004001 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4002 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4003 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004004 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00004005 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004006 return ImplicitConversionSequence::Worse;
4007 }
4008 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004009
Douglas Gregor5c407d92008-10-23 00:40:37 +00004010 return ImplicitConversionSequence::Indistinguishable;
4011}
4012
Douglas Gregor45bb4832013-03-26 23:36:30 +00004013/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4014/// C++ class.
4015static bool isTypeValid(QualType T) {
4016 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4017 return !Record->isInvalidDecl();
4018
4019 return true;
4020}
4021
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004022/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4023/// determine whether they are reference-related,
4024/// reference-compatible, reference-compatible with added
4025/// qualification, or incompatible, for use in C++ initialization by
4026/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4027/// type, and the first type (T1) is the pointee type of the reference
4028/// type being initialized.
4029Sema::ReferenceCompareResult
4030Sema::CompareReferenceRelationship(SourceLocation Loc,
4031 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004032 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004033 bool &ObjCConversion,
4034 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004035 assert(!OrigT1->isReferenceType() &&
4036 "T1 must be the pointee type of the reference type");
4037 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4038
4039 QualType T1 = Context.getCanonicalType(OrigT1);
4040 QualType T2 = Context.getCanonicalType(OrigT2);
4041 Qualifiers T1Quals, T2Quals;
4042 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4043 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4044
4045 // C++ [dcl.init.ref]p4:
4046 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4047 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4048 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004049 DerivedToBase = false;
4050 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004051 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004052 if (UnqualT1 == UnqualT2) {
4053 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004054 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004055 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4056 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004057 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004058 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4059 UnqualT2->isObjCObjectOrInterfaceType() &&
4060 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4061 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004062 else
4063 return Ref_Incompatible;
4064
4065 // At this point, we know that T1 and T2 are reference-related (at
4066 // least).
4067
4068 // If the type is an array type, promote the element qualifiers to the type
4069 // for comparison.
4070 if (isa<ArrayType>(T1) && T1Quals)
4071 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4072 if (isa<ArrayType>(T2) && T2Quals)
4073 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4074
4075 // C++ [dcl.init.ref]p4:
4076 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4077 // reference-related to T2 and cv1 is the same cv-qualification
4078 // as, or greater cv-qualification than, cv2. For purposes of
4079 // overload resolution, cases for which cv1 is greater
4080 // cv-qualification than cv2 are identified as
4081 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004082 //
4083 // Note that we also require equivalence of Objective-C GC and address-space
4084 // qualifiers when performing these computations, so that e.g., an int in
4085 // address space 1 is not reference-compatible with an int in address
4086 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004087 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4088 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004089 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4090 ObjCLifetimeConversion = true;
4091
John McCall31168b02011-06-15 23:02:42 +00004092 T1Quals.removeObjCLifetime();
4093 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004094 }
4095
Douglas Gregord517d552011-04-28 17:56:11 +00004096 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004097 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004098 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004099 return Ref_Compatible_With_Added_Qualification;
4100 else
4101 return Ref_Related;
4102}
4103
Douglas Gregor836a7e82010-08-11 02:15:33 +00004104/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004105/// with DeclType. Return true if something definite is found.
4106static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004107FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4108 QualType DeclType, SourceLocation DeclLoc,
4109 Expr *Init, QualType T2, bool AllowRvalues,
4110 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004111 assert(T2->isRecordType() && "Can only find conversions of record types.");
4112 CXXRecordDecl *T2RecordDecl
4113 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4114
Richard Smith100b24a2014-04-17 01:52:14 +00004115 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004116 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4117 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004118 NamedDecl *D = *I;
4119 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4120 if (isa<UsingShadowDecl>(D))
4121 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4122
4123 FunctionTemplateDecl *ConvTemplate
4124 = dyn_cast<FunctionTemplateDecl>(D);
4125 CXXConversionDecl *Conv;
4126 if (ConvTemplate)
4127 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4128 else
4129 Conv = cast<CXXConversionDecl>(D);
4130
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004132 // explicit conversions, skip it.
4133 if (!AllowExplicit && Conv->isExplicit())
4134 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135
Douglas Gregor836a7e82010-08-11 02:15:33 +00004136 if (AllowRvalues) {
4137 bool DerivedToBase = false;
4138 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004139 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004140
4141 // If we are initializing an rvalue reference, don't permit conversion
4142 // functions that return lvalues.
4143 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4144 const ReferenceType *RefType
4145 = Conv->getConversionType()->getAs<LValueReferenceType>();
4146 if (RefType && !RefType->getPointeeType()->isFunctionType())
4147 continue;
4148 }
4149
Douglas Gregor836a7e82010-08-11 02:15:33 +00004150 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004151 S.CompareReferenceRelationship(
4152 DeclLoc,
4153 Conv->getConversionType().getNonReferenceType()
4154 .getUnqualifiedType(),
4155 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004156 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004157 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004158 continue;
4159 } else {
4160 // If the conversion function doesn't return a reference type,
4161 // it can't be considered for this conversion. An rvalue reference
4162 // is only acceptable if its referencee is a function type.
4163
4164 const ReferenceType *RefType =
4165 Conv->getConversionType()->getAs<ReferenceType>();
4166 if (!RefType ||
4167 (!RefType->isLValueReferenceType() &&
4168 !RefType->getPointeeType()->isFunctionType()))
4169 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171
Douglas Gregor836a7e82010-08-11 02:15:33 +00004172 if (ConvTemplate)
4173 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004174 Init, DeclType, CandidateSet,
4175 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004176 else
4177 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004178 DeclType, CandidateSet,
4179 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004180 }
4181
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004182 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4183
Sebastian Redld92badf2010-06-30 18:13:39 +00004184 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004185 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004186 case OR_Success:
4187 // C++ [over.ics.ref]p1:
4188 //
4189 // [...] If the parameter binds directly to the result of
4190 // applying a conversion function to the argument
4191 // expression, the implicit conversion sequence is a
4192 // user-defined conversion sequence (13.3.3.1.2), with the
4193 // second standard conversion sequence either an identity
4194 // conversion or, if the conversion function returns an
4195 // entity of a type that is a derived class of the parameter
4196 // type, a derived-to-base Conversion.
4197 if (!Best->FinalConversion.DirectBinding)
4198 return false;
4199
4200 ICS.setUserDefined();
4201 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4202 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004203 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004204 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004205 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004206 ICS.UserDefined.EllipsisConversion = false;
4207 assert(ICS.UserDefined.After.ReferenceBinding &&
4208 ICS.UserDefined.After.DirectBinding &&
4209 "Expected a direct reference binding!");
4210 return true;
4211
4212 case OR_Ambiguous:
4213 ICS.setAmbiguous();
4214 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4215 Cand != CandidateSet.end(); ++Cand)
4216 if (Cand->Viable)
4217 ICS.Ambiguous.addConversion(Cand->Function);
4218 return true;
4219
4220 case OR_No_Viable_Function:
4221 case OR_Deleted:
4222 // There was no suitable conversion, or we found a deleted
4223 // conversion; continue with other checks.
4224 return false;
4225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
David Blaikie8a40f702012-01-17 06:56:22 +00004227 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004228}
4229
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004230/// \brief Compute an implicit conversion sequence for reference
4231/// initialization.
4232static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004233TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004234 SourceLocation DeclLoc,
4235 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004236 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004237 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4238
4239 // Most paths end in a failed conversion.
4240 ImplicitConversionSequence ICS;
4241 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4242
4243 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4244 QualType T2 = Init->getType();
4245
4246 // If the initializer is the address of an overloaded function, try
4247 // to resolve the overloaded function. If all goes well, T2 is the
4248 // type of the resulting function.
4249 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4250 DeclAccessPair Found;
4251 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4252 false, Found))
4253 T2 = Fn->getType();
4254 }
4255
4256 // Compute some basic properties of the types and the initializer.
4257 bool isRValRef = DeclType->isRValueReferenceType();
4258 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004259 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004260 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004261 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004263 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004264 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004265
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004266
Sebastian Redld92badf2010-06-30 18:13:39 +00004267 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004268 // A reference to type "cv1 T1" is initialized by an expression
4269 // of type "cv2 T2" as follows:
4270
Sebastian Redld92badf2010-06-30 18:13:39 +00004271 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004272 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004273 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4274 // reference-compatible with "cv2 T2," or
4275 //
4276 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4277 if (InitCategory.isLValue() &&
4278 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004279 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004280 // When a parameter of reference type binds directly (8.5.3)
4281 // to an argument expression, the implicit conversion sequence
4282 // is the identity conversion, unless the argument expression
4283 // has a type that is a derived class of the parameter type,
4284 // in which case the implicit conversion sequence is a
4285 // derived-to-base Conversion (13.3.3.1).
4286 ICS.setStandard();
4287 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004288 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4289 : ObjCConversion? ICK_Compatible_Conversion
4290 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004291 ICS.Standard.Third = ICK_Identity;
4292 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4293 ICS.Standard.setToType(0, T2);
4294 ICS.Standard.setToType(1, T1);
4295 ICS.Standard.setToType(2, T1);
4296 ICS.Standard.ReferenceBinding = true;
4297 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004298 ICS.Standard.IsLvalueReference = !isRValRef;
4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4300 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004303 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004304 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004305
Sebastian Redld92badf2010-06-30 18:13:39 +00004306 // Nothing more to do: the inaccessibility/ambiguity check for
4307 // derived-to-base conversions is suppressed when we're
4308 // computing the implicit conversion sequence (C++
4309 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004310 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004311 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004312
Sebastian Redld92badf2010-06-30 18:13:39 +00004313 // -- has a class type (i.e., T2 is a class type), where T1 is
4314 // not reference-related to T2, and can be implicitly
4315 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4316 // is reference-compatible with "cv3 T3" 92) (this
4317 // conversion is selected by enumerating the applicable
4318 // conversion functions (13.3.1.6) and choosing the best
4319 // one through overload resolution (13.3)),
4320 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004322 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004323 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4324 Init, T2, /*AllowRvalues=*/false,
4325 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004326 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004327 }
4328 }
4329
Sebastian Redld92badf2010-06-30 18:13:39 +00004330 // -- Otherwise, the reference shall be an lvalue reference to a
4331 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004332 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004333 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004334 return ICS;
4335
Douglas Gregorf143cd52011-01-24 16:14:37 +00004336 // -- If the initializer expression
4337 //
4338 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004339 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004340 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4341 (InitCategory.isXValue() ||
4342 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4343 (InitCategory.isLValue() && T2->isFunctionType()))) {
4344 ICS.setStandard();
4345 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004347 : ObjCConversion? ICK_Compatible_Conversion
4348 : ICK_Identity;
4349 ICS.Standard.Third = ICK_Identity;
4350 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4351 ICS.Standard.setToType(0, T2);
4352 ICS.Standard.setToType(1, T1);
4353 ICS.Standard.setToType(2, T1);
4354 ICS.Standard.ReferenceBinding = true;
4355 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4356 // binding unless we're binding to a class prvalue.
4357 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4358 // allow the use of rvalue references in C++98/03 for the benefit of
4359 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004361 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004362 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004363 ICS.Standard.IsLvalueReference = !isRValRef;
4364 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004366 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004367 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004368 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004369 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372
Douglas Gregorf143cd52011-01-24 16:14:37 +00004373 // -- has a class type (i.e., T2 is a class type), where T1 is not
4374 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 // an xvalue, class prvalue, or function lvalue of type
4376 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004377 // "cv3 T3",
4378 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004380 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004382 // class subobject).
4383 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004385 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4386 Init, T2, /*AllowRvalues=*/true,
4387 AllowExplicit)) {
4388 // In the second case, if the reference is an rvalue reference
4389 // and the second standard conversion sequence of the
4390 // user-defined conversion sequence includes an lvalue-to-rvalue
4391 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004393 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4394 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4395
Douglas Gregor95273c32011-01-21 16:36:05 +00004396 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Richard Smith19172c42014-07-14 02:28:44 +00004399 // A temporary of function type cannot be created; don't even try.
4400 if (T1->isFunctionType())
4401 return ICS;
4402
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004403 // -- Otherwise, a temporary of type "cv1 T1" is created and
4404 // initialized from the initializer expression using the
4405 // rules for a non-reference copy initialization (8.5). The
4406 // reference is then bound to the temporary. If T1 is
4407 // reference-related to T2, cv1 must be the same
4408 // cv-qualification as, or greater cv-qualification than,
4409 // cv2; otherwise, the program is ill-formed.
4410 if (RefRelationship == Sema::Ref_Related) {
4411 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4412 // we would be reference-compatible or reference-compatible with
4413 // added qualification. But that wasn't the case, so the reference
4414 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004415 //
4416 // Note that we only want to check address spaces and cvr-qualifiers here.
4417 // ObjC GC and lifetime qualifiers aren't important.
4418 Qualifiers T1Quals = T1.getQualifiers();
4419 Qualifiers T2Quals = T2.getQualifiers();
4420 T1Quals.removeObjCGCAttr();
4421 T1Quals.removeObjCLifetime();
4422 T2Quals.removeObjCGCAttr();
4423 T2Quals.removeObjCLifetime();
4424 if (!T1Quals.compatiblyIncludes(T2Quals))
4425 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004426 }
4427
4428 // If at least one of the types is a class type, the types are not
4429 // related, and we aren't allowed any user conversions, the
4430 // reference binding fails. This case is important for breaking
4431 // recursion, since TryImplicitConversion below will attempt to
4432 // create a temporary through the use of a copy constructor.
4433 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4434 (T1->isRecordType() || T2->isRecordType()))
4435 return ICS;
4436
Douglas Gregorcba72b12011-01-21 05:18:22 +00004437 // If T1 is reference-related to T2 and the reference is an rvalue
4438 // reference, the initializer expression shall not be an lvalue.
4439 if (RefRelationship >= Sema::Ref_Related &&
4440 isRValRef && Init->Classify(S.Context).isLValue())
4441 return ICS;
4442
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004443 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004444 // When a parameter of reference type is not bound directly to
4445 // an argument expression, the conversion sequence is the one
4446 // required to convert the argument expression to the
4447 // underlying type of the reference according to
4448 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4449 // to copy-initializing a temporary of the underlying type with
4450 // the argument expression. Any difference in top-level
4451 // cv-qualification is subsumed by the initialization itself
4452 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004453 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4454 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004455 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004456 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004457 /*AllowObjCWritebackConversion=*/false,
4458 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004459
4460 // Of course, that's still a reference binding.
4461 if (ICS.isStandard()) {
4462 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004463 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004464 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004465 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004466 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004467 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004468 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004469 const ReferenceType *LValRefType =
4470 ICS.UserDefined.ConversionFunction->getReturnType()
4471 ->getAs<LValueReferenceType>();
4472
4473 // C++ [over.ics.ref]p3:
4474 // Except for an implicit object parameter, for which see 13.3.1, a
4475 // standard conversion sequence cannot be formed if it requires [...]
4476 // binding an rvalue reference to an lvalue other than a function
4477 // lvalue.
4478 // Note that the function case is not possible here.
4479 if (DeclType->isRValueReferenceType() && LValRefType) {
4480 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4481 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4482 // reference to an rvalue!
4483 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4484 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004485 }
Richard Smith19172c42014-07-14 02:28:44 +00004486
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004487 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004488 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004489 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004490 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4491 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004492 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4493 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004494 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004495
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004496 return ICS;
4497}
4498
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004499static ImplicitConversionSequence
4500TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4501 bool SuppressUserConversions,
4502 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004503 bool AllowObjCWritebackConversion,
4504 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004505
4506/// TryListConversion - Try to copy-initialize a value of type ToType from the
4507/// initializer list From.
4508static ImplicitConversionSequence
4509TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4510 bool SuppressUserConversions,
4511 bool InOverloadResolution,
4512 bool AllowObjCWritebackConversion) {
4513 // C++11 [over.ics.list]p1:
4514 // When an argument is an initializer list, it is not an expression and
4515 // special rules apply for converting it to a parameter type.
4516
4517 ImplicitConversionSequence Result;
4518 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4519
Sebastian Redl09edce02012-01-23 22:09:39 +00004520 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004521 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004522 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004523 return Result;
4524
Larisse Voufo19d08672015-01-27 18:47:05 +00004525 // Per DR1467:
4526 // If the parameter type is a class X and the initializer list has a single
4527 // element of type cv U, where U is X or a class derived from X, the
4528 // implicit conversion sequence is the one required to convert the element
4529 // to the parameter type.
4530 //
4531 // Otherwise, if the parameter type is a character array [... ]
4532 // and the initializer list has a single element that is an
4533 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4534 // implicit conversion sequence is the identity conversion.
4535 if (From->getNumInits() == 1) {
4536 if (ToType->isRecordType()) {
4537 QualType InitType = From->getInit(0)->getType();
4538 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4539 S.IsDerivedFrom(InitType, ToType))
4540 return TryCopyInitialization(S, From->getInit(0), ToType,
4541 SuppressUserConversions,
4542 InOverloadResolution,
4543 AllowObjCWritebackConversion);
4544 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004545 // FIXME: Check the other conditions here: array of character type,
4546 // initializer is a string literal.
4547 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004548 InitializedEntity Entity =
4549 InitializedEntity::InitializeParameter(S.Context, ToType,
4550 /*Consumed=*/false);
4551 if (S.CanPerformCopyInitialization(Entity, From)) {
4552 Result.setStandard();
4553 Result.Standard.setAsIdentityConversion();
4554 Result.Standard.setFromType(ToType);
4555 Result.Standard.setAllToTypes(ToType);
4556 return Result;
4557 }
4558 }
4559 }
4560
4561 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004562 // C++11 [over.ics.list]p2:
4563 // If the parameter type is std::initializer_list<X> or "array of X" and
4564 // all the elements can be implicitly converted to X, the implicit
4565 // conversion sequence is the worst conversion necessary to convert an
4566 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004567 //
4568 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004569 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004570 // list has exactly N elements or if it has fewer than N elements and X is
4571 // default-constructible, and if all the elements of the initializer list
4572 // can be implicitly converted to X, the implicit conversion sequence is
4573 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004574 //
4575 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004576 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004577 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004578 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004579 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004580 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004581 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004582 if (!X.isNull()) {
4583 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4584 Expr *Init = From->getInit(i);
4585 ImplicitConversionSequence ICS =
4586 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4587 InOverloadResolution,
4588 AllowObjCWritebackConversion);
4589 // If a single element isn't convertible, fail.
4590 if (ICS.isBad()) {
4591 Result = ICS;
4592 break;
4593 }
4594 // Otherwise, look for the worst conversion.
4595 if (Result.isBad() ||
4596 CompareImplicitConversionSequences(S, ICS, Result) ==
4597 ImplicitConversionSequence::Worse)
4598 Result = ICS;
4599 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004600
4601 // For an empty list, we won't have computed any conversion sequence.
4602 // Introduce the identity conversion sequence.
4603 if (From->getNumInits() == 0) {
4604 Result.setStandard();
4605 Result.Standard.setAsIdentityConversion();
4606 Result.Standard.setFromType(ToType);
4607 Result.Standard.setAllToTypes(ToType);
4608 }
4609
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004610 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004611 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004612 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004613
Larisse Voufo19d08672015-01-27 18:47:05 +00004614 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004615 // C++11 [over.ics.list]p3:
4616 // Otherwise, if the parameter is a non-aggregate class X and overload
4617 // resolution chooses a single best constructor [...] the implicit
4618 // conversion sequence is a user-defined conversion sequence. If multiple
4619 // constructors are viable but none is better than the others, the
4620 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004621 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4622 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004623 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4624 /*AllowExplicit=*/false,
4625 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004626 AllowObjCWritebackConversion,
4627 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004628 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004629
Larisse Voufo19d08672015-01-27 18:47:05 +00004630 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004631 // C++11 [over.ics.list]p4:
4632 // Otherwise, if the parameter has an aggregate type which can be
4633 // initialized from the initializer list [...] the implicit conversion
4634 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004635 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004636 // Type is an aggregate, argument is an init list. At this point it comes
4637 // down to checking whether the initialization works.
4638 // FIXME: Find out whether this parameter is consumed or not.
4639 InitializedEntity Entity =
4640 InitializedEntity::InitializeParameter(S.Context, ToType,
4641 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004642 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004643 Result.setUserDefined();
4644 Result.UserDefined.Before.setAsIdentityConversion();
4645 // Initializer lists don't have a type.
4646 Result.UserDefined.Before.setFromType(QualType());
4647 Result.UserDefined.Before.setAllToTypes(QualType());
4648
4649 Result.UserDefined.After.setAsIdentityConversion();
4650 Result.UserDefined.After.setFromType(ToType);
4651 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004652 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004653 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004654 return Result;
4655 }
4656
Larisse Voufo19d08672015-01-27 18:47:05 +00004657 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004658 // C++11 [over.ics.list]p5:
4659 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004660 if (ToType->isReferenceType()) {
4661 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4662 // mention initializer lists in any way. So we go by what list-
4663 // initialization would do and try to extrapolate from that.
4664
4665 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4666
4667 // If the initializer list has a single element that is reference-related
4668 // to the parameter type, we initialize the reference from that.
4669 if (From->getNumInits() == 1) {
4670 Expr *Init = From->getInit(0);
4671
4672 QualType T2 = Init->getType();
4673
4674 // If the initializer is the address of an overloaded function, try
4675 // to resolve the overloaded function. If all goes well, T2 is the
4676 // type of the resulting function.
4677 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4678 DeclAccessPair Found;
4679 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4680 Init, ToType, false, Found))
4681 T2 = Fn->getType();
4682 }
4683
4684 // Compute some basic properties of the types and the initializer.
4685 bool dummy1 = false;
4686 bool dummy2 = false;
4687 bool dummy3 = false;
4688 Sema::ReferenceCompareResult RefRelationship
4689 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4690 dummy2, dummy3);
4691
Richard Smith4d2bbd72013-09-06 01:22:42 +00004692 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004693 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4694 SuppressUserConversions,
4695 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004696 }
Sebastian Redldf888642011-12-03 14:54:30 +00004697 }
4698
4699 // Otherwise, we bind the reference to a temporary created from the
4700 // initializer list.
4701 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4702 InOverloadResolution,
4703 AllowObjCWritebackConversion);
4704 if (Result.isFailure())
4705 return Result;
4706 assert(!Result.isEllipsis() &&
4707 "Sub-initialization cannot result in ellipsis conversion.");
4708
4709 // Can we even bind to a temporary?
4710 if (ToType->isRValueReferenceType() ||
4711 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4712 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4713 Result.UserDefined.After;
4714 SCS.ReferenceBinding = true;
4715 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4716 SCS.BindsToRvalue = true;
4717 SCS.BindsToFunctionLvalue = false;
4718 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4719 SCS.ObjCLifetimeConversionBinding = false;
4720 } else
4721 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4722 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004723 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004724 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004725
Larisse Voufo19d08672015-01-27 18:47:05 +00004726 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004727 // C++11 [over.ics.list]p6:
4728 // Otherwise, if the parameter type is not a class:
4729 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004730 // - if the initializer list has one element that is not itself an
4731 // initializer list, the implicit conversion sequence is the one
4732 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004733 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004734 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004735 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4736 SuppressUserConversions,
4737 InOverloadResolution,
4738 AllowObjCWritebackConversion);
4739 // - if the initializer list has no elements, the implicit conversion
4740 // sequence is the identity conversion.
4741 else if (NumInits == 0) {
4742 Result.setStandard();
4743 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004744 Result.Standard.setFromType(ToType);
4745 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004746 }
4747 return Result;
4748 }
4749
Larisse Voufo19d08672015-01-27 18:47:05 +00004750 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004751 // C++11 [over.ics.list]p7:
4752 // In all cases other than those enumerated above, no conversion is possible
4753 return Result;
4754}
4755
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004756/// TryCopyInitialization - Try to copy-initialize a value of type
4757/// ToType from the expression From. Return the implicit conversion
4758/// sequence required to pass this argument, which may be a bad
4759/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004760/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004761/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004762static ImplicitConversionSequence
4763TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004765 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004766 bool AllowObjCWritebackConversion,
4767 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004768 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4769 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4770 InOverloadResolution,AllowObjCWritebackConversion);
4771
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004772 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004773 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004774 /*FIXME:*/From->getLocStart(),
4775 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004776 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004777
John McCall5c32be02010-08-24 20:38:10 +00004778 return TryImplicitConversion(S, From, ToType,
4779 SuppressUserConversions,
4780 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004781 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004782 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004783 AllowObjCWritebackConversion,
4784 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004785}
4786
Anna Zaks1b068122011-07-28 19:46:48 +00004787static bool TryCopyInitialization(const CanQualType FromQTy,
4788 const CanQualType ToQTy,
4789 Sema &S,
4790 SourceLocation Loc,
4791 ExprValueKind FromVK) {
4792 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4793 ImplicitConversionSequence ICS =
4794 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4795
4796 return !ICS.isBad();
4797}
4798
Douglas Gregor436424c2008-11-18 23:14:02 +00004799/// TryObjectArgumentInitialization - Try to initialize the object
4800/// parameter of the given member function (@c Method) from the
4801/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004802static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004803TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004804 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004805 CXXMethodDecl *Method,
4806 CXXRecordDecl *ActingContext) {
4807 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004808 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4809 // const volatile object.
4810 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4811 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004812 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004813
4814 // Set up the conversion sequence as a "bad" conversion, to allow us
4815 // to exit early.
4816 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004817
4818 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004819 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004820 FromType = PT->getPointeeType();
4821
Douglas Gregor02824322011-01-26 19:30:28 +00004822 // When we had a pointer, it's implicitly dereferenced, so we
4823 // better have an lvalue.
4824 assert(FromClassification.isLValue());
4825 }
4826
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004827 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004828
Douglas Gregor02824322011-01-26 19:30:28 +00004829 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004831 // parameter is
4832 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004833 // - "lvalue reference to cv X" for functions declared without a
4834 // ref-qualifier or with the & ref-qualifier
4835 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004836 // ref-qualifier
4837 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004839 // cv-qualification on the member function declaration.
4840 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004842 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004843 // (C++ [over.match.funcs]p5). We perform a simplified version of
4844 // reference binding here, that allows class rvalues to bind to
4845 // non-constant references.
4846
Douglas Gregor02824322011-01-26 19:30:28 +00004847 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004848 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004850 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004851 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004852 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004853 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004854 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004855 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004856
4857 // Check that we have either the same type or a derived type. It
4858 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004859 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004860 ImplicitConversionKind SecondKind;
4861 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4862 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004863 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004864 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004865 else {
John McCall65eb8792010-02-25 01:37:24 +00004866 ICS.setBad(BadConversionSequence::unrelated_class,
4867 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004868 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004869 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004870
Douglas Gregor02824322011-01-26 19:30:28 +00004871 // Check the ref-qualifier.
4872 switch (Method->getRefQualifier()) {
4873 case RQ_None:
4874 // Do nothing; we don't care about lvalueness or rvalueness.
4875 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876
Douglas Gregor02824322011-01-26 19:30:28 +00004877 case RQ_LValue:
4878 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4879 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004881 ImplicitParamType);
4882 return ICS;
4883 }
4884 break;
4885
4886 case RQ_RValue:
4887 if (!FromClassification.isRValue()) {
4888 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004890 ImplicitParamType);
4891 return ICS;
4892 }
4893 break;
4894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Douglas Gregor436424c2008-11-18 23:14:02 +00004896 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004897 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004898 ICS.Standard.setAsIdentityConversion();
4899 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004900 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004901 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004902 ICS.Standard.ReferenceBinding = true;
4903 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004904 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004905 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004906 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4907 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4908 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004909 return ICS;
4910}
4911
4912/// PerformObjectArgumentInitialization - Perform initialization of
4913/// the implicit object parameter for the given Method with the given
4914/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004915ExprResult
4916Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004918 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004919 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004920 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004921 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004922 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004923
Douglas Gregor02824322011-01-26 19:30:28 +00004924 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004925 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004926 FromRecordType = PT->getPointeeType();
4927 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004928 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004929 } else {
4930 FromRecordType = From->getType();
4931 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004932 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004933 }
4934
John McCall6e9f8f62009-12-03 04:06:58 +00004935 // Note that we always use the true parent context when performing
4936 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004937 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4938 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004939 if (ICS.isBad()) {
4940 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4941 Qualifiers FromQs = FromRecordType.getQualifiers();
4942 Qualifiers ToQs = DestType.getQualifiers();
4943 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4944 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004945 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004946 diag::err_member_function_call_bad_cvr)
4947 << Method->getDeclName() << FromRecordType << (CVR - 1)
4948 << From->getSourceRange();
4949 Diag(Method->getLocation(), diag::note_previous_decl)
4950 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004951 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004952 }
4953 }
4954
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004955 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004956 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004957 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
John Wiegley01296292011-04-08 18:41:53 +00004960 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4961 ExprResult FromRes =
4962 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4963 if (FromRes.isInvalid())
4964 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004965 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004966 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004967
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004968 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004969 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004970 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004971 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004972}
4973
Douglas Gregor5fb53972009-01-14 15:45:31 +00004974/// TryContextuallyConvertToBool - Attempt to contextually convert the
4975/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004976static ImplicitConversionSequence
4977TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004978 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004979 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004980 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004981 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004982 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004983 /*AllowObjCWritebackConversion=*/false,
4984 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004985}
4986
4987/// PerformContextuallyConvertToBool - Perform a contextual conversion
4988/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004989ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004990 if (checkPlaceholderForOverload(*this, From))
4991 return ExprError();
4992
John McCall5c32be02010-08-24 20:38:10 +00004993 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004994 if (!ICS.isBad())
4995 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996
Fariborz Jahanian76197412009-11-18 18:26:29 +00004997 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004998 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004999 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005000 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005001 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005002}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003
Richard Smithf8379a02012-01-18 23:55:52 +00005004/// Check that the specified conversion is permitted in a converted constant
5005/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5006/// is acceptable.
5007static bool CheckConvertedConstantConversions(Sema &S,
5008 StandardConversionSequence &SCS) {
5009 // Since we know that the target type is an integral or unscoped enumeration
5010 // type, most conversion kinds are impossible. All possible First and Third
5011 // conversions are fine.
5012 switch (SCS.Second) {
5013 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005014 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005015 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005016 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005017 return true;
5018
5019 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005020 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005021 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5022 // conversion, so we allow it in a converted constant expression.
5023 //
5024 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5025 // a lot of popular code. We should at least add a warning for this
5026 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005027 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5028 SCS.getToType(2)->isBooleanType();
5029
Richard Smith410cc892014-11-26 03:26:53 +00005030 case ICK_Pointer_Conversion:
5031 case ICK_Pointer_Member:
5032 // C++1z: null pointer conversions and null member pointer conversions are
5033 // only permitted if the source type is std::nullptr_t.
5034 return SCS.getFromType()->isNullPtrType();
5035
5036 case ICK_Floating_Promotion:
5037 case ICK_Complex_Promotion:
5038 case ICK_Floating_Conversion:
5039 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005040 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005041 case ICK_Compatible_Conversion:
5042 case ICK_Derived_To_Base:
5043 case ICK_Vector_Conversion:
5044 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005045 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005046 case ICK_Block_Pointer_Conversion:
5047 case ICK_TransparentUnionConversion:
5048 case ICK_Writeback_Conversion:
5049 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005050 case ICK_C_Only_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005051 return false;
5052
5053 case ICK_Lvalue_To_Rvalue:
5054 case ICK_Array_To_Pointer:
5055 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005056 llvm_unreachable("found a first conversion kind in Second");
5057
Richard Smithf8379a02012-01-18 23:55:52 +00005058 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005059 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005060
5061 case ICK_Num_Conversion_Kinds:
5062 break;
5063 }
5064
5065 llvm_unreachable("unknown conversion kind");
5066}
5067
5068/// CheckConvertedConstantExpression - Check that the expression From is a
5069/// converted constant expression of type T, perform the conversion and produce
5070/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005071static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5072 QualType T, APValue &Value,
5073 Sema::CCEKind CCE,
5074 bool RequireInt) {
5075 assert(S.getLangOpts().CPlusPlus11 &&
5076 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005077
Richard Smith410cc892014-11-26 03:26:53 +00005078 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005079 return ExprError();
5080
Richard Smith410cc892014-11-26 03:26:53 +00005081 // C++1z [expr.const]p3:
5082 // A converted constant expression of type T is an expression,
5083 // implicitly converted to type T, where the converted
5084 // expression is a constant expression and the implicit conversion
5085 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005086 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005087 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005088 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005089 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005090 /*AllowObjcWritebackConversion=*/false,
5091 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005092 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005093 switch (ICS.getKind()) {
5094 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005095 SCS = &ICS.Standard;
5096 break;
5097 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005098 // We are converting to a non-class type, so the Before sequence
5099 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005100 SCS = &ICS.UserDefined.After;
5101 break;
5102 case ImplicitConversionSequence::AmbiguousConversion:
5103 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005104 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5105 return S.Diag(From->getLocStart(),
5106 diag::err_typecheck_converted_constant_expression)
5107 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005108 return ExprError();
5109
5110 case ImplicitConversionSequence::EllipsisConversion:
5111 llvm_unreachable("ellipsis conversion in converted constant expression");
5112 }
5113
Richard Smith410cc892014-11-26 03:26:53 +00005114 // Check that we would only use permitted conversions.
5115 if (!CheckConvertedConstantConversions(S, *SCS)) {
5116 return S.Diag(From->getLocStart(),
5117 diag::err_typecheck_converted_constant_expression_disallowed)
5118 << From->getType() << From->getSourceRange() << T;
5119 }
5120 // [...] and where the reference binding (if any) binds directly.
5121 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5122 return S.Diag(From->getLocStart(),
5123 diag::err_typecheck_converted_constant_expression_indirect)
5124 << From->getType() << From->getSourceRange() << T;
5125 }
5126
5127 ExprResult Result =
5128 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005129 if (Result.isInvalid())
5130 return Result;
5131
5132 // Check for a narrowing implicit conversion.
5133 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005134 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005135 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005136 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005137 case NK_Variable_Narrowing:
5138 // Implicit conversion to a narrower type, and the value is not a constant
5139 // expression. We'll diagnose this in a moment.
5140 case NK_Not_Narrowing:
5141 break;
5142
5143 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005144 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005145 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005146 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005147 break;
5148
5149 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005150 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005151 << CCE << /*Constant*/0 << From->getType() << T;
5152 break;
5153 }
5154
5155 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005156 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005157 Expr::EvalResult Eval;
5158 Eval.Diag = &Notes;
5159
Richard Smith410cc892014-11-26 03:26:53 +00005160 if ((T->isReferenceType()
5161 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5162 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5163 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005164 // The expression can't be folded, so we can't keep it at this position in
5165 // the AST.
5166 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005167 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005168 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005169
5170 if (Notes.empty()) {
5171 // It's a constant expression.
5172 return Result;
5173 }
Richard Smithf8379a02012-01-18 23:55:52 +00005174 }
5175
5176 // It's not a constant expression. Produce an appropriate diagnostic.
5177 if (Notes.size() == 1 &&
5178 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005179 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005180 else {
Richard Smith410cc892014-11-26 03:26:53 +00005181 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005182 << CCE << From->getSourceRange();
5183 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005184 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005185 }
Richard Smith410cc892014-11-26 03:26:53 +00005186 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005187}
5188
Richard Smith410cc892014-11-26 03:26:53 +00005189ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5190 APValue &Value, CCEKind CCE) {
5191 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5192}
5193
5194ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5195 llvm::APSInt &Value,
5196 CCEKind CCE) {
5197 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5198
5199 APValue V;
5200 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5201 if (!R.isInvalid())
5202 Value = V.getInt();
5203 return R;
5204}
5205
5206
John McCallfec112d2011-09-09 06:11:02 +00005207/// dropPointerConversions - If the given standard conversion sequence
5208/// involves any pointer conversions, remove them. This may change
5209/// the result type of the conversion sequence.
5210static void dropPointerConversion(StandardConversionSequence &SCS) {
5211 if (SCS.Second == ICK_Pointer_Conversion) {
5212 SCS.Second = ICK_Identity;
5213 SCS.Third = ICK_Identity;
5214 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5215 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005216}
John McCall5c32be02010-08-24 20:38:10 +00005217
John McCallfec112d2011-09-09 06:11:02 +00005218/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5219/// convert the expression From to an Objective-C pointer type.
5220static ImplicitConversionSequence
5221TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5222 // Do an implicit conversion to 'id'.
5223 QualType Ty = S.Context.getObjCIdType();
5224 ImplicitConversionSequence ICS
5225 = TryImplicitConversion(S, From, Ty,
5226 // FIXME: Are these flags correct?
5227 /*SuppressUserConversions=*/false,
5228 /*AllowExplicit=*/true,
5229 /*InOverloadResolution=*/false,
5230 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005231 /*AllowObjCWritebackConversion=*/false,
5232 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005233
5234 // Strip off any final conversions to 'id'.
5235 switch (ICS.getKind()) {
5236 case ImplicitConversionSequence::BadConversion:
5237 case ImplicitConversionSequence::AmbiguousConversion:
5238 case ImplicitConversionSequence::EllipsisConversion:
5239 break;
5240
5241 case ImplicitConversionSequence::UserDefinedConversion:
5242 dropPointerConversion(ICS.UserDefined.After);
5243 break;
5244
5245 case ImplicitConversionSequence::StandardConversion:
5246 dropPointerConversion(ICS.Standard);
5247 break;
5248 }
5249
5250 return ICS;
5251}
5252
5253/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5254/// conversion of the expression From to an Objective-C pointer type.
5255ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005256 if (checkPlaceholderForOverload(*this, From))
5257 return ExprError();
5258
John McCall8b07ec22010-05-15 11:32:37 +00005259 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005260 ImplicitConversionSequence ICS =
5261 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005262 if (!ICS.isBad())
5263 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005264 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005265}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005266
Richard Smith8dd34252012-02-04 07:07:42 +00005267/// Determine whether the provided type is an integral type, or an enumeration
5268/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005269bool Sema::ICEConvertDiagnoser::match(QualType T) {
5270 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5271 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005272}
5273
Larisse Voufo236bec22013-06-10 06:50:24 +00005274static ExprResult
5275diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5276 Sema::ContextualImplicitConverter &Converter,
5277 QualType T, UnresolvedSetImpl &ViableConversions) {
5278
5279 if (Converter.Suppress)
5280 return ExprError();
5281
5282 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5283 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5284 CXXConversionDecl *Conv =
5285 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5286 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5287 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5288 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005289 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005290}
5291
5292static bool
5293diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5294 Sema::ContextualImplicitConverter &Converter,
5295 QualType T, bool HadMultipleCandidates,
5296 UnresolvedSetImpl &ExplicitConversions) {
5297 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5298 DeclAccessPair Found = ExplicitConversions[0];
5299 CXXConversionDecl *Conversion =
5300 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5301
5302 // The user probably meant to invoke the given explicit
5303 // conversion; use it.
5304 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5305 std::string TypeStr;
5306 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5307
5308 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5309 << FixItHint::CreateInsertion(From->getLocStart(),
5310 "static_cast<" + TypeStr + ">(")
5311 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005312 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005313 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5314
5315 // If we aren't in a SFINAE context, build a call to the
5316 // explicit conversion function.
5317 if (SemaRef.isSFINAEContext())
5318 return true;
5319
Craig Topperc3ec1492014-05-26 06:22:03 +00005320 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005321 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5322 HadMultipleCandidates);
5323 if (Result.isInvalid())
5324 return true;
5325 // Record usage of conversion in an implicit cast.
5326 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005327 CK_UserDefinedConversion, Result.get(),
5328 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005329 }
5330 return false;
5331}
5332
5333static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5334 Sema::ContextualImplicitConverter &Converter,
5335 QualType T, bool HadMultipleCandidates,
5336 DeclAccessPair &Found) {
5337 CXXConversionDecl *Conversion =
5338 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005339 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005340
5341 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5342 if (!Converter.SuppressConversion) {
5343 if (SemaRef.isSFINAEContext())
5344 return true;
5345
5346 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5347 << From->getSourceRange();
5348 }
5349
5350 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5351 HadMultipleCandidates);
5352 if (Result.isInvalid())
5353 return true;
5354 // Record usage of conversion in an implicit cast.
5355 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005356 CK_UserDefinedConversion, Result.get(),
5357 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005358 return false;
5359}
5360
5361static ExprResult finishContextualImplicitConversion(
5362 Sema &SemaRef, SourceLocation Loc, Expr *From,
5363 Sema::ContextualImplicitConverter &Converter) {
5364 if (!Converter.match(From->getType()) && !Converter.Suppress)
5365 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5366 << From->getSourceRange();
5367
5368 return SemaRef.DefaultLvalueConversion(From);
5369}
5370
5371static void
5372collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5373 UnresolvedSetImpl &ViableConversions,
5374 OverloadCandidateSet &CandidateSet) {
5375 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5376 DeclAccessPair FoundDecl = ViableConversions[I];
5377 NamedDecl *D = FoundDecl.getDecl();
5378 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5379 if (isa<UsingShadowDecl>(D))
5380 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5381
5382 CXXConversionDecl *Conv;
5383 FunctionTemplateDecl *ConvTemplate;
5384 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5385 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5386 else
5387 Conv = cast<CXXConversionDecl>(D);
5388
5389 if (ConvTemplate)
5390 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005391 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5392 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005393 else
5394 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005395 ToType, CandidateSet,
5396 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005397 }
5398}
5399
Richard Smithccc11812013-05-21 19:05:48 +00005400/// \brief Attempt to convert the given expression to a type which is accepted
5401/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005402///
Richard Smithccc11812013-05-21 19:05:48 +00005403/// This routine will attempt to convert an expression of class type to a
5404/// type accepted by the specified converter. In C++11 and before, the class
5405/// must have a single non-explicit conversion function converting to a matching
5406/// type. In C++1y, there can be multiple such conversion functions, but only
5407/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005408///
Douglas Gregor4799d032010-06-30 00:20:43 +00005409/// \param Loc The source location of the construct that requires the
5410/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005411///
James Dennett18348b62012-06-22 08:52:37 +00005412/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005413///
Richard Smithccc11812013-05-21 19:05:48 +00005414/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005415///
Douglas Gregor4799d032010-06-30 00:20:43 +00005416/// \returns The expression, converted to an integral or enumeration type if
5417/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005418ExprResult Sema::PerformContextualImplicitConversion(
5419 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005420 // We can't perform any more checking for type-dependent expressions.
5421 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005422 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
Eli Friedman1da70392012-01-26 00:26:18 +00005424 // Process placeholders immediately.
5425 if (From->hasPlaceholderType()) {
5426 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005427 if (result.isInvalid())
5428 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005429 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005430 }
5431
Richard Smithccc11812013-05-21 19:05:48 +00005432 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005433 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005434 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005435 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005436
5437 // FIXME: Check for missing '()' if T is a function type?
5438
Richard Smithccc11812013-05-21 19:05:48 +00005439 // We can only perform contextual implicit conversions on objects of class
5440 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005441 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005442 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005443 if (!Converter.Suppress)
5444 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005445 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005448 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005449 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005450 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005451 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005452
5453 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5454 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5455
Craig Toppere14c0f82014-03-12 04:55:44 +00005456 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005457 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005458 }
Richard Smithccc11812013-05-21 19:05:48 +00005459 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005460
5461 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005462 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005464 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005465 UnresolvedSet<4>
5466 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005467 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005468 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005470
Larisse Voufo236bec22013-06-10 06:50:24 +00005471 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005472 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005473
Larisse Voufo236bec22013-06-10 06:50:24 +00005474 // To check that there is only one target type, in C++1y:
5475 QualType ToType;
5476 bool HasUniqueTargetType = true;
5477
5478 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005479 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005480 NamedDecl *D = (*I)->getUnderlyingDecl();
5481 CXXConversionDecl *Conversion;
5482 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5483 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005484 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005485 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5486 else
5487 continue; // C++11 does not consider conversion operator templates(?).
5488 } else
5489 Conversion = cast<CXXConversionDecl>(D);
5490
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005491 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005492 "Conversion operator templates are considered potentially "
5493 "viable in C++1y");
5494
5495 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5496 if (Converter.match(CurToType) || ConvTemplate) {
5497
5498 if (Conversion->isExplicit()) {
5499 // FIXME: For C++1y, do we need this restriction?
5500 // cf. diagnoseNoViableConversion()
5501 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005502 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005503 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005504 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005505 if (ToType.isNull())
5506 ToType = CurToType.getUnqualifiedType();
5507 else if (HasUniqueTargetType &&
5508 (CurToType.getUnqualifiedType() != ToType))
5509 HasUniqueTargetType = false;
5510 }
5511 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005512 }
Richard Smith8dd34252012-02-04 07:07:42 +00005513 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005515
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005516 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005517 // C++1y [conv]p6:
5518 // ... An expression e of class type E appearing in such a context
5519 // is said to be contextually implicitly converted to a specified
5520 // type T and is well-formed if and only if e can be implicitly
5521 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005522 // for conversion functions whose return type is cv T or reference to
5523 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005524 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525
Larisse Voufo236bec22013-06-10 06:50:24 +00005526 // If no unique T is found:
5527 if (ToType.isNull()) {
5528 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5529 HadMultipleCandidates,
5530 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005531 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005532 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Larisse Voufo236bec22013-06-10 06:50:24 +00005535 // If more than one unique Ts are found:
5536 if (!HasUniqueTargetType)
5537 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5538 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539
Larisse Voufo236bec22013-06-10 06:50:24 +00005540 // If one unique T is found:
5541 // First, build a candidate set from the previously recorded
5542 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005543 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005544 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5545 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005546
Larisse Voufo236bec22013-06-10 06:50:24 +00005547 // Then, perform overload resolution over the candidate set.
5548 OverloadCandidateSet::iterator Best;
5549 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5550 case OR_Success: {
5551 // Apply this conversion.
5552 DeclAccessPair Found =
5553 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5554 if (recordConversion(*this, Loc, From, Converter, T,
5555 HadMultipleCandidates, Found))
5556 return ExprError();
5557 break;
5558 }
5559 case OR_Ambiguous:
5560 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5561 ViableConversions);
5562 case OR_No_Viable_Function:
5563 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5564 HadMultipleCandidates,
5565 ExplicitConversions))
5566 return ExprError();
5567 // fall through 'OR_Deleted' case.
5568 case OR_Deleted:
5569 // We'll complain below about a non-integral condition type.
5570 break;
5571 }
5572 } else {
5573 switch (ViableConversions.size()) {
5574 case 0: {
5575 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5576 HadMultipleCandidates,
5577 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005578 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579
Larisse Voufo236bec22013-06-10 06:50:24 +00005580 // We'll complain below about a non-integral condition type.
5581 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005582 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005583 case 1: {
5584 // Apply this conversion.
5585 DeclAccessPair Found = ViableConversions[0];
5586 if (recordConversion(*this, Loc, From, Converter, T,
5587 HadMultipleCandidates, Found))
5588 return ExprError();
5589 break;
5590 }
5591 default:
5592 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5593 ViableConversions);
5594 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Larisse Voufo236bec22013-06-10 06:50:24 +00005597 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005598}
5599
Richard Smith100b24a2014-04-17 01:52:14 +00005600/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5601/// an acceptable non-member overloaded operator for a call whose
5602/// arguments have types T1 (and, if non-empty, T2). This routine
5603/// implements the check in C++ [over.match.oper]p3b2 concerning
5604/// enumeration types.
5605static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5606 FunctionDecl *Fn,
5607 ArrayRef<Expr *> Args) {
5608 QualType T1 = Args[0]->getType();
5609 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5610
5611 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5612 return true;
5613
5614 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5615 return true;
5616
5617 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5618 if (Proto->getNumParams() < 1)
5619 return false;
5620
5621 if (T1->isEnumeralType()) {
5622 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5623 if (Context.hasSameUnqualifiedType(T1, ArgType))
5624 return true;
5625 }
5626
5627 if (Proto->getNumParams() < 2)
5628 return false;
5629
5630 if (!T2.isNull() && T2->isEnumeralType()) {
5631 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5632 if (Context.hasSameUnqualifiedType(T2, ArgType))
5633 return true;
5634 }
5635
5636 return false;
5637}
5638
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005639/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005640/// candidate functions, using the given function call arguments. If
5641/// @p SuppressUserConversions, then don't allow user-defined
5642/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005643///
James Dennett2a4d13c2012-06-15 07:13:21 +00005644/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005645/// based on an incomplete set of function arguments. This feature is used by
5646/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005647void
5648Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005649 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005650 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005651 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005652 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005653 bool PartialOverloading,
5654 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005655 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005656 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005657 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005658 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005659 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005660
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005662 if (!isa<CXXConstructorDecl>(Method)) {
5663 // If we get here, it's because we're calling a member function
5664 // that is named without a member access expression (e.g.,
5665 // "this->f") that was either written explicitly or created
5666 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005667 // function, e.g., X::f(). We use an empty type for the implied
5668 // object argument (C++ [over.call.func]p3), and the acting context
5669 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005670 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005672 Args, CandidateSet, SuppressUserConversions,
5673 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005674 return;
5675 }
5676 // We treat a constructor like a non-member function, since its object
5677 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005678 }
5679
Douglas Gregorff7028a2009-11-13 23:59:09 +00005680 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005681 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005682
Richard Smith100b24a2014-04-17 01:52:14 +00005683 // C++ [over.match.oper]p3:
5684 // if no operand has a class type, only those non-member functions in the
5685 // lookup set that have a first parameter of type T1 or "reference to
5686 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5687 // is a right operand) a second parameter of type T2 or "reference to
5688 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5689 // candidate functions.
5690 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5691 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5692 return;
5693
Richard Smith8b86f2d2013-11-04 01:48:18 +00005694 // C++11 [class.copy]p11: [DR1402]
5695 // A defaulted move constructor that is defined as deleted is ignored by
5696 // overload resolution.
5697 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5698 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5699 Constructor->isMoveConstructor())
5700 return;
5701
Douglas Gregor27381f32009-11-23 12:27:39 +00005702 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005703 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005704
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005705 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005706 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005707 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005708 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005709 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005710 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005711 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005712 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713
John McCall578a1f82014-12-14 01:46:53 +00005714 if (Constructor) {
5715 // C++ [class.copy]p3:
5716 // A member function template is never instantiated to perform the copy
5717 // of a class object to an object of its class type.
5718 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5719 if (Args.size() == 1 &&
5720 Constructor->isSpecializationCopyingObject() &&
5721 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5722 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5723 Candidate.Viable = false;
5724 Candidate.FailureKind = ovl_fail_illegal_constructor;
5725 return;
5726 }
5727 }
5728
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005729 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005730
5731 // (C++ 13.3.2p2): A candidate function having fewer than m
5732 // parameters is viable only if it has an ellipsis in its parameter
5733 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005734 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005735 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005736 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005737 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005738 return;
5739 }
5740
5741 // (C++ 13.3.2p2): A candidate function having more than m parameters
5742 // is viable only if the (m+1)st parameter has a default argument
5743 // (8.3.6). For the purposes of overload resolution, the
5744 // parameter list is truncated on the right, so that there are
5745 // exactly m parameters.
5746 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005747 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005748 // Not enough arguments.
5749 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005750 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005751 return;
5752 }
5753
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005754 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005755 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005756 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005757 // Skip the check for callers that are implicit members, because in this
5758 // case we may not yet know what the member's target is; the target is
5759 // inferred for the member automatically, based on the bases and fields of
5760 // the class.
5761 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005762 Candidate.Viable = false;
5763 Candidate.FailureKind = ovl_fail_bad_target;
5764 return;
5765 }
5766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005767 // Determine the implicit conversion sequences for each of the
5768 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005769 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005770 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005771 // (C++ 13.3.2p3): for F to be a viable function, there shall
5772 // exist for each argument an implicit conversion sequence
5773 // (13.3.3.1) that converts that argument to the corresponding
5774 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005775 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005776 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005777 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005779 /*InOverloadResolution=*/true,
5780 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005781 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005782 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005783 if (Candidate.Conversions[ArgIdx].isBad()) {
5784 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005785 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005786 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005787 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005788 } else {
5789 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5790 // argument for which there is no corresponding parameter is
5791 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005792 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005793 }
5794 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005795
5796 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5797 Candidate.Viable = false;
5798 Candidate.FailureKind = ovl_fail_enable_if;
5799 Candidate.DeductionFailure.Data = FailedAttr;
5800 return;
5801 }
5802}
5803
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005804ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005805 bool IsInstance) {
5806 SmallVector<ObjCMethodDecl*, 4> Methods;
5807 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5808 return nullptr;
5809
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005810 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5811 bool Match = true;
5812 ObjCMethodDecl *Method = Methods[b];
5813 unsigned NumNamedArgs = Sel.getNumArgs();
5814 // Method might have more arguments than selector indicates. This is due
5815 // to addition of c-style arguments in method.
5816 if (Method->param_size() > NumNamedArgs)
5817 NumNamedArgs = Method->param_size();
5818 if (Args.size() < NumNamedArgs)
5819 continue;
5820
5821 for (unsigned i = 0; i < NumNamedArgs; i++) {
5822 // We can't do any type-checking on a type-dependent argument.
5823 if (Args[i]->isTypeDependent()) {
5824 Match = false;
5825 break;
5826 }
5827
5828 ParmVarDecl *param = Method->parameters()[i];
5829 Expr *argExpr = Args[i];
5830 assert(argExpr && "SelectBestMethod(): missing expression");
5831
5832 // Strip the unbridged-cast placeholder expression off unless it's
5833 // a consumed argument.
5834 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5835 !param->hasAttr<CFConsumedAttr>())
5836 argExpr = stripARCUnbridgedCast(argExpr);
5837
5838 // If the parameter is __unknown_anytype, move on to the next method.
5839 if (param->getType() == Context.UnknownAnyTy) {
5840 Match = false;
5841 break;
5842 }
George Burgess IV45461812015-10-11 20:13:20 +00005843
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005844 ImplicitConversionSequence ConversionState
5845 = TryCopyInitialization(*this, argExpr, param->getType(),
5846 /*SuppressUserConversions*/false,
5847 /*InOverloadResolution=*/true,
5848 /*AllowObjCWritebackConversion=*/
5849 getLangOpts().ObjCAutoRefCount,
5850 /*AllowExplicit*/false);
5851 if (ConversionState.isBad()) {
5852 Match = false;
5853 break;
5854 }
5855 }
5856 // Promote additional arguments to variadic methods.
5857 if (Match && Method->isVariadic()) {
5858 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5859 if (Args[i]->isTypeDependent()) {
5860 Match = false;
5861 break;
5862 }
5863 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5864 nullptr);
5865 if (Arg.isInvalid()) {
5866 Match = false;
5867 break;
5868 }
5869 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005870 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005871 // Check for extra arguments to non-variadic methods.
5872 if (Args.size() != NumNamedArgs)
5873 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005874 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5875 // Special case when selectors have no argument. In this case, select
5876 // one with the most general result type of 'id'.
5877 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5878 QualType ReturnT = Methods[b]->getReturnType();
5879 if (ReturnT->isObjCIdType())
5880 return Methods[b];
5881 }
5882 }
5883 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005884
5885 if (Match)
5886 return Method;
5887 }
5888 return nullptr;
5889}
5890
George Burgess IV2a6150d2015-10-16 01:17:38 +00005891// specific_attr_iterator iterates over enable_if attributes in reverse, and
5892// enable_if is order-sensitive. As a result, we need to reverse things
5893// sometimes. Size of 4 elements is arbitrary.
5894static SmallVector<EnableIfAttr *, 4>
5895getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5896 SmallVector<EnableIfAttr *, 4> Result;
5897 if (!Function->hasAttrs())
5898 return Result;
5899
5900 const auto &FuncAttrs = Function->getAttrs();
5901 for (Attr *Attr : FuncAttrs)
5902 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5903 Result.push_back(EnableIf);
5904
5905 std::reverse(Result.begin(), Result.end());
5906 return Result;
5907}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005908
5909EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5910 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00005911 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5912 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00005913 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005914
5915 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005916 SmallVector<Expr *, 16> ConvertedArgs;
5917 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005918 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005919
5920 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005921 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5922 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005923 !cast<CXXMethodDecl>(Function)->isStatic() &&
5924 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005925 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5926 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005927 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005928 Method, Method);
5929 if (R.isInvalid()) {
5930 InitializationFailed = true;
5931 break;
5932 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005933 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005934 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005935 } else {
5936 ExprResult R =
5937 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5938 Context,
5939 Function->getParamDecl(i)),
5940 SourceLocation(),
5941 Args[i]);
5942 if (R.isInvalid()) {
5943 InitializationFailed = true;
5944 break;
5945 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005946 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005947 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005948 }
5949 }
5950
5951 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005952 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005953
Nick Lewyckye283c552015-08-25 22:33:16 +00005954 // Push default arguments if needed.
5955 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5956 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5957 ParmVarDecl *P = Function->getParamDecl(i);
5958 ExprResult R = PerformCopyInitialization(
5959 InitializedEntity::InitializeParameter(Context,
5960 Function->getParamDecl(i)),
5961 SourceLocation(),
5962 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5963 : P->getDefaultArg());
5964 if (R.isInvalid()) {
5965 InitializationFailed = true;
5966 break;
5967 }
5968 ContainsValueDependentExpr |= R.get()->isValueDependent();
5969 ConvertedArgs.push_back(R.get());
5970 }
5971
5972 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00005973 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00005974 }
5975
George Burgess IV2a6150d2015-10-16 01:17:38 +00005976 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005977 APValue Result;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005978 if (EIA->getCond()->isValueDependent()) {
5979 // Don't even try now, we'll examine it after instantiation.
5980 continue;
5981 }
5982
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005983 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005984 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5985 if (!ContainsValueDependentExpr)
5986 return EIA;
5987 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005988 return EIA;
5989 }
5990 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005991 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005992}
5993
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005994/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005995/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005996void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005997 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005998 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005999 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006000 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006001 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006002 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006003 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6004 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006005 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006006 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006007 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006008 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006009 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006010 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006011 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006012 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006013 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006014 } else {
John McCalla0296f72010-03-19 07:35:19 +00006015 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006016 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6017 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006018 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006019 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006020 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006022 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006023 CandidateSet, SuppressUserConversions,
6024 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006025 else
John McCalla0296f72010-03-19 07:35:19 +00006026 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006027 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006028 CandidateSet, SuppressUserConversions,
6029 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006030 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006031 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006032}
6033
John McCallf0f1cf02009-11-17 07:50:12 +00006034/// AddMethodCandidate - Adds a named decl (which is some kind of
6035/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006036void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006037 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006038 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006039 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006040 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006041 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006042 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006043 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006044
6045 if (isa<UsingShadowDecl>(Decl))
6046 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047
John McCallf0f1cf02009-11-17 07:50:12 +00006048 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6049 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6050 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006051 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006052 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006053 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006054 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006055 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006056 } else {
John McCalla0296f72010-03-19 07:35:19 +00006057 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006058 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006059 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006060 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006061 }
6062}
6063
Douglas Gregor436424c2008-11-18 23:14:02 +00006064/// AddMethodCandidate - Adds the given C++ member function to the set
6065/// of candidate functions, using the given function call arguments
6066/// and the object argument (@c Object). For example, in a call
6067/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6068/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6069/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006070/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006071void
John McCalla0296f72010-03-19 07:35:19 +00006072Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006073 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006074 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006075 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006076 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006077 bool SuppressUserConversions,
6078 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006079 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006080 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006081 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006082 assert(!isa<CXXConstructorDecl>(Method) &&
6083 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006084
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006085 if (!CandidateSet.isNewCandidate(Method))
6086 return;
6087
Richard Smith8b86f2d2013-11-04 01:48:18 +00006088 // C++11 [class.copy]p23: [DR1402]
6089 // A defaulted move assignment operator that is defined as deleted is
6090 // ignored by overload resolution.
6091 if (Method->isDefaulted() && Method->isDeleted() &&
6092 Method->isMoveAssignmentOperator())
6093 return;
6094
Douglas Gregor27381f32009-11-23 12:27:39 +00006095 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006096 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006097
Douglas Gregor436424c2008-11-18 23:14:02 +00006098 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006099 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006100 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006101 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006102 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006103 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006104 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006105
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006106 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006107
6108 // (C++ 13.3.2p2): A candidate function having fewer than m
6109 // parameters is viable only if it has an ellipsis in its parameter
6110 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006111 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6112 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006113 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006114 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006115 return;
6116 }
6117
6118 // (C++ 13.3.2p2): A candidate function having more than m parameters
6119 // is viable only if the (m+1)st parameter has a default argument
6120 // (8.3.6). For the purposes of overload resolution, the
6121 // parameter list is truncated on the right, so that there are
6122 // exactly m parameters.
6123 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006124 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006125 // Not enough arguments.
6126 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006127 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006128 return;
6129 }
6130
6131 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006132
John McCall6e9f8f62009-12-03 04:06:58 +00006133 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006134 // The implicit object argument is ignored.
6135 Candidate.IgnoreObjectArgument = true;
6136 else {
6137 // Determine the implicit conversion sequence for the object
6138 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006139 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006140 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6141 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006142 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006144 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006145 return;
6146 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006147 }
6148
Eli Bendersky291a57e2014-09-25 23:59:08 +00006149 // (CUDA B.1): Check for invalid calls between targets.
6150 if (getLangOpts().CUDA)
6151 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6152 if (CheckCUDATarget(Caller, Method)) {
6153 Candidate.Viable = false;
6154 Candidate.FailureKind = ovl_fail_bad_target;
6155 return;
6156 }
6157
Douglas Gregor436424c2008-11-18 23:14:02 +00006158 // Determine the implicit conversion sequences for each of the
6159 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006160 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006161 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006162 // (C++ 13.3.2p3): for F to be a viable function, there shall
6163 // exist for each argument an implicit conversion sequence
6164 // (13.3.3.1) that converts that argument to the corresponding
6165 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006166 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006167 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006168 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006169 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006170 /*InOverloadResolution=*/true,
6171 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006172 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006173 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006174 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006175 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006176 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006177 }
6178 } else {
6179 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6180 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006181 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006182 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006183 }
6184 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006185
6186 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6187 Candidate.Viable = false;
6188 Candidate.FailureKind = ovl_fail_enable_if;
6189 Candidate.DeductionFailure.Data = FailedAttr;
6190 return;
6191 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006192}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006193
Douglas Gregor97628d62009-08-21 00:16:32 +00006194/// \brief Add a C++ member function template as a candidate to the candidate
6195/// set, using template argument deduction to produce an appropriate member
6196/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006197void
Douglas Gregor97628d62009-08-21 00:16:32 +00006198Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006199 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006200 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006201 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006202 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006203 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006204 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006205 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006206 bool SuppressUserConversions,
6207 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006208 if (!CandidateSet.isNewCandidate(MethodTmpl))
6209 return;
6210
Douglas Gregor97628d62009-08-21 00:16:32 +00006211 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006212 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006213 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006214 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006215 // candidate functions in the usual way.113) A given name can refer to one
6216 // or more function templates and also to a set of overloaded non-template
6217 // functions. In such a case, the candidate functions generated from each
6218 // function template are combined with the set of non-template candidate
6219 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006220 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006221 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006222 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006223 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006224 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006225 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006226 Candidate.FoundDecl = FoundDecl;
6227 Candidate.Function = MethodTmpl->getTemplatedDecl();
6228 Candidate.Viable = false;
6229 Candidate.FailureKind = ovl_fail_bad_deduction;
6230 Candidate.IsSurrogate = false;
6231 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006232 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006233 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006234 Info);
6235 return;
6236 }
Mike Stump11289f42009-09-09 15:08:12 +00006237
Douglas Gregor97628d62009-08-21 00:16:32 +00006238 // Add the function template specialization produced by template argument
6239 // deduction as a candidate.
6240 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006241 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006242 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006243 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006244 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006245 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006246}
6247
Douglas Gregor05155d82009-08-21 23:19:43 +00006248/// \brief Add a C++ function template specialization as a candidate
6249/// in the candidate set, using template argument deduction to produce
6250/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006251void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006252Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006253 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006254 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006255 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006256 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006257 bool SuppressUserConversions,
6258 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006259 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6260 return;
6261
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006262 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006263 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006264 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006265 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006266 // candidate functions in the usual way.113) A given name can refer to one
6267 // or more function templates and also to a set of overloaded non-template
6268 // functions. In such a case, the candidate functions generated from each
6269 // function template are combined with the set of non-template candidate
6270 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006271 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006272 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006273 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006274 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006275 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006276 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006277 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006278 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6279 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006280 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006281 Candidate.IsSurrogate = false;
6282 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006283 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006284 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006285 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006286 return;
6287 }
Mike Stump11289f42009-09-09 15:08:12 +00006288
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006289 // Add the function template specialization produced by template argument
6290 // deduction as a candidate.
6291 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006292 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006293 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006294}
Mike Stump11289f42009-09-09 15:08:12 +00006295
Douglas Gregor4b60a152013-11-07 22:34:54 +00006296/// Determine whether this is an allowable conversion from the result
6297/// of an explicit conversion operator to the expected type, per C++
6298/// [over.match.conv]p1 and [over.match.ref]p1.
6299///
6300/// \param ConvType The return type of the conversion function.
6301///
6302/// \param ToType The type we are converting to.
6303///
6304/// \param AllowObjCPointerConversion Allow a conversion from one
6305/// Objective-C pointer to another.
6306///
6307/// \returns true if the conversion is allowable, false otherwise.
6308static bool isAllowableExplicitConversion(Sema &S,
6309 QualType ConvType, QualType ToType,
6310 bool AllowObjCPointerConversion) {
6311 QualType ToNonRefType = ToType.getNonReferenceType();
6312
6313 // Easy case: the types are the same.
6314 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6315 return true;
6316
6317 // Allow qualification conversions.
6318 bool ObjCLifetimeConversion;
6319 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6320 ObjCLifetimeConversion))
6321 return true;
6322
6323 // If we're not allowed to consider Objective-C pointer conversions,
6324 // we're done.
6325 if (!AllowObjCPointerConversion)
6326 return false;
6327
6328 // Is this an Objective-C pointer conversion?
6329 bool IncompatibleObjC = false;
6330 QualType ConvertedType;
6331 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6332 IncompatibleObjC);
6333}
6334
Douglas Gregora1f013e2008-11-07 22:36:19 +00006335/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006336/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006337/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006338/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006339/// (which may or may not be the same type as the type that the
6340/// conversion function produces).
6341void
6342Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006343 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006344 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006345 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006346 OverloadCandidateSet& CandidateSet,
6347 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006348 assert(!Conversion->getDescribedFunctionTemplate() &&
6349 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006350 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006351 if (!CandidateSet.isNewCandidate(Conversion))
6352 return;
6353
Richard Smith2a7d4812013-05-04 07:00:32 +00006354 // If the conversion function has an undeduced return type, trigger its
6355 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006356 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006357 if (DeduceReturnType(Conversion, From->getExprLoc()))
6358 return;
6359 ConvType = Conversion->getConversionType().getNonReferenceType();
6360 }
6361
Richard Smith089c3162013-09-21 21:55:46 +00006362 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6363 // operator is only a candidate if its return type is the target type or
6364 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006365 if (Conversion->isExplicit() &&
6366 !isAllowableExplicitConversion(*this, ConvType, ToType,
6367 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006368 return;
6369
Douglas Gregor27381f32009-11-23 12:27:39 +00006370 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006371 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006372
Douglas Gregora1f013e2008-11-07 22:36:19 +00006373 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006374 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006375 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006376 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006377 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006378 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006379 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006380 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006381 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006382 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006383 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006384
Douglas Gregor6affc782010-08-19 15:37:02 +00006385 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386 // For conversion functions, the function is considered to be a member of
6387 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006388 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006389 //
6390 // Determine the implicit conversion sequence for the implicit
6391 // object parameter.
6392 QualType ImplicitParamType = From->getType();
6393 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6394 ImplicitParamType = FromPtrType->getPointeeType();
6395 CXXRecordDecl *ConversionContext
6396 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006397
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006398 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006399 = TryObjectArgumentInitialization(*this, From->getType(),
6400 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006401 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006402
John McCall0d1da222010-01-12 00:44:57 +00006403 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006404 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006405 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006406 return;
6407 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006408
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006409 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006410 // derived to base as such conversions are given Conversion Rank. They only
6411 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6412 QualType FromCanon
6413 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6414 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6415 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6416 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006417 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006418 return;
6419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006420
Douglas Gregora1f013e2008-11-07 22:36:19 +00006421 // To determine what the conversion from the result of calling the
6422 // conversion function to the type we're eventually trying to
6423 // convert to (ToType), we need to synthesize a call to the
6424 // conversion function and attempt copy initialization from it. This
6425 // makes sure that we get the right semantics with respect to
6426 // lvalues/rvalues and the type. Fortunately, we can allocate this
6427 // call on the stack and we don't need its arguments to be
6428 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006429 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006430 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006431 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6432 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006433 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006434 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006435
Richard Smith48d24642011-07-13 22:53:21 +00006436 QualType ConversionType = Conversion->getConversionType();
6437 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006438 Candidate.Viable = false;
6439 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6440 return;
6441 }
6442
Richard Smith48d24642011-07-13 22:53:21 +00006443 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006444
Mike Stump11289f42009-09-09 15:08:12 +00006445 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006446 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6447 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006448 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006449 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006450 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006451 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006452 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006453 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006454 /*InOverloadResolution=*/false,
6455 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006456
John McCall0d1da222010-01-12 00:44:57 +00006457 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006458 case ImplicitConversionSequence::StandardConversion:
6459 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006460
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006461 // C++ [over.ics.user]p3:
6462 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006463 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006464 // shall have exact match rank.
6465 if (Conversion->getPrimaryTemplate() &&
6466 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6467 Candidate.Viable = false;
6468 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006469 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471
Douglas Gregorcba72b12011-01-21 05:18:22 +00006472 // C++0x [dcl.init.ref]p5:
6473 // In the second case, if the reference is an rvalue reference and
6474 // the second standard conversion sequence of the user-defined
6475 // conversion sequence includes an lvalue-to-rvalue conversion, the
6476 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006478 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6479 Candidate.Viable = false;
6480 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006481 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006482 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006483 break;
6484
6485 case ImplicitConversionSequence::BadConversion:
6486 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006487 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006488 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006489
6490 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006491 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006492 "Can only end up with a standard conversion sequence or failure");
6493 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006494
Craig Topper5fc8fc22014-08-27 06:28:36 +00006495 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006496 Candidate.Viable = false;
6497 Candidate.FailureKind = ovl_fail_enable_if;
6498 Candidate.DeductionFailure.Data = FailedAttr;
6499 return;
6500 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006501}
6502
Douglas Gregor05155d82009-08-21 23:19:43 +00006503/// \brief Adds a conversion function template specialization
6504/// candidate to the overload set, using template argument deduction
6505/// to deduce the template arguments of the conversion function
6506/// template from the type that we are converting to (C++
6507/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006508void
Douglas Gregor05155d82009-08-21 23:19:43 +00006509Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006510 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006511 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006512 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006513 OverloadCandidateSet &CandidateSet,
6514 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006515 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6516 "Only conversion function templates permitted here");
6517
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006518 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6519 return;
6520
Craig Toppere6706e42012-09-19 02:26:47 +00006521 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006522 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006523 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006524 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006525 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006526 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006527 Candidate.FoundDecl = FoundDecl;
6528 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6529 Candidate.Viable = false;
6530 Candidate.FailureKind = ovl_fail_bad_deduction;
6531 Candidate.IsSurrogate = false;
6532 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006533 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006534 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006535 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006536 return;
6537 }
Mike Stump11289f42009-09-09 15:08:12 +00006538
Douglas Gregor05155d82009-08-21 23:19:43 +00006539 // Add the conversion function template specialization produced by
6540 // template argument deduction as a candidate.
6541 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006542 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006543 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006544}
6545
Douglas Gregorab7897a2008-11-19 22:57:39 +00006546/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6547/// converts the given @c Object to a function pointer via the
6548/// conversion function @c Conversion, and then attempts to call it
6549/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6550/// the type of function that we'll eventually be calling.
6551void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006552 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006553 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006554 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006555 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006556 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006557 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006558 if (!CandidateSet.isNewCandidate(Conversion))
6559 return;
6560
Douglas Gregor27381f32009-11-23 12:27:39 +00006561 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006562 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006563
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006564 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006565 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006566 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006567 Candidate.Surrogate = Conversion;
6568 Candidate.Viable = true;
6569 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006570 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006571 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006572
6573 // Determine the implicit conversion sequence for the implicit
6574 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006575 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006577 Object->Classify(Context),
6578 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006579 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006580 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006581 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006582 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006583 return;
6584 }
6585
6586 // The first conversion is actually a user-defined conversion whose
6587 // first conversion is ObjectInit's standard conversion (which is
6588 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006589 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006590 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006591 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006592 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006593 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006594 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006595 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006596 = Candidate.Conversions[0].UserDefined.Before;
6597 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6598
Mike Stump11289f42009-09-09 15:08:12 +00006599 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006600 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006601
6602 // (C++ 13.3.2p2): A candidate function having fewer than m
6603 // parameters is viable only if it has an ellipsis in its parameter
6604 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006605 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006607 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006608 return;
6609 }
6610
6611 // Function types don't have any default arguments, so just check if
6612 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006613 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006614 // Not enough arguments.
6615 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006616 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006617 return;
6618 }
6619
6620 // Determine the implicit conversion sequences for each of the
6621 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006622 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006623 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006624 // (C++ 13.3.2p3): for F to be a viable function, there shall
6625 // exist for each argument an implicit conversion sequence
6626 // (13.3.3.1) that converts that argument to the corresponding
6627 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006628 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006629 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006630 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006631 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006632 /*InOverloadResolution=*/false,
6633 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006634 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006635 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006636 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006637 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006638 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006639 }
6640 } else {
6641 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6642 // argument for which there is no corresponding parameter is
6643 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006644 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006645 }
6646 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006647
Craig Topper5fc8fc22014-08-27 06:28:36 +00006648 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006649 Candidate.Viable = false;
6650 Candidate.FailureKind = ovl_fail_enable_if;
6651 Candidate.DeductionFailure.Data = FailedAttr;
6652 return;
6653 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006654}
6655
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006656/// \brief Add overload candidates for overloaded operators that are
6657/// member functions.
6658///
6659/// Add the overloaded operator candidates that are member functions
6660/// for the operator Op that was used in an operator expression such
6661/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6662/// CandidateSet will store the added overload candidates. (C++
6663/// [over.match.oper]).
6664void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6665 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006666 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006667 OverloadCandidateSet& CandidateSet,
6668 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006669 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6670
6671 // C++ [over.match.oper]p3:
6672 // For a unary operator @ with an operand of a type whose
6673 // cv-unqualified version is T1, and for a binary operator @ with
6674 // a left operand of a type whose cv-unqualified version is T1 and
6675 // a right operand of a type whose cv-unqualified version is T2,
6676 // three sets of candidate functions, designated member
6677 // candidates, non-member candidates and built-in candidates, are
6678 // constructed as follows:
6679 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006680
Richard Smith0feaf0c2013-04-20 12:41:22 +00006681 // -- If T1 is a complete class type or a class currently being
6682 // defined, the set of member candidates is the result of the
6683 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6684 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006685 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006686 // Complete the type if it can be completed.
6687 RequireCompleteType(OpLoc, T1, 0);
6688 // If the type is neither complete nor being defined, bail out now.
6689 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006690 return;
Mike Stump11289f42009-09-09 15:08:12 +00006691
John McCall27b18f82009-11-17 02:14:36 +00006692 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6693 LookupQualifiedName(Operators, T1Rec->getDecl());
6694 Operators.suppressDiagnostics();
6695
Mike Stump11289f42009-09-09 15:08:12 +00006696 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006697 OperEnd = Operators.end();
6698 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006699 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006700 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006701 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006702 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006703 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006704 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006705 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006706}
6707
Douglas Gregora11693b2008-11-12 17:17:38 +00006708/// AddBuiltinCandidate - Add a candidate for a built-in
6709/// operator. ResultTy and ParamTys are the result and parameter types
6710/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006711/// arguments being passed to the candidate. IsAssignmentOperator
6712/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006713/// operator. NumContextualBoolArguments is the number of arguments
6714/// (at the beginning of the argument list) that will be contextually
6715/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006716void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006717 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006718 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006719 bool IsAssignmentOperator,
6720 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006721 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006722 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006723
Douglas Gregora11693b2008-11-12 17:17:38 +00006724 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006725 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006726 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6727 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006728 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006729 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006730 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006731 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006732 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6733
6734 // Determine the implicit conversion sequences for each of the
6735 // arguments.
6736 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006737 Candidate.ExplicitCallArguments = Args.size();
6738 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006739 // C++ [over.match.oper]p4:
6740 // For the built-in assignment operators, conversions of the
6741 // left operand are restricted as follows:
6742 // -- no temporaries are introduced to hold the left operand, and
6743 // -- no user-defined conversions are applied to the left
6744 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006745 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006746 //
6747 // We block these conversions by turning off user-defined
6748 // conversions, since that is the only way that initialization of
6749 // a reference to a non-class type can occur from something that
6750 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006751 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006752 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006753 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006754 Candidate.Conversions[ArgIdx]
6755 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006756 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006757 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006758 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006759 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006760 /*InOverloadResolution=*/false,
6761 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006762 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006763 }
John McCall0d1da222010-01-12 00:44:57 +00006764 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006765 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006766 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006767 break;
6768 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006769 }
6770}
6771
Craig Toppercd7b0332013-07-01 06:29:40 +00006772namespace {
6773
Douglas Gregora11693b2008-11-12 17:17:38 +00006774/// BuiltinCandidateTypeSet - A set of types that will be used for the
6775/// candidate operator functions for built-in operators (C++
6776/// [over.built]). The types are separated into pointer types and
6777/// enumeration types.
6778class BuiltinCandidateTypeSet {
6779 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006780 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006781
6782 /// PointerTypes - The set of pointer types that will be used in the
6783 /// built-in candidates.
6784 TypeSet PointerTypes;
6785
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006786 /// MemberPointerTypes - The set of member pointer types that will be
6787 /// used in the built-in candidates.
6788 TypeSet MemberPointerTypes;
6789
Douglas Gregora11693b2008-11-12 17:17:38 +00006790 /// EnumerationTypes - The set of enumeration types that will be
6791 /// used in the built-in candidates.
6792 TypeSet EnumerationTypes;
6793
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006795 /// candidates.
6796 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006797
6798 /// \brief A flag indicating non-record types are viable candidates
6799 bool HasNonRecordTypes;
6800
6801 /// \brief A flag indicating whether either arithmetic or enumeration types
6802 /// were present in the candidate set.
6803 bool HasArithmeticOrEnumeralTypes;
6804
Douglas Gregor80af3132011-05-21 23:15:46 +00006805 /// \brief A flag indicating whether the nullptr type was present in the
6806 /// candidate set.
6807 bool HasNullPtrType;
6808
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006809 /// Sema - The semantic analysis instance where we are building the
6810 /// candidate type set.
6811 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006812
Douglas Gregora11693b2008-11-12 17:17:38 +00006813 /// Context - The AST context in which we will build the type sets.
6814 ASTContext &Context;
6815
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006816 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6817 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006818 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006819
6820public:
6821 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006822 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006823
Mike Stump11289f42009-09-09 15:08:12 +00006824 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006825 : HasNonRecordTypes(false),
6826 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006827 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006828 SemaRef(SemaRef),
6829 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006830
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006832 SourceLocation Loc,
6833 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006834 bool AllowExplicitConversions,
6835 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006836
6837 /// pointer_begin - First pointer type found;
6838 iterator pointer_begin() { return PointerTypes.begin(); }
6839
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006840 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006841 iterator pointer_end() { return PointerTypes.end(); }
6842
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006843 /// member_pointer_begin - First member pointer type found;
6844 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6845
6846 /// member_pointer_end - Past the last member pointer type found;
6847 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6848
Douglas Gregora11693b2008-11-12 17:17:38 +00006849 /// enumeration_begin - First enumeration type found;
6850 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6851
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006852 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006853 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006855 iterator vector_begin() { return VectorTypes.begin(); }
6856 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006857
6858 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6859 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006860 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006861};
6862
Craig Toppercd7b0332013-07-01 06:29:40 +00006863} // end anonymous namespace
6864
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006865/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006866/// the set of pointer types along with any more-qualified variants of
6867/// that type. For example, if @p Ty is "int const *", this routine
6868/// will add "int const *", "int const volatile *", "int const
6869/// restrict *", and "int const volatile restrict *" to the set of
6870/// pointer types. Returns true if the add of @p Ty itself succeeded,
6871/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006872///
6873/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006874bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006875BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6876 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006877
Douglas Gregora11693b2008-11-12 17:17:38 +00006878 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006879 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006880 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006881
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006882 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006883 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006884 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006885 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006886 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6887 PointeeTy = PTy->getPointeeType();
6888 buildObjCPtr = true;
6889 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006890 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006891 }
6892
Sebastian Redl4990a632009-11-18 20:39:26 +00006893 // Don't add qualified variants of arrays. For one, they're not allowed
6894 // (the qualifier would sink to the element type), and for another, the
6895 // only overload situation where it matters is subscript or pointer +- int,
6896 // and those shouldn't have qualifier variants anyway.
6897 if (PointeeTy->isArrayType())
6898 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006899
John McCall8ccfcb52009-09-24 19:53:00 +00006900 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006901 bool hasVolatile = VisibleQuals.hasVolatile();
6902 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006903
John McCall8ccfcb52009-09-24 19:53:00 +00006904 // Iterate through all strict supersets of BaseCVR.
6905 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6906 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006907 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006908 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006909
6910 // Skip over restrict if no restrict found anywhere in the types, or if
6911 // the type cannot be restrict-qualified.
6912 if ((CVR & Qualifiers::Restrict) &&
6913 (!hasRestrict ||
6914 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6915 continue;
6916
6917 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006918 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006919
6920 // Build qualified pointer type.
6921 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006922 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006923 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006924 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006925 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6926
6927 // Insert qualified pointer type.
6928 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006929 }
6930
6931 return true;
6932}
6933
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006934/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6935/// to the set of pointer types along with any more-qualified variants of
6936/// that type. For example, if @p Ty is "int const *", this routine
6937/// will add "int const *", "int const volatile *", "int const
6938/// restrict *", and "int const volatile restrict *" to the set of
6939/// pointer types. Returns true if the add of @p Ty itself succeeded,
6940/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006941///
6942/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006943bool
6944BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6945 QualType Ty) {
6946 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006947 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006948 return false;
6949
John McCall8ccfcb52009-09-24 19:53:00 +00006950 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6951 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006952
John McCall8ccfcb52009-09-24 19:53:00 +00006953 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006954 // Don't add qualified variants of arrays. For one, they're not allowed
6955 // (the qualifier would sink to the element type), and for another, the
6956 // only overload situation where it matters is subscript or pointer +- int,
6957 // and those shouldn't have qualifier variants anyway.
6958 if (PointeeTy->isArrayType())
6959 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006960 const Type *ClassTy = PointerTy->getClass();
6961
6962 // Iterate through all strict supersets of the pointee type's CVR
6963 // qualifiers.
6964 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6965 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6966 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
John McCall8ccfcb52009-09-24 19:53:00 +00006968 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006969 MemberPointerTypes.insert(
6970 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006971 }
6972
6973 return true;
6974}
6975
Douglas Gregora11693b2008-11-12 17:17:38 +00006976/// AddTypesConvertedFrom - Add each of the types to which the type @p
6977/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006978/// primarily interested in pointer types and enumeration types. We also
6979/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006980/// AllowUserConversions is true if we should look at the conversion
6981/// functions of a class type, and AllowExplicitConversions if we
6982/// should also include the explicit conversion functions of a class
6983/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006984void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006985BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006986 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006987 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006988 bool AllowExplicitConversions,
6989 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006990 // Only deal with canonical types.
6991 Ty = Context.getCanonicalType(Ty);
6992
6993 // Look through reference types; they aren't part of the type of an
6994 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006995 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006996 Ty = RefTy->getPointeeType();
6997
John McCall33ddac02011-01-19 10:06:00 +00006998 // If we're dealing with an array type, decay to the pointer.
6999 if (Ty->isArrayType())
7000 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7001
7002 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007003 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007004
Chandler Carruth00a38332010-12-13 01:44:01 +00007005 // Flag if we ever add a non-record type.
7006 const RecordType *TyRec = Ty->getAs<RecordType>();
7007 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7008
Chandler Carruth00a38332010-12-13 01:44:01 +00007009 // Flag if we encounter an arithmetic type.
7010 HasArithmeticOrEnumeralTypes =
7011 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7012
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007013 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7014 PointerTypes.insert(Ty);
7015 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007016 // Insert our type, and its more-qualified variants, into the set
7017 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007018 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007019 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007020 } else if (Ty->isMemberPointerType()) {
7021 // Member pointers are far easier, since the pointee can't be converted.
7022 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7023 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007024 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007025 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007026 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007027 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007028 // We treat vector types as arithmetic types in many contexts as an
7029 // extension.
7030 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007031 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007032 } else if (Ty->isNullPtrType()) {
7033 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007034 } else if (AllowUserConversions && TyRec) {
7035 // No conversion functions in incomplete types.
7036 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
7037 return;
Mike Stump11289f42009-09-09 15:08:12 +00007038
Chandler Carruth00a38332010-12-13 01:44:01 +00007039 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007040 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007041 if (isa<UsingShadowDecl>(D))
7042 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007043
Chandler Carruth00a38332010-12-13 01:44:01 +00007044 // Skip conversion function templates; they don't tell us anything
7045 // about which builtin types we can convert to.
7046 if (isa<FunctionTemplateDecl>(D))
7047 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007048
Chandler Carruth00a38332010-12-13 01:44:01 +00007049 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7050 if (AllowExplicitConversions || !Conv->isExplicit()) {
7051 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7052 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007053 }
7054 }
7055 }
7056}
7057
Douglas Gregor84605ae2009-08-24 13:43:27 +00007058/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7059/// the volatile- and non-volatile-qualified assignment operators for the
7060/// given type to the candidate set.
7061static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7062 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007063 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007064 OverloadCandidateSet &CandidateSet) {
7065 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007066
Douglas Gregor84605ae2009-08-24 13:43:27 +00007067 // T& operator=(T&, T)
7068 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7069 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007070 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007071 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007072
Douglas Gregor84605ae2009-08-24 13:43:27 +00007073 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7074 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007075 ParamTypes[0]
7076 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007077 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007079 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007080 }
7081}
Mike Stump11289f42009-09-09 15:08:12 +00007082
Sebastian Redl1054fae2009-10-25 17:03:50 +00007083/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7084/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007085static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7086 Qualifiers VRQuals;
7087 const RecordType *TyRec;
7088 if (const MemberPointerType *RHSMPType =
7089 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007090 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007091 else
7092 TyRec = ArgExpr->getType()->getAs<RecordType>();
7093 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007094 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007095 VRQuals.addVolatile();
7096 VRQuals.addRestrict();
7097 return VRQuals;
7098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007099
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007100 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007101 if (!ClassDecl->hasDefinition())
7102 return VRQuals;
7103
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007104 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007105 if (isa<UsingShadowDecl>(D))
7106 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7107 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007108 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7109 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7110 CanTy = ResTypeRef->getPointeeType();
7111 // Need to go down the pointer/mempointer chain and add qualifiers
7112 // as see them.
7113 bool done = false;
7114 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007115 if (CanTy.isRestrictQualified())
7116 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007117 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7118 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007120 CanTy->getAs<MemberPointerType>())
7121 CanTy = ResTypeMPtr->getPointeeType();
7122 else
7123 done = true;
7124 if (CanTy.isVolatileQualified())
7125 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007126 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7127 return VRQuals;
7128 }
7129 }
7130 }
7131 return VRQuals;
7132}
John McCall52872982010-11-13 05:51:15 +00007133
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007134namespace {
John McCall52872982010-11-13 05:51:15 +00007135
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007136/// \brief Helper class to manage the addition of builtin operator overload
7137/// candidates. It provides shared state and utility methods used throughout
7138/// the process, as well as a helper method to add each group of builtin
7139/// operator overloads from the standard to a candidate set.
7140class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007141 // Common instance state available to all overload candidate addition methods.
7142 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007143 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007144 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007145 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007146 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007147 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007148
Chandler Carruthc6586e52010-12-12 10:35:00 +00007149 // Define some constants used to index and iterate over the arithemetic types
7150 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007151 // The "promoted arithmetic types" are the arithmetic
7152 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007153 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007154 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007155 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007156 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007157 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007158 LastPromotedArithmeticType = 11;
7159 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007160
Chandler Carruthc6586e52010-12-12 10:35:00 +00007161 /// \brief Get the canonical type for a given arithmetic type index.
7162 CanQualType getArithmeticType(unsigned index) {
7163 assert(index < NumArithmeticTypes);
7164 static CanQualType ASTContext::* const
7165 ArithmeticTypes[NumArithmeticTypes] = {
7166 // Start of promoted types.
7167 &ASTContext::FloatTy,
7168 &ASTContext::DoubleTy,
7169 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007170
Chandler Carruthc6586e52010-12-12 10:35:00 +00007171 // Start of integral types.
7172 &ASTContext::IntTy,
7173 &ASTContext::LongTy,
7174 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007175 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007176 &ASTContext::UnsignedIntTy,
7177 &ASTContext::UnsignedLongTy,
7178 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007179 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007180 // End of promoted types.
7181
7182 &ASTContext::BoolTy,
7183 &ASTContext::CharTy,
7184 &ASTContext::WCharTy,
7185 &ASTContext::Char16Ty,
7186 &ASTContext::Char32Ty,
7187 &ASTContext::SignedCharTy,
7188 &ASTContext::ShortTy,
7189 &ASTContext::UnsignedCharTy,
7190 &ASTContext::UnsignedShortTy,
7191 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007192 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007193 };
7194 return S.Context.*ArithmeticTypes[index];
7195 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007196
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007197 /// \brief Gets the canonical type resulting from the usual arithemetic
7198 /// converions for the given arithmetic types.
7199 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7200 // Accelerator table for performing the usual arithmetic conversions.
7201 // The rules are basically:
7202 // - if either is floating-point, use the wider floating-point
7203 // - if same signedness, use the higher rank
7204 // - if same size, use unsigned of the higher rank
7205 // - use the larger type
7206 // These rules, together with the axiom that higher ranks are
7207 // never smaller, are sufficient to precompute all of these results
7208 // *except* when dealing with signed types of higher rank.
7209 // (we could precompute SLL x UI for all known platforms, but it's
7210 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007211 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007212 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007213 Dep=-1,
7214 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007215 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007216 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007217 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007218/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7219/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7220/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7221/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7222/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7223/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7224/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7225/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7226/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7227/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7228/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007229 };
7230
7231 assert(L < LastPromotedArithmeticType);
7232 assert(R < LastPromotedArithmeticType);
7233 int Idx = ConversionsTable[L][R];
7234
7235 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007236 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007237
7238 // Slow path: we need to compare widths.
7239 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007240 CanQualType LT = getArithmeticType(L),
7241 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007242 unsigned LW = S.Context.getIntWidth(LT),
7243 RW = S.Context.getIntWidth(RT);
7244
7245 // If they're different widths, use the signed type.
7246 if (LW > RW) return LT;
7247 else if (LW < RW) return RT;
7248
7249 // Otherwise, use the unsigned type of the signed type's rank.
7250 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7251 assert(L == SLL || R == SLL);
7252 return S.Context.UnsignedLongLongTy;
7253 }
7254
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007255 /// \brief Helper method to factor out the common pattern of adding overloads
7256 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007257 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007258 bool HasVolatile,
7259 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007260 QualType ParamTypes[2] = {
7261 S.Context.getLValueReferenceType(CandidateTy),
7262 S.Context.IntTy
7263 };
7264
7265 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007266 if (Args.size() == 1)
7267 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007268 else
Richard Smithe54c3072013-05-05 15:51:06 +00007269 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007270
7271 // Use a heuristic to reduce number of builtin candidates in the set:
7272 // add volatile version only if there are conversions to a volatile type.
7273 if (HasVolatile) {
7274 ParamTypes[0] =
7275 S.Context.getLValueReferenceType(
7276 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007277 if (Args.size() == 1)
7278 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007279 else
Richard Smithe54c3072013-05-05 15:51:06 +00007280 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007281 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007282
7283 // Add restrict version only if there are conversions to a restrict type
7284 // and our candidate type is a non-restrict-qualified pointer.
7285 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7286 !CandidateTy.isRestrictQualified()) {
7287 ParamTypes[0]
7288 = S.Context.getLValueReferenceType(
7289 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007290 if (Args.size() == 1)
7291 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007292 else
Richard Smithe54c3072013-05-05 15:51:06 +00007293 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007294
7295 if (HasVolatile) {
7296 ParamTypes[0]
7297 = S.Context.getLValueReferenceType(
7298 S.Context.getCVRQualifiedType(CandidateTy,
7299 (Qualifiers::Volatile |
7300 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007301 if (Args.size() == 1)
7302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007303 else
Richard Smithe54c3072013-05-05 15:51:06 +00007304 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007305 }
7306 }
7307
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007308 }
7309
7310public:
7311 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007312 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007313 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007314 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007315 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007316 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007317 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007318 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007319 HasArithmeticOrEnumeralCandidateType(
7320 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007321 CandidateTypes(CandidateTypes),
7322 CandidateSet(CandidateSet) {
7323 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007324 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007325 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007326 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007327 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007328 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007329 assert(getArithmeticType(FirstPromotedArithmeticType)
7330 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007331 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007332 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007333 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007334 "Invalid last promoted arithmetic type");
7335 }
7336
7337 // C++ [over.built]p3:
7338 //
7339 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7340 // is either volatile or empty, there exist candidate operator
7341 // functions of the form
7342 //
7343 // VQ T& operator++(VQ T&);
7344 // T operator++(VQ T&, int);
7345 //
7346 // C++ [over.built]p4:
7347 //
7348 // For every pair (T, VQ), where T is an arithmetic type other
7349 // than bool, and VQ is either volatile or empty, there exist
7350 // candidate operator functions of the form
7351 //
7352 // VQ T& operator--(VQ T&);
7353 // T operator--(VQ T&, int);
7354 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007355 if (!HasArithmeticOrEnumeralCandidateType)
7356 return;
7357
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007358 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7359 Arith < NumArithmeticTypes; ++Arith) {
7360 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007361 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007362 VisibleTypeConversionsQuals.hasVolatile(),
7363 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 }
7365 }
7366
7367 // C++ [over.built]p5:
7368 //
7369 // For every pair (T, VQ), where T is a cv-qualified or
7370 // cv-unqualified object type, and VQ is either volatile or
7371 // empty, there exist candidate operator functions of the form
7372 //
7373 // T*VQ& operator++(T*VQ&);
7374 // T*VQ& operator--(T*VQ&);
7375 // T* operator++(T*VQ&, int);
7376 // T* operator--(T*VQ&, int);
7377 void addPlusPlusMinusMinusPointerOverloads() {
7378 for (BuiltinCandidateTypeSet::iterator
7379 Ptr = CandidateTypes[0].pointer_begin(),
7380 PtrEnd = CandidateTypes[0].pointer_end();
7381 Ptr != PtrEnd; ++Ptr) {
7382 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007383 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007384 continue;
7385
7386 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007387 (!(*Ptr).isVolatileQualified() &&
7388 VisibleTypeConversionsQuals.hasVolatile()),
7389 (!(*Ptr).isRestrictQualified() &&
7390 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 }
7392 }
7393
7394 // C++ [over.built]p6:
7395 // For every cv-qualified or cv-unqualified object type T, there
7396 // exist candidate operator functions of the form
7397 //
7398 // T& operator*(T*);
7399 //
7400 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007401 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007402 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007403 // T& operator*(T*);
7404 void addUnaryStarPointerOverloads() {
7405 for (BuiltinCandidateTypeSet::iterator
7406 Ptr = CandidateTypes[0].pointer_begin(),
7407 PtrEnd = CandidateTypes[0].pointer_end();
7408 Ptr != PtrEnd; ++Ptr) {
7409 QualType ParamTy = *Ptr;
7410 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007411 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7412 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007413
Douglas Gregor02824322011-01-26 19:30:28 +00007414 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7415 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7416 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007417
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007418 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007419 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007420 }
7421 }
7422
7423 // C++ [over.built]p9:
7424 // For every promoted arithmetic type T, there exist candidate
7425 // operator functions of the form
7426 //
7427 // T operator+(T);
7428 // T operator-(T);
7429 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007430 if (!HasArithmeticOrEnumeralCandidateType)
7431 return;
7432
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 for (unsigned Arith = FirstPromotedArithmeticType;
7434 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007435 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007436 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007437 }
7438
7439 // Extension: We also add these operators for vector types.
7440 for (BuiltinCandidateTypeSet::iterator
7441 Vec = CandidateTypes[0].vector_begin(),
7442 VecEnd = CandidateTypes[0].vector_end();
7443 Vec != VecEnd; ++Vec) {
7444 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007445 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007446 }
7447 }
7448
7449 // C++ [over.built]p8:
7450 // For every type T, there exist candidate operator functions of
7451 // the form
7452 //
7453 // T* operator+(T*);
7454 void addUnaryPlusPointerOverloads() {
7455 for (BuiltinCandidateTypeSet::iterator
7456 Ptr = CandidateTypes[0].pointer_begin(),
7457 PtrEnd = CandidateTypes[0].pointer_end();
7458 Ptr != PtrEnd; ++Ptr) {
7459 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007460 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 }
7462 }
7463
7464 // C++ [over.built]p10:
7465 // For every promoted integral type T, there exist candidate
7466 // operator functions of the form
7467 //
7468 // T operator~(T);
7469 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007470 if (!HasArithmeticOrEnumeralCandidateType)
7471 return;
7472
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007473 for (unsigned Int = FirstPromotedIntegralType;
7474 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007475 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007476 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007477 }
7478
7479 // Extension: We also add this operator for vector types.
7480 for (BuiltinCandidateTypeSet::iterator
7481 Vec = CandidateTypes[0].vector_begin(),
7482 VecEnd = CandidateTypes[0].vector_end();
7483 Vec != VecEnd; ++Vec) {
7484 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007485 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007486 }
7487 }
7488
7489 // C++ [over.match.oper]p16:
7490 // For every pointer to member type T, there exist candidate operator
7491 // functions of the form
7492 //
7493 // bool operator==(T,T);
7494 // bool operator!=(T,T);
7495 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7496 /// Set of (canonical) types that we've already handled.
7497 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7498
Richard Smithe54c3072013-05-05 15:51:06 +00007499 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007500 for (BuiltinCandidateTypeSet::iterator
7501 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7502 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7503 MemPtr != MemPtrEnd;
7504 ++MemPtr) {
7505 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007506 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007507 continue;
7508
7509 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007510 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007511 }
7512 }
7513 }
7514
7515 // C++ [over.built]p15:
7516 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007517 // For every T, where T is an enumeration type, a pointer type, or
7518 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007519 //
7520 // bool operator<(T, T);
7521 // bool operator>(T, T);
7522 // bool operator<=(T, T);
7523 // bool operator>=(T, T);
7524 // bool operator==(T, T);
7525 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007526 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007527 // C++ [over.match.oper]p3:
7528 // [...]the built-in candidates include all of the candidate operator
7529 // functions defined in 13.6 that, compared to the given operator, [...]
7530 // do not have the same parameter-type-list as any non-template non-member
7531 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007532 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007533 // Note that in practice, this only affects enumeration types because there
7534 // aren't any built-in candidates of record type, and a user-defined operator
7535 // must have an operand of record or enumeration type. Also, the only other
7536 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007537 // cannot be overloaded for enumeration types, so this is the only place
7538 // where we must suppress candidates like this.
7539 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7540 UserDefinedBinaryOperators;
7541
Richard Smithe54c3072013-05-05 15:51:06 +00007542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007543 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7544 CandidateTypes[ArgIdx].enumeration_end()) {
7545 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7546 CEnd = CandidateSet.end();
7547 C != CEnd; ++C) {
7548 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7549 continue;
7550
Eli Friedman14f082b2012-09-18 21:52:24 +00007551 if (C->Function->isFunctionTemplateSpecialization())
7552 continue;
7553
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007554 QualType FirstParamType =
7555 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7556 QualType SecondParamType =
7557 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7558
7559 // Skip if either parameter isn't of enumeral type.
7560 if (!FirstParamType->isEnumeralType() ||
7561 !SecondParamType->isEnumeralType())
7562 continue;
7563
7564 // Add this operator to the set of known user-defined operators.
7565 UserDefinedBinaryOperators.insert(
7566 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7567 S.Context.getCanonicalType(SecondParamType)));
7568 }
7569 }
7570 }
7571
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572 /// Set of (canonical) types that we've already handled.
7573 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7574
Richard Smithe54c3072013-05-05 15:51:06 +00007575 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007576 for (BuiltinCandidateTypeSet::iterator
7577 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7578 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7579 Ptr != PtrEnd; ++Ptr) {
7580 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007581 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007582 continue;
7583
7584 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007585 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007586 }
7587 for (BuiltinCandidateTypeSet::iterator
7588 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7589 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7590 Enum != EnumEnd; ++Enum) {
7591 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7592
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007593 // Don't add the same builtin candidate twice, or if a user defined
7594 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007595 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007596 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7597 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007598 continue;
7599
7600 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007601 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007602 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007603
7604 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7605 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007606 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007607 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007608 NullPtrTy))) {
7609 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007610 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007611 CandidateSet);
7612 }
7613 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007614 }
7615 }
7616
7617 // C++ [over.built]p13:
7618 //
7619 // For every cv-qualified or cv-unqualified object type T
7620 // there exist candidate operator functions of the form
7621 //
7622 // T* operator+(T*, ptrdiff_t);
7623 // T& operator[](T*, ptrdiff_t); [BELOW]
7624 // T* operator-(T*, ptrdiff_t);
7625 // T* operator+(ptrdiff_t, T*);
7626 // T& operator[](ptrdiff_t, T*); [BELOW]
7627 //
7628 // C++ [over.built]p14:
7629 //
7630 // For every T, where T is a pointer to object type, there
7631 // exist candidate operator functions of the form
7632 //
7633 // ptrdiff_t operator-(T, T);
7634 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7635 /// Set of (canonical) types that we've already handled.
7636 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7637
7638 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007639 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007640 S.Context.getPointerDiffType(),
7641 S.Context.getPointerDiffType(),
7642 };
7643 for (BuiltinCandidateTypeSet::iterator
7644 Ptr = CandidateTypes[Arg].pointer_begin(),
7645 PtrEnd = CandidateTypes[Arg].pointer_end();
7646 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007647 QualType PointeeTy = (*Ptr)->getPointeeType();
7648 if (!PointeeTy->isObjectType())
7649 continue;
7650
Eric Christopher9207a522015-08-21 16:24:01 +00007651 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007652 if (Arg == 0 || Op == OO_Plus) {
7653 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7654 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007655 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007656 }
7657 if (Op == OO_Minus) {
7658 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007659 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007660 continue;
7661
7662 QualType ParamTypes[2] = { *Ptr, *Ptr };
7663 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007664 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007665 }
7666 }
7667 }
7668 }
7669
7670 // C++ [over.built]p12:
7671 //
7672 // For every pair of promoted arithmetic types L and R, there
7673 // exist candidate operator functions of the form
7674 //
7675 // LR operator*(L, R);
7676 // LR operator/(L, R);
7677 // LR operator+(L, R);
7678 // LR operator-(L, R);
7679 // bool operator<(L, R);
7680 // bool operator>(L, R);
7681 // bool operator<=(L, R);
7682 // bool operator>=(L, R);
7683 // bool operator==(L, R);
7684 // bool operator!=(L, R);
7685 //
7686 // where LR is the result of the usual arithmetic conversions
7687 // between types L and R.
7688 //
7689 // C++ [over.built]p24:
7690 //
7691 // For every pair of promoted arithmetic types L and R, there exist
7692 // candidate operator functions of the form
7693 //
7694 // LR operator?(bool, L, R);
7695 //
7696 // where LR is the result of the usual arithmetic conversions
7697 // between types L and R.
7698 // Our candidates ignore the first parameter.
7699 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007700 if (!HasArithmeticOrEnumeralCandidateType)
7701 return;
7702
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007703 for (unsigned Left = FirstPromotedArithmeticType;
7704 Left < LastPromotedArithmeticType; ++Left) {
7705 for (unsigned Right = FirstPromotedArithmeticType;
7706 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007707 QualType LandR[2] = { getArithmeticType(Left),
7708 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 QualType Result =
7710 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007711 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007712 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 }
7714 }
7715
7716 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7717 // conditional operator for vector types.
7718 for (BuiltinCandidateTypeSet::iterator
7719 Vec1 = CandidateTypes[0].vector_begin(),
7720 Vec1End = CandidateTypes[0].vector_end();
7721 Vec1 != Vec1End; ++Vec1) {
7722 for (BuiltinCandidateTypeSet::iterator
7723 Vec2 = CandidateTypes[1].vector_begin(),
7724 Vec2End = CandidateTypes[1].vector_end();
7725 Vec2 != Vec2End; ++Vec2) {
7726 QualType LandR[2] = { *Vec1, *Vec2 };
7727 QualType Result = S.Context.BoolTy;
7728 if (!isComparison) {
7729 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7730 Result = *Vec1;
7731 else
7732 Result = *Vec2;
7733 }
7734
Richard Smithe54c3072013-05-05 15:51:06 +00007735 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007736 }
7737 }
7738 }
7739
7740 // C++ [over.built]p17:
7741 //
7742 // For every pair of promoted integral types L and R, there
7743 // exist candidate operator functions of the form
7744 //
7745 // LR operator%(L, R);
7746 // LR operator&(L, R);
7747 // LR operator^(L, R);
7748 // LR operator|(L, R);
7749 // L operator<<(L, R);
7750 // L operator>>(L, R);
7751 //
7752 // where LR is the result of the usual arithmetic conversions
7753 // between types L and R.
7754 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007755 if (!HasArithmeticOrEnumeralCandidateType)
7756 return;
7757
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758 for (unsigned Left = FirstPromotedIntegralType;
7759 Left < LastPromotedIntegralType; ++Left) {
7760 for (unsigned Right = FirstPromotedIntegralType;
7761 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007762 QualType LandR[2] = { getArithmeticType(Left),
7763 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7765 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007766 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007767 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007768 }
7769 }
7770 }
7771
7772 // C++ [over.built]p20:
7773 //
7774 // For every pair (T, VQ), where T is an enumeration or
7775 // pointer to member type and VQ is either volatile or
7776 // empty, there exist candidate operator functions of the form
7777 //
7778 // VQ T& operator=(VQ T&, T);
7779 void addAssignmentMemberPointerOrEnumeralOverloads() {
7780 /// Set of (canonical) types that we've already handled.
7781 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7782
7783 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7784 for (BuiltinCandidateTypeSet::iterator
7785 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7786 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7787 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007788 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007789 continue;
7790
Richard Smithe54c3072013-05-05 15:51:06 +00007791 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007792 }
7793
7794 for (BuiltinCandidateTypeSet::iterator
7795 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7796 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7797 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007798 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007799 continue;
7800
Richard Smithe54c3072013-05-05 15:51:06 +00007801 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007802 }
7803 }
7804 }
7805
7806 // C++ [over.built]p19:
7807 //
7808 // For every pair (T, VQ), where T is any type and VQ is either
7809 // volatile or empty, there exist candidate operator functions
7810 // of the form
7811 //
7812 // T*VQ& operator=(T*VQ&, T*);
7813 //
7814 // C++ [over.built]p21:
7815 //
7816 // For every pair (T, VQ), where T is a cv-qualified or
7817 // cv-unqualified object type and VQ is either volatile or
7818 // empty, there exist candidate operator functions of the form
7819 //
7820 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7821 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7822 void addAssignmentPointerOverloads(bool isEqualOp) {
7823 /// Set of (canonical) types that we've already handled.
7824 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7825
7826 for (BuiltinCandidateTypeSet::iterator
7827 Ptr = CandidateTypes[0].pointer_begin(),
7828 PtrEnd = CandidateTypes[0].pointer_end();
7829 Ptr != PtrEnd; ++Ptr) {
7830 // If this is operator=, keep track of the builtin candidates we added.
7831 if (isEqualOp)
7832 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007833 else if (!(*Ptr)->getPointeeType()->isObjectType())
7834 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007835
7836 // non-volatile version
7837 QualType ParamTypes[2] = {
7838 S.Context.getLValueReferenceType(*Ptr),
7839 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7840 };
Richard Smithe54c3072013-05-05 15:51:06 +00007841 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007842 /*IsAssigmentOperator=*/ isEqualOp);
7843
Douglas Gregor5bee2582012-06-04 00:15:09 +00007844 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7845 VisibleTypeConversionsQuals.hasVolatile();
7846 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007847 // volatile version
7848 ParamTypes[0] =
7849 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007850 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007851 /*IsAssigmentOperator=*/isEqualOp);
7852 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007853
7854 if (!(*Ptr).isRestrictQualified() &&
7855 VisibleTypeConversionsQuals.hasRestrict()) {
7856 // restrict version
7857 ParamTypes[0]
7858 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007859 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007860 /*IsAssigmentOperator=*/isEqualOp);
7861
7862 if (NeedVolatile) {
7863 // volatile restrict version
7864 ParamTypes[0]
7865 = S.Context.getLValueReferenceType(
7866 S.Context.getCVRQualifiedType(*Ptr,
7867 (Qualifiers::Volatile |
7868 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007869 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007870 /*IsAssigmentOperator=*/isEqualOp);
7871 }
7872 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007873 }
7874
7875 if (isEqualOp) {
7876 for (BuiltinCandidateTypeSet::iterator
7877 Ptr = CandidateTypes[1].pointer_begin(),
7878 PtrEnd = CandidateTypes[1].pointer_end();
7879 Ptr != PtrEnd; ++Ptr) {
7880 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007881 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007882 continue;
7883
Chandler Carruth8e543b32010-12-12 08:17:55 +00007884 QualType ParamTypes[2] = {
7885 S.Context.getLValueReferenceType(*Ptr),
7886 *Ptr,
7887 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888
7889 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007890 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007891 /*IsAssigmentOperator=*/true);
7892
Douglas Gregor5bee2582012-06-04 00:15:09 +00007893 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7894 VisibleTypeConversionsQuals.hasVolatile();
7895 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007896 // volatile version
7897 ParamTypes[0] =
7898 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7900 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007901 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007902
7903 if (!(*Ptr).isRestrictQualified() &&
7904 VisibleTypeConversionsQuals.hasRestrict()) {
7905 // restrict version
7906 ParamTypes[0]
7907 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7909 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007910
7911 if (NeedVolatile) {
7912 // volatile restrict version
7913 ParamTypes[0]
7914 = S.Context.getLValueReferenceType(
7915 S.Context.getCVRQualifiedType(*Ptr,
7916 (Qualifiers::Volatile |
7917 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7919 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007920 }
7921 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007922 }
7923 }
7924 }
7925
7926 // C++ [over.built]p18:
7927 //
7928 // For every triple (L, VQ, R), where L is an arithmetic type,
7929 // VQ is either volatile or empty, and R is a promoted
7930 // arithmetic type, there exist candidate operator functions of
7931 // the form
7932 //
7933 // VQ L& operator=(VQ L&, R);
7934 // VQ L& operator*=(VQ L&, R);
7935 // VQ L& operator/=(VQ L&, R);
7936 // VQ L& operator+=(VQ L&, R);
7937 // VQ L& operator-=(VQ L&, R);
7938 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007939 if (!HasArithmeticOrEnumeralCandidateType)
7940 return;
7941
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007942 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7943 for (unsigned Right = FirstPromotedArithmeticType;
7944 Right < LastPromotedArithmeticType; ++Right) {
7945 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007946 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007947
7948 // Add this built-in operator as a candidate (VQ is empty).
7949 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007950 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007951 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007952 /*IsAssigmentOperator=*/isEqualOp);
7953
7954 // Add this built-in operator as a candidate (VQ is 'volatile').
7955 if (VisibleTypeConversionsQuals.hasVolatile()) {
7956 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007957 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007958 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007960 /*IsAssigmentOperator=*/isEqualOp);
7961 }
7962 }
7963 }
7964
7965 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7966 for (BuiltinCandidateTypeSet::iterator
7967 Vec1 = CandidateTypes[0].vector_begin(),
7968 Vec1End = CandidateTypes[0].vector_end();
7969 Vec1 != Vec1End; ++Vec1) {
7970 for (BuiltinCandidateTypeSet::iterator
7971 Vec2 = CandidateTypes[1].vector_begin(),
7972 Vec2End = CandidateTypes[1].vector_end();
7973 Vec2 != Vec2End; ++Vec2) {
7974 QualType ParamTypes[2];
7975 ParamTypes[1] = *Vec2;
7976 // Add this built-in operator as a candidate (VQ is empty).
7977 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007978 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 /*IsAssigmentOperator=*/isEqualOp);
7980
7981 // Add this built-in operator as a candidate (VQ is 'volatile').
7982 if (VisibleTypeConversionsQuals.hasVolatile()) {
7983 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7984 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007986 /*IsAssigmentOperator=*/isEqualOp);
7987 }
7988 }
7989 }
7990 }
7991
7992 // C++ [over.built]p22:
7993 //
7994 // For every triple (L, VQ, R), where L is an integral type, VQ
7995 // is either volatile or empty, and R is a promoted integral
7996 // type, there exist candidate operator functions of the form
7997 //
7998 // VQ L& operator%=(VQ L&, R);
7999 // VQ L& operator<<=(VQ L&, R);
8000 // VQ L& operator>>=(VQ L&, R);
8001 // VQ L& operator&=(VQ L&, R);
8002 // VQ L& operator^=(VQ L&, R);
8003 // VQ L& operator|=(VQ L&, R);
8004 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008005 if (!HasArithmeticOrEnumeralCandidateType)
8006 return;
8007
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008008 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8009 for (unsigned Right = FirstPromotedIntegralType;
8010 Right < LastPromotedIntegralType; ++Right) {
8011 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008012 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008013
8014 // Add this built-in operator as a candidate (VQ is empty).
8015 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008016 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008017 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008018 if (VisibleTypeConversionsQuals.hasVolatile()) {
8019 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008020 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008021 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8022 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008023 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008024 }
8025 }
8026 }
8027 }
8028
8029 // C++ [over.operator]p23:
8030 //
8031 // There also exist candidate operator functions of the form
8032 //
8033 // bool operator!(bool);
8034 // bool operator&&(bool, bool);
8035 // bool operator||(bool, bool);
8036 void addExclaimOverload() {
8037 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008038 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008039 /*IsAssignmentOperator=*/false,
8040 /*NumContextualBoolArguments=*/1);
8041 }
8042 void addAmpAmpOrPipePipeOverload() {
8043 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008044 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008045 /*IsAssignmentOperator=*/false,
8046 /*NumContextualBoolArguments=*/2);
8047 }
8048
8049 // C++ [over.built]p13:
8050 //
8051 // For every cv-qualified or cv-unqualified object type T there
8052 // exist candidate operator functions of the form
8053 //
8054 // T* operator+(T*, ptrdiff_t); [ABOVE]
8055 // T& operator[](T*, ptrdiff_t);
8056 // T* operator-(T*, ptrdiff_t); [ABOVE]
8057 // T* operator+(ptrdiff_t, T*); [ABOVE]
8058 // T& operator[](ptrdiff_t, T*);
8059 void addSubscriptOverloads() {
8060 for (BuiltinCandidateTypeSet::iterator
8061 Ptr = CandidateTypes[0].pointer_begin(),
8062 PtrEnd = CandidateTypes[0].pointer_end();
8063 Ptr != PtrEnd; ++Ptr) {
8064 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8065 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008066 if (!PointeeType->isObjectType())
8067 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008068
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8070
8071 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008072 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008073 }
8074
8075 for (BuiltinCandidateTypeSet::iterator
8076 Ptr = CandidateTypes[1].pointer_begin(),
8077 PtrEnd = CandidateTypes[1].pointer_end();
8078 Ptr != PtrEnd; ++Ptr) {
8079 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8080 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008081 if (!PointeeType->isObjectType())
8082 continue;
8083
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008084 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8085
8086 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008087 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008088 }
8089 }
8090
8091 // C++ [over.built]p11:
8092 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8093 // C1 is the same type as C2 or is a derived class of C2, T is an object
8094 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8095 // there exist candidate operator functions of the form
8096 //
8097 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8098 //
8099 // where CV12 is the union of CV1 and CV2.
8100 void addArrowStarOverloads() {
8101 for (BuiltinCandidateTypeSet::iterator
8102 Ptr = CandidateTypes[0].pointer_begin(),
8103 PtrEnd = CandidateTypes[0].pointer_end();
8104 Ptr != PtrEnd; ++Ptr) {
8105 QualType C1Ty = (*Ptr);
8106 QualType C1;
8107 QualifierCollector Q1;
8108 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8109 if (!isa<RecordType>(C1))
8110 continue;
8111 // heuristic to reduce number of builtin candidates in the set.
8112 // Add volatile/restrict version only if there are conversions to a
8113 // volatile/restrict type.
8114 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8115 continue;
8116 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8117 continue;
8118 for (BuiltinCandidateTypeSet::iterator
8119 MemPtr = CandidateTypes[1].member_pointer_begin(),
8120 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8121 MemPtr != MemPtrEnd; ++MemPtr) {
8122 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8123 QualType C2 = QualType(mptr->getClass(), 0);
8124 C2 = C2.getUnqualifiedType();
8125 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8126 break;
8127 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8128 // build CV12 T&
8129 QualType T = mptr->getPointeeType();
8130 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8131 T.isVolatileQualified())
8132 continue;
8133 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8134 T.isRestrictQualified())
8135 continue;
8136 T = Q1.apply(S.Context, T);
8137 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008138 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008139 }
8140 }
8141 }
8142
8143 // Note that we don't consider the first argument, since it has been
8144 // contextually converted to bool long ago. The candidates below are
8145 // therefore added as binary.
8146 //
8147 // C++ [over.built]p25:
8148 // For every type T, where T is a pointer, pointer-to-member, or scoped
8149 // enumeration type, there exist candidate operator functions of the form
8150 //
8151 // T operator?(bool, T, T);
8152 //
8153 void addConditionalOperatorOverloads() {
8154 /// Set of (canonical) types that we've already handled.
8155 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8156
8157 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8158 for (BuiltinCandidateTypeSet::iterator
8159 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8160 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8161 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008162 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008163 continue;
8164
8165 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008166 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008167 }
8168
8169 for (BuiltinCandidateTypeSet::iterator
8170 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8171 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8172 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008173 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008174 continue;
8175
8176 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008177 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008178 }
8179
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008180 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008181 for (BuiltinCandidateTypeSet::iterator
8182 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8183 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8184 Enum != EnumEnd; ++Enum) {
8185 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8186 continue;
8187
David Blaikie82e95a32014-11-19 07:49:47 +00008188 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008189 continue;
8190
8191 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008192 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008193 }
8194 }
8195 }
8196 }
8197};
8198
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008199} // end anonymous namespace
8200
8201/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8202/// operator overloads to the candidate set (C++ [over.built]), based
8203/// on the operator @p Op and the arguments given. For example, if the
8204/// operator is a binary '+', this routine might add "int
8205/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008206void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8207 SourceLocation OpLoc,
8208 ArrayRef<Expr *> Args,
8209 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008210 // Find all of the types that the arguments can convert to, but only
8211 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008212 // that make use of these types. Also record whether we encounter non-record
8213 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008214 Qualifiers VisibleTypeConversionsQuals;
8215 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008216 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008217 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008218
8219 bool HasNonRecordCandidateType = false;
8220 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008221 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008222 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008223 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008224 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8225 OpLoc,
8226 true,
8227 (Op == OO_Exclaim ||
8228 Op == OO_AmpAmp ||
8229 Op == OO_PipePipe),
8230 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008231 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8232 CandidateTypes[ArgIdx].hasNonRecordTypes();
8233 HasArithmeticOrEnumeralCandidateType =
8234 HasArithmeticOrEnumeralCandidateType ||
8235 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008236 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008237
Chandler Carruth00a38332010-12-13 01:44:01 +00008238 // Exit early when no non-record types have been added to the candidate set
8239 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008240 //
8241 // We can't exit early for !, ||, or &&, since there we have always have
8242 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008243 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008244 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008245 return;
8246
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008247 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008248 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008249 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008250 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008251 CandidateTypes, CandidateSet);
8252
8253 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008254 switch (Op) {
8255 case OO_None:
8256 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008257 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008258
Chandler Carruth5184de02010-12-12 08:51:33 +00008259 case OO_New:
8260 case OO_Delete:
8261 case OO_Array_New:
8262 case OO_Array_Delete:
8263 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008264 llvm_unreachable(
8265 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008266
8267 case OO_Comma:
8268 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008269 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008270 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008271 // -- For the operator ',', the unary operator '&', the
8272 // operator '->', or the operator 'co_await', the
8273 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008274 break;
8275
8276 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008277 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008278 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008279 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008280
8281 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008282 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008283 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008284 } else {
8285 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8286 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8287 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008288 break;
8289
Chandler Carruth5184de02010-12-12 08:51:33 +00008290 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008291 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008292 OpBuilder.addUnaryStarPointerOverloads();
8293 else
8294 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8295 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008296
Chandler Carruth5184de02010-12-12 08:51:33 +00008297 case OO_Slash:
8298 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008299 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008300
8301 case OO_PlusPlus:
8302 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008303 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8304 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008305 break;
8306
Douglas Gregor84605ae2009-08-24 13:43:27 +00008307 case OO_EqualEqual:
8308 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008309 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008310 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008311
Douglas Gregora11693b2008-11-12 17:17:38 +00008312 case OO_Less:
8313 case OO_Greater:
8314 case OO_LessEqual:
8315 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008316 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008317 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8318 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008319
Douglas Gregora11693b2008-11-12 17:17:38 +00008320 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008321 case OO_Caret:
8322 case OO_Pipe:
8323 case OO_LessLess:
8324 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008325 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008326 break;
8327
Chandler Carruth5184de02010-12-12 08:51:33 +00008328 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008329 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008330 // C++ [over.match.oper]p3:
8331 // -- For the operator ',', the unary operator '&', or the
8332 // operator '->', the built-in candidates set is empty.
8333 break;
8334
8335 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8336 break;
8337
8338 case OO_Tilde:
8339 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8340 break;
8341
Douglas Gregora11693b2008-11-12 17:17:38 +00008342 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008343 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008344 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008345
8346 case OO_PlusEqual:
8347 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008348 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008349 // Fall through.
8350
8351 case OO_StarEqual:
8352 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008353 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008354 break;
8355
8356 case OO_PercentEqual:
8357 case OO_LessLessEqual:
8358 case OO_GreaterGreaterEqual:
8359 case OO_AmpEqual:
8360 case OO_CaretEqual:
8361 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008362 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008363 break;
8364
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008365 case OO_Exclaim:
8366 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008367 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008368
Douglas Gregora11693b2008-11-12 17:17:38 +00008369 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008370 case OO_PipePipe:
8371 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008372 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008373
8374 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008375 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008376 break;
8377
8378 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008379 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008380 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008381
8382 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008383 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008384 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8385 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008386 }
8387}
8388
Douglas Gregore254f902009-02-04 00:32:51 +00008389/// \brief Add function candidates found via argument-dependent lookup
8390/// to the set of overloading candidates.
8391///
8392/// This routine performs argument-dependent name lookup based on the
8393/// given function name (which may also be an operator name) and adds
8394/// all of the overload candidates found by ADL to the overload
8395/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008396void
Douglas Gregore254f902009-02-04 00:32:51 +00008397Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008398 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008399 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008400 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008401 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008402 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008403 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008404
John McCall91f61fc2010-01-26 06:04:06 +00008405 // FIXME: This approach for uniquing ADL results (and removing
8406 // redundant candidates from the set) relies on pointer-equality,
8407 // which means we need to key off the canonical decl. However,
8408 // always going back to the canonical decl might not get us the
8409 // right set of default arguments. What default arguments are
8410 // we supposed to consider on ADL candidates, anyway?
8411
Douglas Gregorcabea402009-09-22 15:41:20 +00008412 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008413 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008414
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008415 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008416 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8417 CandEnd = CandidateSet.end();
8418 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008419 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008420 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008421 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008422 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008423 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008424
8425 // For each of the ADL candidates we found, add it to the overload
8426 // set.
John McCall8fe68082010-01-26 07:16:45 +00008427 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008428 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008429 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008430 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008431 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008432
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008433 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8434 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008435 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008436 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008437 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008438 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008439 }
Douglas Gregore254f902009-02-04 00:32:51 +00008440}
8441
George Burgess IV2a6150d2015-10-16 01:17:38 +00008442// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8443// Cand2 for overloading. This function assumes that all of the enable_if attrs
8444// on Cand1 and Cand2 have conditions that evaluate to true.
8445//
8446// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8447// Cand1's first N enable_if attributes have precisely the same conditions as
8448// Cand2's first N enable_if attributes (where N = the number of enable_if
8449// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8450static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8451 const FunctionDecl *Cand2) {
8452
8453 // FIXME: The next several lines are just
8454 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8455 // instead of reverse order which is how they're stored in the AST.
8456 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8457 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8458
8459 // Candidate 1 is better if it has strictly more attributes and
8460 // the common sequence is identical.
8461 if (Cand1Attrs.size() <= Cand2Attrs.size())
8462 return false;
8463
8464 auto Cand1I = Cand1Attrs.begin();
8465 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8466 for (auto &Cand2A : Cand2Attrs) {
8467 Cand1ID.clear();
8468 Cand2ID.clear();
8469
8470 auto &Cand1A = *Cand1I++;
8471 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8472 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8473 if (Cand1ID != Cand2ID)
8474 return false;
8475 }
8476
8477 return true;
8478}
8479
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008480/// isBetterOverloadCandidate - Determines whether the first overload
8481/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008482bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8483 const OverloadCandidate &Cand2,
8484 SourceLocation Loc,
8485 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008486 // Define viable functions to be better candidates than non-viable
8487 // functions.
8488 if (!Cand2.Viable)
8489 return Cand1.Viable;
8490 else if (!Cand1.Viable)
8491 return false;
8492
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008493 // C++ [over.match.best]p1:
8494 //
8495 // -- if F is a static member function, ICS1(F) is defined such
8496 // that ICS1(F) is neither better nor worse than ICS1(G) for
8497 // any function G, and, symmetrically, ICS1(G) is neither
8498 // better nor worse than ICS1(F).
8499 unsigned StartArg = 0;
8500 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8501 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008502
Douglas Gregord3cb3562009-07-07 23:38:56 +00008503 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008504 // A viable function F1 is defined to be a better function than another
8505 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008506 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008507 unsigned NumArgs = Cand1.NumConversions;
8508 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008509 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008510 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008511 switch (CompareImplicitConversionSequences(S,
8512 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008513 Cand2.Conversions[ArgIdx])) {
8514 case ImplicitConversionSequence::Better:
8515 // Cand1 has a better conversion sequence.
8516 HasBetterConversion = true;
8517 break;
8518
8519 case ImplicitConversionSequence::Worse:
8520 // Cand1 can't be better than Cand2.
8521 return false;
8522
8523 case ImplicitConversionSequence::Indistinguishable:
8524 // Do nothing.
8525 break;
8526 }
8527 }
8528
Mike Stump11289f42009-09-09 15:08:12 +00008529 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008530 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008531 if (HasBetterConversion)
8532 return true;
8533
Douglas Gregora1f013e2008-11-07 22:36:19 +00008534 // -- the context is an initialization by user-defined conversion
8535 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8536 // from the return type of F1 to the destination type (i.e.,
8537 // the type of the entity being initialized) is a better
8538 // conversion sequence than the standard conversion sequence
8539 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008540 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008541 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008542 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008543 // First check whether we prefer one of the conversion functions over the
8544 // other. This only distinguishes the results in non-standard, extension
8545 // cases such as the conversion from a lambda closure type to a function
8546 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008547 ImplicitConversionSequence::CompareKind Result =
8548 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8549 if (Result == ImplicitConversionSequence::Indistinguishable)
8550 Result = CompareStandardConversionSequences(S,
8551 Cand1.FinalConversion,
8552 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008553
Richard Smithec2748a2014-05-17 04:36:39 +00008554 if (Result != ImplicitConversionSequence::Indistinguishable)
8555 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008556
8557 // FIXME: Compare kind of reference binding if conversion functions
8558 // convert to a reference type used in direct reference binding, per
8559 // C++14 [over.match.best]p1 section 2 bullet 3.
8560 }
8561
8562 // -- F1 is a non-template function and F2 is a function template
8563 // specialization, or, if not that,
8564 bool Cand1IsSpecialization = Cand1.Function &&
8565 Cand1.Function->getPrimaryTemplate();
8566 bool Cand2IsSpecialization = Cand2.Function &&
8567 Cand2.Function->getPrimaryTemplate();
8568 if (Cand1IsSpecialization != Cand2IsSpecialization)
8569 return Cand2IsSpecialization;
8570
8571 // -- F1 and F2 are function template specializations, and the function
8572 // template for F1 is more specialized than the template for F2
8573 // according to the partial ordering rules described in 14.5.5.2, or,
8574 // if not that,
8575 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8576 if (FunctionTemplateDecl *BetterTemplate
8577 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8578 Cand2.Function->getPrimaryTemplate(),
8579 Loc,
8580 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8581 : TPOC_Call,
8582 Cand1.ExplicitCallArguments,
8583 Cand2.ExplicitCallArguments))
8584 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008585 }
8586
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008587 // Check for enable_if value-based overload resolution.
8588 if (Cand1.Function && Cand2.Function &&
8589 (Cand1.Function->hasAttr<EnableIfAttr>() ||
George Burgess IV2a6150d2015-10-16 01:17:38 +00008590 Cand2.Function->hasAttr<EnableIfAttr>()))
8591 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008592
Artem Belevich94a55e82015-09-22 17:22:59 +00008593 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8594 Cand1.Function && Cand2.Function) {
8595 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8596 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8597 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8598 }
8599
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008600 bool HasPS1 = Cand1.Function != nullptr &&
8601 functionHasPassObjectSizeParams(Cand1.Function);
8602 bool HasPS2 = Cand2.Function != nullptr &&
8603 functionHasPassObjectSizeParams(Cand2.Function);
8604 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008605}
8606
Richard Smith2dbe4042015-11-04 19:26:32 +00008607/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008608/// name lookup and overload resolution. This applies when the same internal/no
8609/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008610/// the same header). In such a case, we don't consider the declarations to
8611/// declare the same entity, but we also don't want lookups with both
8612/// declarations visible to be ambiguous in some cases (this happens when using
8613/// a modularized libstdc++).
8614bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8615 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008616 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8617 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8618 if (!VA || !VB)
8619 return false;
8620
8621 // The declarations must be declaring the same name as an internal linkage
8622 // entity in different modules.
8623 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8624 VB->getDeclContext()->getRedeclContext()) ||
8625 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8626 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8627 VA->isExternallyVisible() || VB->isExternallyVisible())
8628 return false;
8629
8630 // Check that the declarations appear to be equivalent.
8631 //
8632 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8633 // For constants and functions, we should check the initializer or body is
8634 // the same. For non-constant variables, we shouldn't allow it at all.
8635 if (Context.hasSameType(VA->getType(), VB->getType()))
8636 return true;
8637
8638 // Enum constants within unnamed enumerations will have different types, but
8639 // may still be similar enough to be interchangeable for our purposes.
8640 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8641 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8642 // Only handle anonymous enums. If the enumerations were named and
8643 // equivalent, they would have been merged to the same type.
8644 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8645 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8646 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8647 !Context.hasSameType(EnumA->getIntegerType(),
8648 EnumB->getIntegerType()))
8649 return false;
8650 // Allow this only if the value is the same for both enumerators.
8651 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8652 }
8653 }
8654
8655 // Nothing else is sufficiently similar.
8656 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008657}
8658
8659void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8660 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8661 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8662
8663 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8664 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8665 << !M << (M ? M->getFullModuleName() : "");
8666
8667 for (auto *E : Equiv) {
8668 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8669 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8670 << !M << (M ? M->getFullModuleName() : "");
8671 }
Richard Smith896c66e2015-10-21 07:13:52 +00008672}
8673
Mike Stump11289f42009-09-09 15:08:12 +00008674/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008675/// within an overload candidate set.
8676///
James Dennettffad8b72012-06-22 08:10:18 +00008677/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008678/// which overload resolution occurs.
8679///
James Dennettffad8b72012-06-22 08:10:18 +00008680/// \param Best If overload resolution was successful or found a deleted
8681/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008682///
8683/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008684OverloadingResult
8685OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008686 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008687 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008688 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008689 Best = end();
8690 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8691 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008692 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008693 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008694 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008695 }
8696
8697 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008698 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008699 return OR_No_Viable_Function;
8700
Richard Smith2dbe4042015-11-04 19:26:32 +00008701 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008702
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008703 // Make sure that this function is better than every other viable
8704 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008705 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008706 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008707 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008708 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008709 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008710 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8711 Cand->Function)) {
8712 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008713 continue;
8714 }
8715
John McCall5c32be02010-08-24 20:38:10 +00008716 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008717 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008718 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008719 }
Mike Stump11289f42009-09-09 15:08:12 +00008720
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008721 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008722 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008723 (Best->Function->isDeleted() ||
8724 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008725 return OR_Deleted;
8726
Richard Smith2dbe4042015-11-04 19:26:32 +00008727 if (!EquivalentCands.empty())
8728 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8729 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008730
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008731 return OR_Success;
8732}
8733
John McCall53262c92010-01-12 02:15:36 +00008734namespace {
8735
8736enum OverloadCandidateKind {
8737 oc_function,
8738 oc_method,
8739 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008740 oc_function_template,
8741 oc_method_template,
8742 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008743 oc_implicit_default_constructor,
8744 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008745 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008746 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008747 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008748 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008749};
8750
John McCalle1ac8d12010-01-13 00:25:19 +00008751OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8752 FunctionDecl *Fn,
8753 std::string &Description) {
8754 bool isTemplate = false;
8755
8756 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8757 isTemplate = true;
8758 Description = S.getTemplateArgumentBindingsText(
8759 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8760 }
John McCallfd0b2f82010-01-06 09:43:14 +00008761
8762 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008763 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008764 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008765
Sebastian Redl08905022011-02-05 19:23:19 +00008766 if (Ctor->getInheritedConstructor())
8767 return oc_implicit_inherited_constructor;
8768
Alexis Hunt119c10e2011-05-25 23:16:36 +00008769 if (Ctor->isDefaultConstructor())
8770 return oc_implicit_default_constructor;
8771
8772 if (Ctor->isMoveConstructor())
8773 return oc_implicit_move_constructor;
8774
8775 assert(Ctor->isCopyConstructor() &&
8776 "unexpected sort of implicit constructor");
8777 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008778 }
8779
8780 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8781 // This actually gets spelled 'candidate function' for now, but
8782 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008783 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008784 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008785
Alexis Hunt119c10e2011-05-25 23:16:36 +00008786 if (Meth->isMoveAssignmentOperator())
8787 return oc_implicit_move_assignment;
8788
Douglas Gregor12695102012-02-10 08:36:38 +00008789 if (Meth->isCopyAssignmentOperator())
8790 return oc_implicit_copy_assignment;
8791
8792 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8793 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008794 }
8795
John McCalle1ac8d12010-01-13 00:25:19 +00008796 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008797}
8798
Larisse Voufo98b20f12013-07-19 23:00:19 +00008799void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008800 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8801 if (!Ctor) return;
8802
8803 Ctor = Ctor->getInheritedConstructor();
8804 if (!Ctor) return;
8805
8806 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8807}
8808
John McCall53262c92010-01-12 02:15:36 +00008809} // end anonymous namespace
8810
George Burgess IV5f21c712015-10-12 19:57:04 +00008811static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8812 const FunctionDecl *FD) {
8813 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8814 bool AlwaysTrue;
8815 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8816 return false;
8817 if (!AlwaysTrue)
8818 return false;
8819 }
8820 return true;
8821}
8822
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008823/// \brief Returns true if we can take the address of the function.
8824///
8825/// \param Complain - If true, we'll emit a diagnostic
8826/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8827/// we in overload resolution?
8828/// \param Loc - The location of the statement we're complaining about. Ignored
8829/// if we're not complaining, or if we're in overload resolution.
8830static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8831 bool Complain,
8832 bool InOverloadResolution,
8833 SourceLocation Loc) {
8834 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8835 if (Complain) {
8836 // FIXME(gbiv): Both diagnostics below lack tests. We should add tests.
8837 if (InOverloadResolution)
8838 S.Diag(FD->getLocStart(),
8839 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8840 else
8841 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8842 }
8843 return false;
8844 }
8845
8846 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8847 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8848 if (I == FD->param_end())
8849 return true;
8850
8851 if (Complain) {
8852 // Add one to ParamNo because it's user-facing
8853 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8854 if (InOverloadResolution)
8855 S.Diag(FD->getLocation(),
8856 diag::note_ovl_candidate_has_pass_object_size_params)
8857 << ParamNo;
8858 else
8859 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8860 << FD << ParamNo;
8861 }
8862 return false;
8863}
8864
8865static bool checkAddressOfCandidateIsAvailable(Sema &S,
8866 const FunctionDecl *FD) {
8867 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8868 /*InOverloadResolution=*/true,
8869 /*Loc=*/SourceLocation());
8870}
8871
8872bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8873 bool Complain,
8874 SourceLocation Loc) {
8875 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8876 /*InOverloadResolution=*/false,
8877 Loc);
8878}
8879
John McCall53262c92010-01-12 02:15:36 +00008880// Notes the location of an overload candidate.
George Burgess IV5f21c712015-10-12 19:57:04 +00008881void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8882 bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008883 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8884 return;
8885
John McCalle1ac8d12010-01-13 00:25:19 +00008886 std::string FnDesc;
8887 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008888 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8889 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008890
8891 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00008892 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008893 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008894}
8895
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008896// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008897// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00008898void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8899 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008900 assert(OverloadedExpr->getType() == Context.OverloadTy);
8901
8902 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8903 OverloadExpr *OvlExpr = Ovl.Expression;
8904
8905 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8906 IEnd = OvlExpr->decls_end();
8907 I != IEnd; ++I) {
8908 if (FunctionTemplateDecl *FunTmpl =
8909 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008910 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8911 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008912 } else if (FunctionDecl *Fun
8913 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
George Burgess IV5f21c712015-10-12 19:57:04 +00008914 NoteOverloadCandidate(Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008915 }
8916 }
8917}
8918
John McCall0d1da222010-01-12 00:44:57 +00008919/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8920/// "lead" diagnostic; it will be given two arguments, the source and
8921/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008922void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8923 Sema &S,
8924 SourceLocation CaretLoc,
8925 const PartialDiagnostic &PDiag) const {
8926 S.Diag(CaretLoc, PDiag)
8927 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008928 // FIXME: The note limiting machinery is borrowed from
8929 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8930 // refactoring here.
8931 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8932 unsigned CandsShown = 0;
8933 AmbiguousConversionSequence::const_iterator I, E;
8934 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8935 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8936 break;
8937 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008938 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008939 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008940 if (I != E)
8941 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008942}
8943
Richard Smith17c00b42014-11-12 01:24:00 +00008944static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008945 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00008946 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8947 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008948 assert(Cand->Function && "for now, candidate must be a function");
8949 FunctionDecl *Fn = Cand->Function;
8950
8951 // There's a conversion slot for the object argument if this is a
8952 // non-constructor method. Note that 'I' corresponds the
8953 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008954 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008955 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008956 if (I == 0)
8957 isObjectArgument = true;
8958 else
8959 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008960 }
8961
John McCalle1ac8d12010-01-13 00:25:19 +00008962 std::string FnDesc;
8963 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8964
John McCall6a61b522010-01-13 09:16:55 +00008965 Expr *FromExpr = Conv.Bad.FromExpr;
8966 QualType FromTy = Conv.Bad.getFromType();
8967 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008968
John McCallfb7ad0f2010-02-02 02:42:52 +00008969 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008970 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008971 Expr *E = FromExpr->IgnoreParens();
8972 if (isa<UnaryOperator>(E))
8973 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008974 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008975
8976 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8977 << (unsigned) FnKind << FnDesc
8978 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8979 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008980 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008981 return;
8982 }
8983
John McCall6d174642010-01-23 08:10:49 +00008984 // Do some hand-waving analysis to see if the non-viability is due
8985 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008986 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8987 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8988 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8989 CToTy = RT->getPointeeType();
8990 else {
8991 // TODO: detect and diagnose the full richness of const mismatches.
8992 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8993 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8994 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8995 }
8996
8997 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8998 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008999 Qualifiers FromQs = CFromTy.getQualifiers();
9000 Qualifiers ToQs = CToTy.getQualifiers();
9001
9002 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9003 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9004 << (unsigned) FnKind << FnDesc
9005 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9006 << FromTy
9007 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9008 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009009 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009010 return;
9011 }
9012
John McCall31168b02011-06-15 23:02:42 +00009013 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009015 << (unsigned) FnKind << FnDesc
9016 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9017 << FromTy
9018 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9019 << (unsigned) isObjectArgument << I+1;
9020 MaybeEmitInheritedConstructorNote(S, Fn);
9021 return;
9022 }
9023
Douglas Gregoraec25842011-04-26 23:16:46 +00009024 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9025 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9026 << (unsigned) FnKind << FnDesc
9027 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9028 << FromTy
9029 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9030 << (unsigned) isObjectArgument << I+1;
9031 MaybeEmitInheritedConstructorNote(S, Fn);
9032 return;
9033 }
9034
John McCall47000992010-01-14 03:28:57 +00009035 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9036 assert(CVR && "unexpected qualifiers mismatch");
9037
9038 if (isObjectArgument) {
9039 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9040 << (unsigned) FnKind << FnDesc
9041 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9042 << FromTy << (CVR - 1);
9043 } else {
9044 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9045 << (unsigned) FnKind << FnDesc
9046 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9047 << FromTy << (CVR - 1) << I+1;
9048 }
Sebastian Redl08905022011-02-05 19:23:19 +00009049 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00009050 return;
9051 }
9052
Sebastian Redla72462c2011-09-24 17:48:32 +00009053 // Special diagnostic for failure to convert an initializer list, since
9054 // telling the user that it has type void is not useful.
9055 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9057 << (unsigned) FnKind << FnDesc
9058 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9059 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9060 MaybeEmitInheritedConstructorNote(S, Fn);
9061 return;
9062 }
9063
John McCall6d174642010-01-23 08:10:49 +00009064 // Diagnose references or pointers to incomplete types differently,
9065 // since it's far from impossible that the incompleteness triggered
9066 // the failure.
9067 QualType TempFromTy = FromTy.getNonReferenceType();
9068 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9069 TempFromTy = PTy->getPointeeType();
9070 if (TempFromTy->isIncompleteType()) {
9071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9072 << (unsigned) FnKind << FnDesc
9073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9074 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009075 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00009076 return;
9077 }
9078
Douglas Gregor56f2e342010-06-30 23:01:39 +00009079 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009080 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009081 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9082 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9083 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9084 FromPtrTy->getPointeeType()) &&
9085 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9086 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009087 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009088 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009089 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009090 }
9091 } else if (const ObjCObjectPointerType *FromPtrTy
9092 = FromTy->getAs<ObjCObjectPointerType>()) {
9093 if (const ObjCObjectPointerType *ToPtrTy
9094 = ToTy->getAs<ObjCObjectPointerType>())
9095 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9096 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9097 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9098 FromPtrTy->getPointeeType()) &&
9099 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009100 BaseToDerivedConversion = 2;
9101 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009102 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9103 !FromTy->isIncompleteType() &&
9104 !ToRefTy->getPointeeType()->isIncompleteType() &&
9105 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
9106 BaseToDerivedConversion = 3;
9107 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9108 ToTy.getNonReferenceType().getCanonicalType() ==
9109 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9111 << (unsigned) FnKind << FnDesc
9112 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9113 << (unsigned) isObjectArgument << I + 1;
9114 MaybeEmitInheritedConstructorNote(S, Fn);
9115 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009116 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009118
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009119 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009120 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009121 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009122 << (unsigned) FnKind << FnDesc
9123 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009124 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009125 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00009126 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009127 return;
9128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009129
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009130 if (isa<ObjCObjectPointerType>(CFromTy) &&
9131 isa<PointerType>(CToTy)) {
9132 Qualifiers FromQs = CFromTy.getQualifiers();
9133 Qualifiers ToQs = CToTy.getQualifiers();
9134 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9136 << (unsigned) FnKind << FnDesc
9137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9139 MaybeEmitInheritedConstructorNote(S, Fn);
9140 return;
9141 }
9142 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009143
9144 if (TakingCandidateAddress &&
9145 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9146 return;
9147
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009148 // Emit the generic diagnostic and, optionally, add the hints to it.
9149 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9150 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009151 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009152 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9153 << (unsigned) (Cand->Fix.Kind);
9154
9155 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009156 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9157 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009158 FDiag << *HI;
9159 S.Diag(Fn->getLocation(), FDiag);
9160
Sebastian Redl08905022011-02-05 19:23:19 +00009161 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00009162}
9163
Larisse Voufo98b20f12013-07-19 23:00:19 +00009164/// Additional arity mismatch diagnosis specific to a function overload
9165/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9166/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009167static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9168 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009169 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009170 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009171
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009172 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009173 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009174 // right number of arguments, because only overloaded operators have
9175 // the weird behavior of overloading member and non-member functions.
9176 // Just don't report anything.
9177 if (Fn->isInvalidDecl() &&
9178 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009179 return true;
9180
9181 if (NumArgs < MinParams) {
9182 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9183 (Cand->FailureKind == ovl_fail_bad_deduction &&
9184 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9185 } else {
9186 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9187 (Cand->FailureKind == ovl_fail_bad_deduction &&
9188 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9189 }
9190
9191 return false;
9192}
9193
9194/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009195static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009196 assert(isa<FunctionDecl>(D) &&
9197 "The templated declaration should at least be a function"
9198 " when diagnosing bad template argument deduction due to too many"
9199 " or too few arguments");
9200
9201 FunctionDecl *Fn = cast<FunctionDecl>(D);
9202
9203 // TODO: treat calls to a missing default constructor as a special case
9204 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9205 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009206
John McCall6a61b522010-01-13 09:16:55 +00009207 // at least / at most / exactly
9208 unsigned mode, modeCount;
9209 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009210 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9211 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009212 mode = 0; // "at least"
9213 else
9214 mode = 2; // "exactly"
9215 modeCount = MinParams;
9216 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009217 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009218 mode = 1; // "at most"
9219 else
9220 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009221 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009222 }
9223
9224 std::string Description;
9225 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9226
Richard Smith10ff50d2012-05-11 05:16:41 +00009227 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009229 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9230 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009231 else
9232 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009233 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9234 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00009235 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009236}
9237
Larisse Voufo98b20f12013-07-19 23:00:19 +00009238/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009239static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9240 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009241 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9242 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9243}
Larisse Voufo47c08452013-07-19 22:53:23 +00009244
Richard Smith17c00b42014-11-12 01:24:00 +00009245static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9247 return FD->getDescribedFunctionTemplate();
9248 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9249 return RD->getDescribedClassTemplate();
9250
9251 llvm_unreachable("Unsupported: Getting the described template declaration"
9252 " for bad deduction diagnosis");
9253}
9254
9255/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009256static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9257 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009258 unsigned NumArgs,
9259 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009260 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009261 NamedDecl *ParamD;
9262 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9263 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9264 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009265 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009266 case Sema::TDK_Success:
9267 llvm_unreachable("TDK_success while diagnosing bad deduction");
9268
9269 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009270 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009271 S.Diag(Templated->getLocation(),
9272 diag::note_ovl_candidate_incomplete_deduction)
9273 << ParamD->getDeclName();
9274 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009275 return;
9276 }
9277
John McCall42d7d192010-08-05 09:05:08 +00009278 case Sema::TDK_Underqualified: {
9279 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9280 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9281
Larisse Voufo98b20f12013-07-19 23:00:19 +00009282 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009283
9284 // Param will have been canonicalized, but it should just be a
9285 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009286 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009287 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009288 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009289 assert(S.Context.hasSameType(Param, NonCanonParam));
9290
9291 // Arg has also been canonicalized, but there's nothing we can do
9292 // about that. It also doesn't matter as much, because it won't
9293 // have any template parameters in it (because deduction isn't
9294 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009295 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009296
Larisse Voufo98b20f12013-07-19 23:00:19 +00009297 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9298 << ParamD->getDeclName() << Arg << NonCanonParam;
9299 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009300 return;
9301 }
9302
9303 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009304 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009305 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009306 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009307 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009308 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009309 which = 1;
9310 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009311 which = 2;
9312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009313
Larisse Voufo98b20f12013-07-19 23:00:19 +00009314 S.Diag(Templated->getLocation(),
9315 diag::note_ovl_candidate_inconsistent_deduction)
9316 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9317 << *DeductionFailure.getSecondArg();
9318 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009319 return;
9320 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009321
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009322 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009323 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009324 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009325 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009326 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009327 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009328 else {
9329 int index = 0;
9330 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9331 index = TTP->getIndex();
9332 else if (NonTypeTemplateParmDecl *NTTP
9333 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9334 index = NTTP->getIndex();
9335 else
9336 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009337 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009338 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009339 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009340 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009341 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009342 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009343
Douglas Gregor02eb4832010-05-08 18:13:28 +00009344 case Sema::TDK_TooManyArguments:
9345 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009346 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009347 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009348
9349 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009350 S.Diag(Templated->getLocation(),
9351 diag::note_ovl_candidate_instantiation_depth);
9352 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009353 return;
9354
9355 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009356 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009357 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009358 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009359 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009360 TemplateArgString = " ";
9361 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009362 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009363 }
9364
Richard Smith6f8d2c62012-05-09 05:17:00 +00009365 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009366 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009367 if (PDiag && PDiag->second.getDiagID() ==
9368 diag::err_typename_nested_not_found_enable_if) {
9369 // FIXME: Use the source range of the condition, and the fully-qualified
9370 // name of the enable_if template. These are both present in PDiag.
9371 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9372 << "'enable_if'" << TemplateArgString;
9373 return;
9374 }
9375
Richard Smith9ca64612012-05-07 09:03:25 +00009376 // Format the SFINAE diagnostic into the argument string.
9377 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9378 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009379 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009380 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009381 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009382 SFINAEArgString = ": ";
9383 R = SourceRange(PDiag->first, PDiag->first);
9384 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9385 }
9386
Larisse Voufo98b20f12013-07-19 23:00:19 +00009387 S.Diag(Templated->getLocation(),
9388 diag::note_ovl_candidate_substitution_failure)
9389 << TemplateArgString << SFINAEArgString << R;
9390 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009391 return;
9392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009393
Richard Smith8c6eeb92013-01-31 04:03:12 +00009394 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009395 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9396 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009397 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009398 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009399 return;
9400 }
9401
Richard Trieue3732352013-04-08 21:11:40 +00009402 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009403 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009404 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9405 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009406 if (FirstTA.getKind() == TemplateArgument::Template &&
9407 SecondTA.getKind() == TemplateArgument::Template) {
9408 TemplateName FirstTN = FirstTA.getAsTemplate();
9409 TemplateName SecondTN = SecondTA.getAsTemplate();
9410 if (FirstTN.getKind() == TemplateName::Template &&
9411 SecondTN.getKind() == TemplateName::Template) {
9412 if (FirstTN.getAsTemplateDecl()->getName() ==
9413 SecondTN.getAsTemplateDecl()->getName()) {
9414 // FIXME: This fixes a bad diagnostic where both templates are named
9415 // the same. This particular case is a bit difficult since:
9416 // 1) It is passed as a string to the diagnostic printer.
9417 // 2) The diagnostic printer only attempts to find a better
9418 // name for types, not decls.
9419 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009420 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009421 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9422 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9423 return;
9424 }
9425 }
9426 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009427
9428 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9429 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9430 return;
9431
Faisal Vali2b391ab2013-09-26 19:54:12 +00009432 // FIXME: For generic lambda parameters, check if the function is a lambda
9433 // call operator, and if so, emit a prettier and more informative
9434 // diagnostic that mentions 'auto' and lambda in addition to
9435 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009436 S.Diag(Templated->getLocation(),
9437 diag::note_ovl_candidate_non_deduced_mismatch)
9438 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009439 return;
Richard Trieue3732352013-04-08 21:11:40 +00009440 }
John McCall8b9ed552010-02-01 18:53:26 +00009441 // TODO: diagnose these individually, then kill off
9442 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009443 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009444 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9445 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009446 return;
9447 }
9448}
9449
Larisse Voufo98b20f12013-07-19 23:00:19 +00009450/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009451static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009452 unsigned NumArgs,
9453 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009454 unsigned TDK = Cand->DeductionFailure.Result;
9455 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9456 if (CheckArityMismatch(S, Cand, NumArgs))
9457 return;
9458 }
9459 DiagnoseBadDeduction(S, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009460 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009461}
9462
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009463/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009464static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009465 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9466 FunctionDecl *Callee = Cand->Function;
9467
9468 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9469 CalleeTarget = S.IdentifyCUDATarget(Callee);
9470
9471 std::string FnDesc;
9472 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9473
9474 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009475 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9476
9477 // This could be an implicit constructor for which we could not infer the
9478 // target due to a collsion. Diagnose that case.
9479 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9480 if (Meth != nullptr && Meth->isImplicit()) {
9481 CXXRecordDecl *ParentClass = Meth->getParent();
9482 Sema::CXXSpecialMember CSM;
9483
9484 switch (FnKind) {
9485 default:
9486 return;
9487 case oc_implicit_default_constructor:
9488 CSM = Sema::CXXDefaultConstructor;
9489 break;
9490 case oc_implicit_copy_constructor:
9491 CSM = Sema::CXXCopyConstructor;
9492 break;
9493 case oc_implicit_move_constructor:
9494 CSM = Sema::CXXMoveConstructor;
9495 break;
9496 case oc_implicit_copy_assignment:
9497 CSM = Sema::CXXCopyAssignment;
9498 break;
9499 case oc_implicit_move_assignment:
9500 CSM = Sema::CXXMoveAssignment;
9501 break;
9502 };
9503
9504 bool ConstRHS = false;
9505 if (Meth->getNumParams()) {
9506 if (const ReferenceType *RT =
9507 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9508 ConstRHS = RT->getPointeeType().isConstQualified();
9509 }
9510 }
9511
9512 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9513 /* ConstRHS */ ConstRHS,
9514 /* Diagnose */ true);
9515 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009516}
9517
Richard Smith17c00b42014-11-12 01:24:00 +00009518static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009519 FunctionDecl *Callee = Cand->Function;
9520 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9521
9522 S.Diag(Callee->getLocation(),
9523 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9524 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9525}
9526
John McCall8b9ed552010-02-01 18:53:26 +00009527/// Generates a 'note' diagnostic for an overload candidate. We've
9528/// already generated a primary error at the call site.
9529///
9530/// It really does need to be a single diagnostic with its caret
9531/// pointed at the candidate declaration. Yes, this creates some
9532/// major challenges of technical writing. Yes, this makes pointing
9533/// out problems with specific arguments quite awkward. It's still
9534/// better than generating twenty screens of text for every failed
9535/// overload.
9536///
9537/// It would be great to be able to express per-candidate problems
9538/// more richly for those diagnostic clients that cared, but we'd
9539/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009540static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009541 unsigned NumArgs,
9542 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009543 FunctionDecl *Fn = Cand->Function;
9544
John McCall12f97bc2010-01-08 04:41:39 +00009545 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009546 if (Cand->Viable && (Fn->isDeleted() ||
9547 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009548 std::string FnDesc;
9549 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009550
9551 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009552 << FnKind << FnDesc
9553 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009554 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009555 return;
John McCall12f97bc2010-01-08 04:41:39 +00009556 }
9557
John McCalle1ac8d12010-01-13 00:25:19 +00009558 // We don't really have anything else to say about viable candidates.
9559 if (Cand->Viable) {
9560 S.NoteOverloadCandidate(Fn);
9561 return;
9562 }
John McCall0d1da222010-01-12 00:44:57 +00009563
John McCall6a61b522010-01-13 09:16:55 +00009564 switch (Cand->FailureKind) {
9565 case ovl_fail_too_many_arguments:
9566 case ovl_fail_too_few_arguments:
9567 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009568
John McCall6a61b522010-01-13 09:16:55 +00009569 case ovl_fail_bad_deduction:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009570 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009571
John McCall578a1f82014-12-14 01:46:53 +00009572 case ovl_fail_illegal_constructor: {
9573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9574 << (Fn->getPrimaryTemplate() ? 1 : 0);
9575 MaybeEmitInheritedConstructorNote(S, Fn);
9576 return;
9577 }
9578
John McCallfe796dd2010-01-23 05:17:32 +00009579 case ovl_fail_trivial_conversion:
9580 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009581 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009582 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009583
John McCall65eb8792010-02-25 01:37:24 +00009584 case ovl_fail_bad_conversion: {
9585 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009586 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009587 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009588 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009589
John McCall6a61b522010-01-13 09:16:55 +00009590 // FIXME: this currently happens when we're called from SemaInit
9591 // when user-conversion overload fails. Figure out how to handle
9592 // those conditions and diagnose them well.
9593 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009594 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009595
9596 case ovl_fail_bad_target:
9597 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009598
9599 case ovl_fail_enable_if:
9600 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009601 }
John McCalld3224162010-01-08 00:58:21 +00009602}
9603
Richard Smith17c00b42014-11-12 01:24:00 +00009604static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009605 // Desugar the type of the surrogate down to a function type,
9606 // retaining as many typedefs as possible while still showing
9607 // the function type (and, therefore, its parameter types).
9608 QualType FnType = Cand->Surrogate->getConversionType();
9609 bool isLValueReference = false;
9610 bool isRValueReference = false;
9611 bool isPointer = false;
9612 if (const LValueReferenceType *FnTypeRef =
9613 FnType->getAs<LValueReferenceType>()) {
9614 FnType = FnTypeRef->getPointeeType();
9615 isLValueReference = true;
9616 } else if (const RValueReferenceType *FnTypeRef =
9617 FnType->getAs<RValueReferenceType>()) {
9618 FnType = FnTypeRef->getPointeeType();
9619 isRValueReference = true;
9620 }
9621 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9622 FnType = FnTypePtr->getPointeeType();
9623 isPointer = true;
9624 }
9625 // Desugar down to a function type.
9626 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9627 // Reconstruct the pointer/reference as appropriate.
9628 if (isPointer) FnType = S.Context.getPointerType(FnType);
9629 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9630 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9631
9632 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9633 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009634 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009635}
9636
Richard Smith17c00b42014-11-12 01:24:00 +00009637static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9638 SourceLocation OpLoc,
9639 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009640 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009641 std::string TypeStr("operator");
9642 TypeStr += Opc;
9643 TypeStr += "(";
9644 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009645 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009646 TypeStr += ")";
9647 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9648 } else {
9649 TypeStr += ", ";
9650 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9651 TypeStr += ")";
9652 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9653 }
9654}
9655
Richard Smith17c00b42014-11-12 01:24:00 +00009656static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9657 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009658 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009659 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9660 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009661 if (ICS.isBad()) break; // all meaningless after first invalid
9662 if (!ICS.isAmbiguous()) continue;
9663
John McCall5c32be02010-08-24 20:38:10 +00009664 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009665 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009666 }
9667}
9668
Larisse Voufo98b20f12013-07-19 23:00:19 +00009669static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009670 if (Cand->Function)
9671 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009672 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009673 return Cand->Surrogate->getLocation();
9674 return SourceLocation();
9675}
9676
Larisse Voufo98b20f12013-07-19 23:00:19 +00009677static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009678 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009679 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009680 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009681
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009682 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009683 case Sema::TDK_Incomplete:
9684 return 1;
9685
9686 case Sema::TDK_Underqualified:
9687 case Sema::TDK_Inconsistent:
9688 return 2;
9689
9690 case Sema::TDK_SubstitutionFailure:
9691 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009692 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009693 return 3;
9694
9695 case Sema::TDK_InstantiationDepth:
9696 case Sema::TDK_FailedOverloadResolution:
9697 return 4;
9698
9699 case Sema::TDK_InvalidExplicitArguments:
9700 return 5;
9701
9702 case Sema::TDK_TooManyArguments:
9703 case Sema::TDK_TooFewArguments:
9704 return 6;
9705 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009706 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009707}
9708
Richard Smith17c00b42014-11-12 01:24:00 +00009709namespace {
John McCallad2587a2010-01-12 00:48:53 +00009710struct CompareOverloadCandidatesForDisplay {
9711 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009712 size_t NumArgs;
9713
9714 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9715 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009716
9717 bool operator()(const OverloadCandidate *L,
9718 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009719 // Fast-path this check.
9720 if (L == R) return false;
9721
John McCall12f97bc2010-01-08 04:41:39 +00009722 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009723 if (L->Viable) {
9724 if (!R->Viable) return true;
9725
9726 // TODO: introduce a tri-valued comparison for overload
9727 // candidates. Would be more worthwhile if we had a sort
9728 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009729 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9730 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009731 } else if (R->Viable)
9732 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009733
John McCall3712d9e2010-01-15 23:32:50 +00009734 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009735
John McCall3712d9e2010-01-15 23:32:50 +00009736 // Criteria by which we can sort non-viable candidates:
9737 if (!L->Viable) {
9738 // 1. Arity mismatches come after other candidates.
9739 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009740 L->FailureKind == ovl_fail_too_few_arguments) {
9741 if (R->FailureKind == ovl_fail_too_many_arguments ||
9742 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009743 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9744 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9745 if (LDist == RDist) {
9746 if (L->FailureKind == R->FailureKind)
9747 // Sort non-surrogates before surrogates.
9748 return !L->IsSurrogate && R->IsSurrogate;
9749 // Sort candidates requiring fewer parameters than there were
9750 // arguments given after candidates requiring more parameters
9751 // than there were arguments given.
9752 return L->FailureKind == ovl_fail_too_many_arguments;
9753 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009754 return LDist < RDist;
9755 }
John McCall3712d9e2010-01-15 23:32:50 +00009756 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009757 }
John McCall3712d9e2010-01-15 23:32:50 +00009758 if (R->FailureKind == ovl_fail_too_many_arguments ||
9759 R->FailureKind == ovl_fail_too_few_arguments)
9760 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009761
John McCallfe796dd2010-01-23 05:17:32 +00009762 // 2. Bad conversions come first and are ordered by the number
9763 // of bad conversions and quality of good conversions.
9764 if (L->FailureKind == ovl_fail_bad_conversion) {
9765 if (R->FailureKind != ovl_fail_bad_conversion)
9766 return true;
9767
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009768 // The conversion that can be fixed with a smaller number of changes,
9769 // comes first.
9770 unsigned numLFixes = L->Fix.NumConversionsFixed;
9771 unsigned numRFixes = R->Fix.NumConversionsFixed;
9772 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9773 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009774 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009775 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009776 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009777
John McCallfe796dd2010-01-23 05:17:32 +00009778 // If there's any ordering between the defined conversions...
9779 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009780 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009781
9782 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009783 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009784 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009785 switch (CompareImplicitConversionSequences(S,
9786 L->Conversions[I],
9787 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009788 case ImplicitConversionSequence::Better:
9789 leftBetter++;
9790 break;
9791
9792 case ImplicitConversionSequence::Worse:
9793 leftBetter--;
9794 break;
9795
9796 case ImplicitConversionSequence::Indistinguishable:
9797 break;
9798 }
9799 }
9800 if (leftBetter > 0) return true;
9801 if (leftBetter < 0) return false;
9802
9803 } else if (R->FailureKind == ovl_fail_bad_conversion)
9804 return false;
9805
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009806 if (L->FailureKind == ovl_fail_bad_deduction) {
9807 if (R->FailureKind != ovl_fail_bad_deduction)
9808 return true;
9809
9810 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9811 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009812 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009813 } else if (R->FailureKind == ovl_fail_bad_deduction)
9814 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009815
John McCall3712d9e2010-01-15 23:32:50 +00009816 // TODO: others?
9817 }
9818
9819 // Sort everything else by location.
9820 SourceLocation LLoc = GetLocationForCandidate(L);
9821 SourceLocation RLoc = GetLocationForCandidate(R);
9822
9823 // Put candidates without locations (e.g. builtins) at the end.
9824 if (LLoc.isInvalid()) return false;
9825 if (RLoc.isInvalid()) return true;
9826
9827 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009828 }
9829};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009830}
John McCall12f97bc2010-01-08 04:41:39 +00009831
John McCallfe796dd2010-01-23 05:17:32 +00009832/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009833/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009834static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9835 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009836 assert(!Cand->Viable);
9837
9838 // Don't do anything on failures other than bad conversion.
9839 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9840
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009841 // We only want the FixIts if all the arguments can be corrected.
9842 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009843 // Use a implicit copy initialization to check conversion fixes.
9844 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009845
John McCallfe796dd2010-01-23 05:17:32 +00009846 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009847 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009848 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009849 while (true) {
9850 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9851 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009852 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009853 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009854 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009855 }
John McCallfe796dd2010-01-23 05:17:32 +00009856 }
9857
9858 if (ConvIdx == ConvCount)
9859 return;
9860
John McCall65eb8792010-02-25 01:37:24 +00009861 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9862 "remaining conversion is initialized?");
9863
Douglas Gregoradc7a702010-04-16 17:45:54 +00009864 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009865 // operation somehow.
9866 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009867
9868 const FunctionProtoType* Proto;
9869 unsigned ArgIdx = ConvIdx;
9870
9871 if (Cand->IsSurrogate) {
9872 QualType ConvType
9873 = Cand->Surrogate->getConversionType().getNonReferenceType();
9874 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9875 ConvType = ConvPtrType->getPointeeType();
9876 Proto = ConvType->getAs<FunctionProtoType>();
9877 ArgIdx--;
9878 } else if (Cand->Function) {
9879 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9880 if (isa<CXXMethodDecl>(Cand->Function) &&
9881 !isa<CXXConstructorDecl>(Cand->Function))
9882 ArgIdx--;
9883 } else {
9884 // Builtin binary operator with a bad first conversion.
9885 assert(ConvCount <= 3);
9886 for (; ConvIdx != ConvCount; ++ConvIdx)
9887 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009888 = TryCopyInitialization(S, Args[ConvIdx],
9889 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009890 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009891 /*InOverloadResolution*/ true,
9892 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009893 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009894 return;
9895 }
9896
9897 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009898 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009899 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009900 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009901 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9902 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9903 /*InOverloadResolution=*/true,
9904 /*AllowObjCWritebackConversion=*/
9905 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009906 // Store the FixIt in the candidate if it exists.
9907 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009908 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009909 }
John McCallfe796dd2010-01-23 05:17:32 +00009910 else
9911 Cand->Conversions[ConvIdx].setEllipsis();
9912 }
9913}
9914
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009915/// PrintOverloadCandidates - When overload resolution fails, prints
9916/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009917/// set.
John McCall5c32be02010-08-24 20:38:10 +00009918void OverloadCandidateSet::NoteCandidates(Sema &S,
9919 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009920 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009921 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009922 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009923 // Sort the candidates by viability and position. Sorting directly would
9924 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009925 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009926 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9927 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009928 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009929 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009930 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009931 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009932 if (Cand->Function || Cand->IsSurrogate)
9933 Cands.push_back(Cand);
9934 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9935 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009936 }
9937 }
9938
John McCallad2587a2010-01-12 00:48:53 +00009939 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009940 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009941
John McCall0d1da222010-01-12 00:44:57 +00009942 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009943
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009944 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009945 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009946 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009947 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9948 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009949
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009950 // Set an arbitrary limit on the number of candidate functions we'll spam
9951 // the user with. FIXME: This limit should depend on details of the
9952 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009953 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009954 break;
9955 }
9956 ++CandsShown;
9957
John McCalld3224162010-01-08 00:58:21 +00009958 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009959 NoteFunctionCandidate(S, Cand, Args.size(),
9960 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +00009961 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009962 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009963 else {
9964 assert(Cand->Viable &&
9965 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009966 // Generally we only see ambiguities including viable builtin
9967 // operators if overload resolution got screwed up by an
9968 // ambiguous user-defined conversion.
9969 //
9970 // FIXME: It's quite possible for different conversions to see
9971 // different ambiguities, though.
9972 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009973 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009974 ReportedAmbiguousConversions = true;
9975 }
John McCalld3224162010-01-08 00:58:21 +00009976
John McCall0d1da222010-01-12 00:44:57 +00009977 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009978 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009979 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009980 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009981
9982 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009983 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009984}
9985
Larisse Voufo98b20f12013-07-19 23:00:19 +00009986static SourceLocation
9987GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9988 return Cand->Specialization ? Cand->Specialization->getLocation()
9989 : SourceLocation();
9990}
9991
Richard Smith17c00b42014-11-12 01:24:00 +00009992namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009993struct CompareTemplateSpecCandidatesForDisplay {
9994 Sema &S;
9995 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9996
9997 bool operator()(const TemplateSpecCandidate *L,
9998 const TemplateSpecCandidate *R) {
9999 // Fast-path this check.
10000 if (L == R)
10001 return false;
10002
10003 // Assuming that both candidates are not matches...
10004
10005 // Sort by the ranking of deduction failures.
10006 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10007 return RankDeductionFailure(L->DeductionFailure) <
10008 RankDeductionFailure(R->DeductionFailure);
10009
10010 // Sort everything else by location.
10011 SourceLocation LLoc = GetLocationForCandidate(L);
10012 SourceLocation RLoc = GetLocationForCandidate(R);
10013
10014 // Put candidates without locations (e.g. builtins) at the end.
10015 if (LLoc.isInvalid())
10016 return false;
10017 if (RLoc.isInvalid())
10018 return true;
10019
10020 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10021 }
10022};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010023}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010024
10025/// Diagnose a template argument deduction failure.
10026/// We are treating these failures as overload failures due to bad
10027/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010028void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10029 bool ForTakingAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010030 DiagnoseBadDeduction(S, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010031 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010032}
10033
10034void TemplateSpecCandidateSet::destroyCandidates() {
10035 for (iterator i = begin(), e = end(); i != e; ++i) {
10036 i->DeductionFailure.Destroy();
10037 }
10038}
10039
10040void TemplateSpecCandidateSet::clear() {
10041 destroyCandidates();
10042 Candidates.clear();
10043}
10044
10045/// NoteCandidates - When no template specialization match is found, prints
10046/// diagnostic messages containing the non-matching specializations that form
10047/// the candidate set.
10048/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10049/// OCD == OCD_AllCandidates and Cand->Viable == false.
10050void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10051 // Sort the candidates by position (assuming no candidate is a match).
10052 // Sorting directly would be prohibitive, so we make a set of pointers
10053 // and sort those.
10054 SmallVector<TemplateSpecCandidate *, 32> Cands;
10055 Cands.reserve(size());
10056 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10057 if (Cand->Specialization)
10058 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010059 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010060 // in general, want to list every possible builtin candidate.
10061 }
10062
10063 std::sort(Cands.begin(), Cands.end(),
10064 CompareTemplateSpecCandidatesForDisplay(S));
10065
10066 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10067 // for generalization purposes (?).
10068 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10069
10070 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10071 unsigned CandsShown = 0;
10072 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10073 TemplateSpecCandidate *Cand = *I;
10074
10075 // Set an arbitrary limit on the number of candidates we'll spam
10076 // the user with. FIXME: This limit should depend on details of the
10077 // candidate list.
10078 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10079 break;
10080 ++CandsShown;
10081
10082 assert(Cand->Specialization &&
10083 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010084 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010085 }
10086
10087 if (I != E)
10088 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10089}
10090
Douglas Gregorb491ed32011-02-19 21:32:49 +000010091// [PossiblyAFunctionType] --> [Return]
10092// NonFunctionType --> NonFunctionType
10093// R (A) --> R(A)
10094// R (*)(A) --> R (A)
10095// R (&)(A) --> R (A)
10096// R (S::*)(A) --> R (A)
10097QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10098 QualType Ret = PossiblyAFunctionType;
10099 if (const PointerType *ToTypePtr =
10100 PossiblyAFunctionType->getAs<PointerType>())
10101 Ret = ToTypePtr->getPointeeType();
10102 else if (const ReferenceType *ToTypeRef =
10103 PossiblyAFunctionType->getAs<ReferenceType>())
10104 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010105 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010106 PossiblyAFunctionType->getAs<MemberPointerType>())
10107 Ret = MemTypePtr->getPointeeType();
10108 Ret =
10109 Context.getCanonicalType(Ret).getUnqualifiedType();
10110 return Ret;
10111}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010112
Richard Smith17c00b42014-11-12 01:24:00 +000010113namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010114// A helper class to help with address of function resolution
10115// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010116class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010117 Sema& S;
10118 Expr* SourceExpr;
10119 const QualType& TargetType;
10120 QualType TargetFunctionType; // Extracted function type from target type
10121
10122 bool Complain;
10123 //DeclAccessPair& ResultFunctionAccessPair;
10124 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010125
Douglas Gregorb491ed32011-02-19 21:32:49 +000010126 bool TargetTypeIsNonStaticMemberFunction;
10127 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010128 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010129 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010130
Douglas Gregorb491ed32011-02-19 21:32:49 +000010131 OverloadExpr::FindResult OvlExprInfo;
10132 OverloadExpr *OvlExpr;
10133 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010134 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010135 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010136
Douglas Gregorb491ed32011-02-19 21:32:49 +000010137public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010138 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10139 const QualType &TargetType, bool Complain)
10140 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10141 Complain(Complain), Context(S.getASTContext()),
10142 TargetTypeIsNonStaticMemberFunction(
10143 !!TargetType->getAs<MemberPointerType>()),
10144 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010145 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010146 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010147 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10148 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010149 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010150 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010151
David Majnemera4f7c7a2013-08-01 06:13:59 +000010152 if (TargetFunctionType->isFunctionType()) {
10153 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10154 if (!UME->isImplicitAccess() &&
10155 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10156 StaticMemberFunctionFromBoundPointer = true;
10157 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10158 DeclAccessPair dap;
10159 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10160 OvlExpr, false, &dap)) {
10161 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10162 if (!Method->isStatic()) {
10163 // If the target type is a non-function type and the function found
10164 // is a non-static member function, pretend as if that was the
10165 // target, it's the only possible type to end up with.
10166 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010167
David Majnemera4f7c7a2013-08-01 06:13:59 +000010168 // And skip adding the function if its not in the proper form.
10169 // We'll diagnose this due to an empty set of functions.
10170 if (!OvlExprInfo.HasFormOfMemberPointer)
10171 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010172 }
10173
David Majnemera4f7c7a2013-08-01 06:13:59 +000010174 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010175 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010176 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010177 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010178
10179 if (OvlExpr->hasExplicitTemplateArgs())
10180 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010181
Douglas Gregorb491ed32011-02-19 21:32:49 +000010182 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10183 // C++ [over.over]p4:
10184 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010185 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010186 if (FoundNonTemplateFunction)
10187 EliminateAllTemplateMatches();
10188 else
10189 EliminateAllExceptMostSpecializedTemplate();
10190 }
10191 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010192
10193 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10194 Matches.size() > 1)
10195 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010196 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010197
10198 bool hasComplained() const { return HasComplained; }
10199
Douglas Gregorb491ed32011-02-19 21:32:49 +000010200private:
George Burgess IV2a6150d2015-10-16 01:17:38 +000010201 // Is A considered a better overload candidate for the desired type than B?
10202 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10203 return hasBetterEnableIfAttrs(S, A, B);
10204 }
10205
10206 // Returns true if we've eliminated any (read: all but one) candidates, false
10207 // otherwise.
10208 bool eliminiateSuboptimalOverloadCandidates() {
10209 // Same algorithm as overload resolution -- one pass to pick the "best",
10210 // another pass to be sure that nothing is better than the best.
10211 auto Best = Matches.begin();
10212 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10213 if (isBetterCandidate(I->second, Best->second))
10214 Best = I;
10215
10216 const FunctionDecl *BestFn = Best->second;
10217 auto IsBestOrInferiorToBest = [this, BestFn](
10218 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10219 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10220 };
10221
10222 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10223 // option, so we can potentially give the user a better error
10224 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10225 return false;
10226 Matches[0] = *Best;
10227 Matches.resize(1);
10228 return true;
10229 }
10230
Douglas Gregorb491ed32011-02-19 21:32:49 +000010231 bool isTargetTypeAFunction() const {
10232 return TargetFunctionType->isFunctionType();
10233 }
10234
10235 // [ToType] [Return]
10236
10237 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10238 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10239 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10240 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10241 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10242 }
10243
10244 // return true if any matching specializations were found
10245 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10246 const DeclAccessPair& CurAccessFunPair) {
10247 if (CXXMethodDecl *Method
10248 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10249 // Skip non-static function templates when converting to pointer, and
10250 // static when converting to member pointer.
10251 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10252 return false;
10253 }
10254 else if (TargetTypeIsNonStaticMemberFunction)
10255 return false;
10256
10257 // C++ [over.over]p2:
10258 // If the name is a function template, template argument deduction is
10259 // done (14.8.2.2), and if the argument deduction succeeds, the
10260 // resulting template argument list is used to generate a single
10261 // function template specialization, which is added to the set of
10262 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010263 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010264 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010265 if (Sema::TemplateDeductionResult Result
10266 = S.DeduceTemplateArguments(FunctionTemplate,
10267 &OvlExplicitTemplateArgs,
10268 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010269 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010270 // Make a note of the failed deduction for diagnostics.
10271 FailedCandidates.addCandidate()
10272 .set(FunctionTemplate->getTemplatedDecl(),
10273 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010274 return false;
10275 }
10276
Douglas Gregor19a41f12013-04-17 08:45:07 +000010277 // Template argument deduction ensures that we have an exact match or
10278 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010279 // This function template specicalization works.
10280 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +000010281 assert(S.isSameOrCompatibleFunctionType(
10282 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010283 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010284
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010285 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010286 return false;
10287
Douglas Gregorb491ed32011-02-19 21:32:49 +000010288 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10289 return true;
10290 }
10291
10292 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10293 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010295 // Skip non-static functions when converting to pointer, and static
10296 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010297 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10298 return false;
10299 }
10300 else if (TargetTypeIsNonStaticMemberFunction)
10301 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010302
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010303 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010304 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010305 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010306 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010307 return false;
10308
Richard Smith2a7d4812013-05-04 07:00:32 +000010309 // If any candidate has a placeholder return type, trigger its deduction
10310 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010311 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010312 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010313 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10314 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010315 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010316 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010317
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010318 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010319 return false;
10320
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010321 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010322 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10323 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010324 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
George Burgess IV5f21c712015-10-12 19:57:04 +000010325 ResultTy) ||
10326 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10327 Matches.push_back(std::make_pair(
10328 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010329 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010330 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010331 }
Mike Stump11289f42009-09-09 15:08:12 +000010332 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010333
10334 return false;
10335 }
10336
10337 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10338 bool Ret = false;
10339
10340 // If the overload expression doesn't have the form of a pointer to
10341 // member, don't try to convert it to a pointer-to-member type.
10342 if (IsInvalidFormOfPointerToMemberFunction())
10343 return false;
10344
10345 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10346 E = OvlExpr->decls_end();
10347 I != E; ++I) {
10348 // Look through any using declarations to find the underlying function.
10349 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10350
10351 // C++ [over.over]p3:
10352 // Non-member functions and static member functions match
10353 // targets of type "pointer-to-function" or "reference-to-function."
10354 // Nonstatic member functions match targets of
10355 // type "pointer-to-member-function."
10356 // Note that according to DR 247, the containing class does not matter.
10357 if (FunctionTemplateDecl *FunctionTemplate
10358 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10359 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10360 Ret = true;
10361 }
10362 // If we have explicit template arguments supplied, skip non-templates.
10363 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10364 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10365 Ret = true;
10366 }
10367 assert(Ret || Matches.empty());
10368 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010369 }
10370
Douglas Gregorb491ed32011-02-19 21:32:49 +000010371 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010372 // [...] and any given function template specialization F1 is
10373 // eliminated if the set contains a second function template
10374 // specialization whose function template is more specialized
10375 // than the function template of F1 according to the partial
10376 // ordering rules of 14.5.5.2.
10377
10378 // The algorithm specified above is quadratic. We instead use a
10379 // two-pass algorithm (similar to the one used to identify the
10380 // best viable function in an overload set) that identifies the
10381 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010382
10383 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10384 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10385 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010386
Larisse Voufo98b20f12013-07-19 23:00:19 +000010387 // TODO: It looks like FailedCandidates does not serve much purpose
10388 // here, since the no_viable diagnostic has index 0.
10389 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010390 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010391 SourceExpr->getLocStart(), S.PDiag(),
10392 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10393 .second->getDeclName(),
10394 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10395 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010396
Douglas Gregorb491ed32011-02-19 21:32:49 +000010397 if (Result != MatchesCopy.end()) {
10398 // Make it the first and only element
10399 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10400 Matches[0].second = cast<FunctionDecl>(*Result);
10401 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010402 } else
10403 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010405
Douglas Gregorb491ed32011-02-19 21:32:49 +000010406 void EliminateAllTemplateMatches() {
10407 // [...] any function template specializations in the set are
10408 // eliminated if the set also contains a non-template function, [...]
10409 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010410 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010411 ++I;
10412 else {
10413 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010414 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010415 }
10416 }
10417 }
10418
Artem Belevich94a55e82015-09-22 17:22:59 +000010419 void EliminateSuboptimalCudaMatches() {
10420 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10421 }
10422
Douglas Gregorb491ed32011-02-19 21:32:49 +000010423public:
10424 void ComplainNoMatchesFound() const {
10425 assert(Matches.empty());
10426 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10427 << OvlExpr->getName() << TargetFunctionType
10428 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010429 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010430 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10431 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010432 else {
10433 // We have some deduction failure messages. Use them to diagnose
10434 // the function templates, and diagnose the non-template candidates
10435 // normally.
10436 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10437 IEnd = OvlExpr->decls_end();
10438 I != IEnd; ++I)
10439 if (FunctionDecl *Fun =
10440 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010441 if (!functionHasPassObjectSizeParams(Fun))
10442 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10443 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010444 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10445 }
10446 }
10447
Douglas Gregorb491ed32011-02-19 21:32:49 +000010448 bool IsInvalidFormOfPointerToMemberFunction() const {
10449 return TargetTypeIsNonStaticMemberFunction &&
10450 !OvlExprInfo.HasFormOfMemberPointer;
10451 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010452
Douglas Gregorb491ed32011-02-19 21:32:49 +000010453 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10454 // TODO: Should we condition this on whether any functions might
10455 // have matched, or is it more appropriate to do that in callers?
10456 // TODO: a fixit wouldn't hurt.
10457 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10458 << TargetType << OvlExpr->getSourceRange();
10459 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010460
10461 bool IsStaticMemberFunctionFromBoundPointer() const {
10462 return StaticMemberFunctionFromBoundPointer;
10463 }
10464
10465 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10466 S.Diag(OvlExpr->getLocStart(),
10467 diag::err_invalid_form_pointer_member_function)
10468 << OvlExpr->getSourceRange();
10469 }
10470
Douglas Gregorb491ed32011-02-19 21:32:49 +000010471 void ComplainOfInvalidConversion() const {
10472 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10473 << OvlExpr->getName() << TargetType;
10474 }
10475
10476 void ComplainMultipleMatchesFound() const {
10477 assert(Matches.size() > 1);
10478 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10479 << OvlExpr->getName()
10480 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010481 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10482 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010483 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010484
10485 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10486
Douglas Gregorb491ed32011-02-19 21:32:49 +000010487 int getNumMatches() const { return Matches.size(); }
10488
10489 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010490 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010491 return Matches[0].second;
10492 }
10493
10494 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010495 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010496 return &Matches[0].first;
10497 }
10498};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010499}
Richard Smith17c00b42014-11-12 01:24:00 +000010500
Douglas Gregorb491ed32011-02-19 21:32:49 +000010501/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10502/// an overloaded function (C++ [over.over]), where @p From is an
10503/// expression with overloaded function type and @p ToType is the type
10504/// we're trying to resolve to. For example:
10505///
10506/// @code
10507/// int f(double);
10508/// int f(int);
10509///
10510/// int (*pfd)(double) = f; // selects f(double)
10511/// @endcode
10512///
10513/// This routine returns the resulting FunctionDecl if it could be
10514/// resolved, and NULL otherwise. When @p Complain is true, this
10515/// routine will emit diagnostics if there is an error.
10516FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010517Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10518 QualType TargetType,
10519 bool Complain,
10520 DeclAccessPair &FoundResult,
10521 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010522 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010523
10524 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10525 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010526 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010527 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010528 bool ShouldComplain = Complain && !Resolver.hasComplained();
10529 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010530 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10531 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10532 else
10533 Resolver.ComplainNoMatchesFound();
10534 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010535 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010536 Resolver.ComplainMultipleMatchesFound();
10537 else if (NumMatches == 1) {
10538 Fn = Resolver.getMatchingFunctionDecl();
10539 assert(Fn);
10540 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010541 if (Complain) {
10542 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10543 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10544 else
10545 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10546 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010547 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010548
10549 if (pHadMultipleCandidates)
10550 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010551 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010552}
10553
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010554/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010555/// resolve that overloaded function expression down to a single function.
10556///
10557/// This routine can only resolve template-ids that refer to a single function
10558/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010559/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010560/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010561///
10562/// If no template-ids are found, no diagnostics are emitted and NULL is
10563/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010564FunctionDecl *
10565Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10566 bool Complain,
10567 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010568 // C++ [over.over]p1:
10569 // [...] [Note: any redundant set of parentheses surrounding the
10570 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010571 // C++ [over.over]p1:
10572 // [...] The overloaded function name can be preceded by the &
10573 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010574
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010575 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010576 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010577 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010578
10579 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010580 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010581 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010582
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010583 // Look through all of the overloaded functions, searching for one
10584 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010585 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010586 for (UnresolvedSetIterator I = ovl->decls_begin(),
10587 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010588 // C++0x [temp.arg.explicit]p3:
10589 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010590 // where deduction is not done, if a template argument list is
10591 // specified and it, along with any default template arguments,
10592 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010593 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010594 FunctionTemplateDecl *FunctionTemplate
10595 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010596
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010597 // C++ [over.over]p2:
10598 // If the name is a function template, template argument deduction is
10599 // done (14.8.2.2), and if the argument deduction succeeds, the
10600 // resulting template argument list is used to generate a single
10601 // function template specialization, which is added to the set of
10602 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010603 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010604 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010605 if (TemplateDeductionResult Result
10606 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010607 Specialization, Info,
10608 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010609 // Make a note of the failed deduction for diagnostics.
10610 // TODO: Actually use the failed-deduction info?
10611 FailedCandidates.addCandidate()
10612 .set(FunctionTemplate->getTemplatedDecl(),
10613 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010614 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010615 }
10616
John McCall0009fcc2011-04-26 20:42:42 +000010617 assert(Specialization && "no specialization and no error?");
10618
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010619 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010620 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010621 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010622 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10623 << ovl->getName();
10624 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010625 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010626 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010627 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010628
John McCall0009fcc2011-04-26 20:42:42 +000010629 Matched = Specialization;
10630 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010632
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010633 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010634 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010635 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010636 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010637
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010638 return Matched;
10639}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010640
Douglas Gregor1beec452011-03-12 01:48:56 +000010641
10642
10643
John McCall50a2c2c2011-10-11 23:14:30 +000010644// Resolve and fix an overloaded expression that can be resolved
10645// because it identifies a single function template specialization.
10646//
Douglas Gregor1beec452011-03-12 01:48:56 +000010647// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010648//
10649// Return true if it was logically possible to so resolve the
10650// expression, regardless of whether or not it succeeded. Always
10651// returns true if 'complain' is set.
10652bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10653 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010654 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010655 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010656 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010657 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010658
John McCall50a2c2c2011-10-11 23:14:30 +000010659 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010660
John McCall0009fcc2011-04-26 20:42:42 +000010661 DeclAccessPair found;
10662 ExprResult SingleFunctionExpression;
10663 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10664 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010665 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010666 SrcExpr = ExprError();
10667 return true;
10668 }
John McCall0009fcc2011-04-26 20:42:42 +000010669
10670 // It is only correct to resolve to an instance method if we're
10671 // resolving a form that's permitted to be a pointer to member.
10672 // Otherwise we'll end up making a bound member expression, which
10673 // is illegal in all the contexts we resolve like this.
10674 if (!ovl.HasFormOfMemberPointer &&
10675 isa<CXXMethodDecl>(fn) &&
10676 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010677 if (!complain) return false;
10678
10679 Diag(ovl.Expression->getExprLoc(),
10680 diag::err_bound_member_function)
10681 << 0 << ovl.Expression->getSourceRange();
10682
10683 // TODO: I believe we only end up here if there's a mix of
10684 // static and non-static candidates (otherwise the expression
10685 // would have 'bound member' type, not 'overload' type).
10686 // Ideally we would note which candidate was chosen and why
10687 // the static candidates were rejected.
10688 SrcExpr = ExprError();
10689 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010690 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010691
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010692 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010693 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010694 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010695
10696 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010697 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010698 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010699 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010700 if (SingleFunctionExpression.isInvalid()) {
10701 SrcExpr = ExprError();
10702 return true;
10703 }
10704 }
John McCall0009fcc2011-04-26 20:42:42 +000010705 }
10706
10707 if (!SingleFunctionExpression.isUsable()) {
10708 if (complain) {
10709 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10710 << ovl.Expression->getName()
10711 << DestTypeForComplaining
10712 << OpRangeForComplaining
10713 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010714 NoteAllOverloadCandidates(SrcExpr.get());
10715
10716 SrcExpr = ExprError();
10717 return true;
10718 }
10719
10720 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010721 }
10722
John McCall50a2c2c2011-10-11 23:14:30 +000010723 SrcExpr = SingleFunctionExpression;
10724 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010725}
10726
Douglas Gregorcabea402009-09-22 15:41:20 +000010727/// \brief Add a single candidate to the overload set.
10728static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010729 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010730 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010731 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010732 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010733 bool PartialOverloading,
10734 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010735 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010736 if (isa<UsingShadowDecl>(Callee))
10737 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10738
Douglas Gregorcabea402009-09-22 15:41:20 +000010739 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010740 if (ExplicitTemplateArgs) {
10741 assert(!KnownValid && "Explicit template arguments?");
10742 return;
10743 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010744 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10745 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010746 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010747 return;
John McCalld14a8642009-11-21 08:51:07 +000010748 }
10749
10750 if (FunctionTemplateDecl *FuncTemplate
10751 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010752 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010753 ExplicitTemplateArgs, Args, CandidateSet,
10754 /*SuppressUsedConversions=*/false,
10755 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010756 return;
10757 }
10758
Richard Smith95ce4f62011-06-26 22:19:54 +000010759 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010760}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010761
Douglas Gregorcabea402009-09-22 15:41:20 +000010762/// \brief Add the overload candidates named by callee and/or found by argument
10763/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010764void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010765 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010766 OverloadCandidateSet &CandidateSet,
10767 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010768
10769#ifndef NDEBUG
10770 // Verify that ArgumentDependentLookup is consistent with the rules
10771 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010772 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010773 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10774 // and let Y be the lookup set produced by argument dependent
10775 // lookup (defined as follows). If X contains
10776 //
10777 // -- a declaration of a class member, or
10778 //
10779 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010780 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010781 //
10782 // -- a declaration that is neither a function or a function
10783 // template
10784 //
10785 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010786
John McCall57500772009-12-16 12:17:52 +000010787 if (ULE->requiresADL()) {
10788 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10789 E = ULE->decls_end(); I != E; ++I) {
10790 assert(!(*I)->getDeclContext()->isRecord());
10791 assert(isa<UsingShadowDecl>(*I) ||
10792 !(*I)->getDeclContext()->isFunctionOrMethod());
10793 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010794 }
10795 }
10796#endif
10797
John McCall57500772009-12-16 12:17:52 +000010798 // It would be nice to avoid this copy.
10799 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010800 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010801 if (ULE->hasExplicitTemplateArgs()) {
10802 ULE->copyTemplateArgumentsInto(TABuffer);
10803 ExplicitTemplateArgs = &TABuffer;
10804 }
10805
10806 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10807 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010808 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10809 CandidateSet, PartialOverloading,
10810 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010811
John McCall57500772009-12-16 12:17:52 +000010812 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010813 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010814 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010815 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010816}
John McCalld681c392009-12-16 08:11:27 +000010817
Richard Smith0603bbb2013-06-12 22:56:54 +000010818/// Determine whether a declaration with the specified name could be moved into
10819/// a different namespace.
10820static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10821 switch (Name.getCXXOverloadedOperator()) {
10822 case OO_New: case OO_Array_New:
10823 case OO_Delete: case OO_Array_Delete:
10824 return false;
10825
10826 default:
10827 return true;
10828 }
10829}
10830
Richard Smith998a5912011-06-05 22:42:48 +000010831/// Attempt to recover from an ill-formed use of a non-dependent name in a
10832/// template, where the non-dependent name was declared after the template
10833/// was defined. This is common in code written for a compilers which do not
10834/// correctly implement two-stage name lookup.
10835///
10836/// Returns true if a viable candidate was found and a diagnostic was issued.
10837static bool
10838DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10839 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010840 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010841 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010842 ArrayRef<Expr *> Args,
10843 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010844 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10845 return false;
10846
10847 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010848 if (DC->isTransparentContext())
10849 continue;
10850
Richard Smith998a5912011-06-05 22:42:48 +000010851 SemaRef.LookupQualifiedName(R, DC);
10852
10853 if (!R.empty()) {
10854 R.suppressDiagnostics();
10855
10856 if (isa<CXXRecordDecl>(DC)) {
10857 // Don't diagnose names we find in classes; we get much better
10858 // diagnostics for these from DiagnoseEmptyLookup.
10859 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010860 if (DoDiagnoseEmptyLookup)
10861 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010862 return false;
10863 }
10864
Richard Smith100b24a2014-04-17 01:52:14 +000010865 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010866 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10867 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010868 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010869 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010870
10871 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010872 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010873 // No viable functions. Don't bother the user with notes for functions
10874 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010875 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010876 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010877 }
Richard Smith998a5912011-06-05 22:42:48 +000010878
10879 // Find the namespaces where ADL would have looked, and suggest
10880 // declaring the function there instead.
10881 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10882 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010883 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010884 AssociatedNamespaces,
10885 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010886 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010887 if (canBeDeclaredInNamespace(R.getLookupName())) {
10888 DeclContext *Std = SemaRef.getStdNamespace();
10889 for (Sema::AssociatedNamespaceSet::iterator
10890 it = AssociatedNamespaces.begin(),
10891 end = AssociatedNamespaces.end(); it != end; ++it) {
10892 // Never suggest declaring a function within namespace 'std'.
10893 if (Std && Std->Encloses(*it))
10894 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010895
Richard Smith0603bbb2013-06-12 22:56:54 +000010896 // Never suggest declaring a function within a namespace with a
10897 // reserved name, like __gnu_cxx.
10898 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10899 if (NS &&
10900 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10901 continue;
10902
10903 SuggestedNamespaces.insert(*it);
10904 }
Richard Smith998a5912011-06-05 22:42:48 +000010905 }
10906
10907 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10908 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010909 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010910 SemaRef.Diag(Best->Function->getLocation(),
10911 diag::note_not_found_by_two_phase_lookup)
10912 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010913 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010914 SemaRef.Diag(Best->Function->getLocation(),
10915 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010916 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010917 } else {
10918 // FIXME: It would be useful to list the associated namespaces here,
10919 // but the diagnostics infrastructure doesn't provide a way to produce
10920 // a localized representation of a list of items.
10921 SemaRef.Diag(Best->Function->getLocation(),
10922 diag::note_not_found_by_two_phase_lookup)
10923 << R.getLookupName() << 2;
10924 }
10925
10926 // Try to recover by calling this function.
10927 return true;
10928 }
10929
10930 R.clear();
10931 }
10932
10933 return false;
10934}
10935
10936/// Attempt to recover from ill-formed use of a non-dependent operator in a
10937/// template, where the non-dependent operator was declared after the template
10938/// was defined.
10939///
10940/// Returns true if a viable candidate was found and a diagnostic was issued.
10941static bool
10942DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10943 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010944 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010945 DeclarationName OpName =
10946 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10947 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10948 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010949 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010950 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010951}
10952
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010953namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010954class BuildRecoveryCallExprRAII {
10955 Sema &SemaRef;
10956public:
10957 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10958 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10959 SemaRef.IsBuildingRecoveryCallExpr = true;
10960 }
10961
10962 ~BuildRecoveryCallExprRAII() {
10963 SemaRef.IsBuildingRecoveryCallExpr = false;
10964 }
10965};
10966
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010967}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010968
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010969static std::unique_ptr<CorrectionCandidateCallback>
10970MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10971 bool HasTemplateArgs, bool AllowTypoCorrection) {
10972 if (!AllowTypoCorrection)
10973 return llvm::make_unique<NoTypoCorrectionCCC>();
10974 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10975 HasTemplateArgs, ME);
10976}
10977
John McCalld681c392009-12-16 08:11:27 +000010978/// Attempts to recover from a call where no functions were found.
10979///
10980/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010981static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010982BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010983 UnresolvedLookupExpr *ULE,
10984 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010985 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010986 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010987 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010988 // Do not try to recover if it is already building a recovery call.
10989 // This stops infinite loops for template instantiations like
10990 //
10991 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10992 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10993 //
10994 if (SemaRef.IsBuildingRecoveryCallExpr)
10995 return ExprError();
10996 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010997
10998 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010999 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011000 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011001
John McCall57500772009-12-16 12:17:52 +000011002 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011003 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011004 if (ULE->hasExplicitTemplateArgs()) {
11005 ULE->copyTemplateArgumentsInto(TABuffer);
11006 ExplicitTemplateArgs = &TABuffer;
11007 }
11008
John McCalld681c392009-12-16 08:11:27 +000011009 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11010 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011011 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011012 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011013 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011014 ExplicitTemplateArgs, Args,
11015 &DoDiagnoseEmptyLookup) &&
11016 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11017 S, SS, R,
11018 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11019 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11020 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011021 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011022
John McCall57500772009-12-16 12:17:52 +000011023 assert(!R.empty() && "lookup results empty despite recovery");
11024
11025 // Build an implicit member call if appropriate. Just drop the
11026 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011027 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011028 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011029 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11030 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011031 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011032 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011033 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011034 else
11035 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11036
11037 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011038 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011039
11040 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011041 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011042 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011043 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011044 MultiExprArg(Args.data(), Args.size()),
11045 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011046}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011047
Sam Panzer0f384432012-08-21 00:52:01 +000011048/// \brief Constructs and populates an OverloadedCandidateSet from
11049/// the given function.
11050/// \returns true when an the ExprResult output parameter has been set.
11051bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11052 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011053 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011054 SourceLocation RParenLoc,
11055 OverloadCandidateSet *CandidateSet,
11056 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011057#ifndef NDEBUG
11058 if (ULE->requiresADL()) {
11059 // To do ADL, we must have found an unqualified name.
11060 assert(!ULE->getQualifier() && "qualified name with ADL");
11061
11062 // We don't perform ADL for implicit declarations of builtins.
11063 // Verify that this was correctly set up.
11064 FunctionDecl *F;
11065 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11066 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11067 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011068 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011069
John McCall57500772009-12-16 12:17:52 +000011070 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011071 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011072 }
John McCall57500772009-12-16 12:17:52 +000011073#endif
11074
John McCall4124c492011-10-17 18:40:02 +000011075 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011076 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011077 *Result = ExprError();
11078 return true;
11079 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011080
John McCall57500772009-12-16 12:17:52 +000011081 // Add the functions denoted by the callee to the set of candidate
11082 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011083 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011084
Hans Wennborgb2747382015-06-12 21:23:23 +000011085 if (getLangOpts().MSVCCompat &&
11086 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011087 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11088
11089 OverloadCandidateSet::iterator Best;
11090 if (CandidateSet->empty() ||
11091 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11092 OR_No_Viable_Function) {
11093 // In Microsoft mode, if we are inside a template class member function then
11094 // create a type dependent CallExpr. The goal is to postpone name lookup
11095 // to instantiation time to be able to search into type dependent base
11096 // classes.
11097 CallExpr *CE = new (Context) CallExpr(
11098 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011099 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011100 CE->setValueDependent(true);
11101 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011102 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011103 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011104 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011105 }
John McCalld681c392009-12-16 08:11:27 +000011106
Hans Wennborg64937c62015-06-11 21:21:57 +000011107 if (CandidateSet->empty())
11108 return false;
11109
John McCall4124c492011-10-17 18:40:02 +000011110 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011111 return false;
11112}
John McCall4124c492011-10-17 18:40:02 +000011113
Sam Panzer0f384432012-08-21 00:52:01 +000011114/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11115/// the completed call expression. If overload resolution fails, emits
11116/// diagnostics and returns ExprError()
11117static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11118 UnresolvedLookupExpr *ULE,
11119 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011120 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011121 SourceLocation RParenLoc,
11122 Expr *ExecConfig,
11123 OverloadCandidateSet *CandidateSet,
11124 OverloadCandidateSet::iterator *Best,
11125 OverloadingResult OverloadResult,
11126 bool AllowTypoCorrection) {
11127 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011128 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011129 RParenLoc, /*EmptyLookup=*/true,
11130 AllowTypoCorrection);
11131
11132 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011133 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011134 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011135 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011136 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11137 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011138 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011139 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11140 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011141 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011142
Richard Smith998a5912011-06-05 22:42:48 +000011143 case OR_No_Viable_Function: {
11144 // Try to recover by looking for viable functions which the user might
11145 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011146 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011147 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011148 /*EmptyLookup=*/false,
11149 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011150 if (!Recovery.isInvalid())
11151 return Recovery;
11152
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011153 // If the user passes in a function that we can't take the address of, we
11154 // generally end up emitting really bad error messages. Here, we attempt to
11155 // emit better ones.
11156 for (const Expr *Arg : Args) {
11157 if (!Arg->getType()->isFunctionType())
11158 continue;
11159 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11160 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11161 if (FD &&
11162 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11163 Arg->getExprLoc()))
11164 return ExprError();
11165 }
11166 }
11167
11168 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11169 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011170 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011171 break;
Richard Smith998a5912011-06-05 22:42:48 +000011172 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011173
11174 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011175 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011176 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011177 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011178 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011179
Sam Panzer0f384432012-08-21 00:52:01 +000011180 case OR_Deleted: {
11181 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11182 << (*Best)->Function->isDeleted()
11183 << ULE->getName()
11184 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11185 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011186 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011187
Sam Panzer0f384432012-08-21 00:52:01 +000011188 // We emitted an error for the unvailable/deleted function call but keep
11189 // the call in the AST.
11190 FunctionDecl *FDecl = (*Best)->Function;
11191 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011192 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11193 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011194 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011195 }
11196
Douglas Gregorb412e172010-07-25 18:17:45 +000011197 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011198 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011199}
11200
Sam Panzer0f384432012-08-21 00:52:01 +000011201/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11202/// (which eventually refers to the declaration Func) and the call
11203/// arguments Args/NumArgs, attempt to resolve the function call down
11204/// to a specific function. If overload resolution succeeds, returns
11205/// the call expression produced by overload resolution.
11206/// Otherwise, emits diagnostics and returns ExprError.
11207ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11208 UnresolvedLookupExpr *ULE,
11209 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011210 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011211 SourceLocation RParenLoc,
11212 Expr *ExecConfig,
11213 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000011214 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11215 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011216 ExprResult result;
11217
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011218 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11219 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011220 return result;
11221
11222 OverloadCandidateSet::iterator Best;
11223 OverloadingResult OverloadResult =
11224 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11225
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011226 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011227 RParenLoc, ExecConfig, &CandidateSet,
11228 &Best, OverloadResult,
11229 AllowTypoCorrection);
11230}
11231
John McCall4c4c1df2010-01-26 03:27:55 +000011232static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011233 return Functions.size() > 1 ||
11234 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11235}
11236
Douglas Gregor084d8552009-03-13 23:49:33 +000011237/// \brief Create a unary operation that may resolve to an overloaded
11238/// operator.
11239///
11240/// \param OpLoc The location of the operator itself (e.g., '*').
11241///
11242/// \param OpcIn The UnaryOperator::Opcode that describes this
11243/// operator.
11244///
James Dennett18348b62012-06-22 08:52:37 +000011245/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011246/// considered by overload resolution. The caller needs to build this
11247/// set based on the context using, e.g.,
11248/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11249/// set should not contain any member functions; those will be added
11250/// by CreateOverloadedUnaryOp().
11251///
James Dennett91738ff2012-06-22 10:32:46 +000011252/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011253ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000011254Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
11255 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011256 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011257 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000011258
11259 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11260 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11261 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011262 // TODO: provide better source location info.
11263 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011264
John McCall4124c492011-10-17 18:40:02 +000011265 if (checkPlaceholderForOverload(*this, Input))
11266 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011267
Craig Topperc3ec1492014-05-26 06:22:03 +000011268 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011269 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011270
Douglas Gregor084d8552009-03-13 23:49:33 +000011271 // For post-increment and post-decrement, add the implicit '0' as
11272 // the second argument, so that we know this is a post-increment or
11273 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011274 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011275 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011276 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11277 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011278 NumArgs = 2;
11279 }
11280
Richard Smithe54c3072013-05-05 15:51:06 +000011281 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11282
Douglas Gregor084d8552009-03-13 23:49:33 +000011283 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011284 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011285 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11286 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011287
Craig Topperc3ec1492014-05-26 06:22:03 +000011288 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011289 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011290 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011291 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011292 /*ADL*/ true, IsOverloaded(Fns),
11293 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011294 return new (Context)
11295 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11296 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011297 }
11298
11299 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011300 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011301
11302 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011303 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011304
11305 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011306 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011307
John McCall4c4c1df2010-01-26 03:27:55 +000011308 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011309 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011310 /*ExplicitTemplateArgs*/nullptr,
11311 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011312
Douglas Gregor084d8552009-03-13 23:49:33 +000011313 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011314 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011315
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011316 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11317
Douglas Gregor084d8552009-03-13 23:49:33 +000011318 // Perform overload resolution.
11319 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011320 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011321 case OR_Success: {
11322 // We found a built-in operator or an overloaded operator.
11323 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011324
Douglas Gregor084d8552009-03-13 23:49:33 +000011325 if (FnDecl) {
11326 // We matched an overloaded operator. Build a call to that
11327 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011328
Douglas Gregor084d8552009-03-13 23:49:33 +000011329 // Convert the arguments.
11330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011331 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011332
John Wiegley01296292011-04-08 18:41:53 +000011333 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011334 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011335 Best->FoundDecl, Method);
11336 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011337 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011338 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011339 } else {
11340 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011341 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011342 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011343 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011344 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011345 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011346 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011347 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011348 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011349 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011350 }
11351
Douglas Gregor084d8552009-03-13 23:49:33 +000011352 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011353 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011354 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011355 if (FnExpr.isInvalid())
11356 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011357
Richard Smithc1564702013-11-15 02:58:23 +000011358 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011359 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011360 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11361 ResultTy = ResultTy.getNonLValueExprType(Context);
11362
Eli Friedman030eee42009-11-18 03:58:17 +000011363 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011364 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011365 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011366 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011367
Alp Toker314cc812014-01-25 16:55:45 +000011368 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011369 return ExprError();
11370
John McCallb268a282010-08-23 23:25:46 +000011371 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011372 } else {
11373 // We matched a built-in operator. Convert the arguments, then
11374 // break out so that we will build the appropriate built-in
11375 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011376 ExprResult InputRes =
11377 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11378 Best->Conversions[0], AA_Passing);
11379 if (InputRes.isInvalid())
11380 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011381 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011382 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011383 }
John Wiegley01296292011-04-08 18:41:53 +000011384 }
11385
11386 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011387 // This is an erroneous use of an operator which can be overloaded by
11388 // a non-member function. Check for non-member operators which were
11389 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011390 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011391 // FIXME: Recover by calling the found function.
11392 return ExprError();
11393
John Wiegley01296292011-04-08 18:41:53 +000011394 // No viable function; fall through to handling this as a
11395 // built-in operator, which will produce an error message for us.
11396 break;
11397
11398 case OR_Ambiguous:
11399 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11400 << UnaryOperator::getOpcodeStr(Opc)
11401 << Input->getType()
11402 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011403 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011404 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11405 return ExprError();
11406
11407 case OR_Deleted:
11408 Diag(OpLoc, diag::err_ovl_deleted_oper)
11409 << Best->Function->isDeleted()
11410 << UnaryOperator::getOpcodeStr(Opc)
11411 << getDeletedOrUnavailableSuffix(Best->Function)
11412 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011414 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011415 return ExprError();
11416 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011417
11418 // Either we found no viable overloaded operator or we matched a
11419 // built-in operator. In either case, fall through to trying to
11420 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011421 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011422}
11423
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011424/// \brief Create a binary operation that may resolve to an overloaded
11425/// operator.
11426///
11427/// \param OpLoc The location of the operator itself (e.g., '+').
11428///
11429/// \param OpcIn The BinaryOperator::Opcode that describes this
11430/// operator.
11431///
James Dennett18348b62012-06-22 08:52:37 +000011432/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011433/// considered by overload resolution. The caller needs to build this
11434/// set based on the context using, e.g.,
11435/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11436/// set should not contain any member functions; those will be added
11437/// by CreateOverloadedBinOp().
11438///
11439/// \param LHS Left-hand argument.
11440/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011441ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011442Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011443 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011444 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011445 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011446 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011447 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011448
11449 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11450 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11451 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11452
11453 // If either side is type-dependent, create an appropriate dependent
11454 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011455 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011456 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011457 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011458 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011459 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011460 return new (Context) BinaryOperator(
11461 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11462 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011463
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011464 return new (Context) CompoundAssignOperator(
11465 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11466 Context.DependentTy, Context.DependentTy, OpLoc,
11467 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011468 }
John McCall4c4c1df2010-01-26 03:27:55 +000011469
11470 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011471 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011472 // TODO: provide better source location info in DNLoc component.
11473 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011474 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011475 = UnresolvedLookupExpr::Create(Context, NamingClass,
11476 NestedNameSpecifierLoc(), OpNameInfo,
11477 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011478 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011479 return new (Context)
11480 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11481 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011482 }
11483
John McCall4124c492011-10-17 18:40:02 +000011484 // Always do placeholder-like conversions on the RHS.
11485 if (checkPlaceholderForOverload(*this, Args[1]))
11486 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011487
John McCall526ab472011-10-25 17:37:35 +000011488 // Do placeholder-like conversion on the LHS; note that we should
11489 // not get here with a PseudoObject LHS.
11490 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011491 if (checkPlaceholderForOverload(*this, Args[0]))
11492 return ExprError();
11493
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011494 // If this is the assignment operator, we only perform overload resolution
11495 // if the left-hand side is a class or enumeration type. This is actually
11496 // a hack. The standard requires that we do overload resolution between the
11497 // various built-in candidates, but as DR507 points out, this can lead to
11498 // problems. So we do it this way, which pretty much follows what GCC does.
11499 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011500 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011501 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011502
John McCalle26a8722010-12-04 08:14:53 +000011503 // If this is the .* operator, which is not overloadable, just
11504 // create a built-in binary operator.
11505 if (Opc == BO_PtrMemD)
11506 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11507
Douglas Gregor084d8552009-03-13 23:49:33 +000011508 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011509 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011510
11511 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011512 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011513
11514 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011515 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011516
Richard Smith0daabd72014-09-23 20:31:39 +000011517 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11518 // performed for an assignment operator (nor for operator[] nor operator->,
11519 // which don't get here).
11520 if (Opc != BO_Assign)
11521 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11522 /*ExplicitTemplateArgs*/ nullptr,
11523 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011524
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011525 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011526 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011527
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011528 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11529
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011530 // Perform overload resolution.
11531 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011532 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011533 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011534 // We found a built-in operator or an overloaded operator.
11535 FunctionDecl *FnDecl = Best->Function;
11536
11537 if (FnDecl) {
11538 // We matched an overloaded operator. Build a call to that
11539 // operator.
11540
11541 // Convert the arguments.
11542 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011543 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011544 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011545
Chandler Carruth8e543b32010-12-12 08:17:55 +000011546 ExprResult Arg1 =
11547 PerformCopyInitialization(
11548 InitializedEntity::InitializeParameter(Context,
11549 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011550 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011551 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011552 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011553
John Wiegley01296292011-04-08 18:41:53 +000011554 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011555 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011556 Best->FoundDecl, Method);
11557 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011558 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011559 Args[0] = Arg0.getAs<Expr>();
11560 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011561 } else {
11562 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011563 ExprResult Arg0 = PerformCopyInitialization(
11564 InitializedEntity::InitializeParameter(Context,
11565 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011566 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011567 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011568 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011569
Chandler Carruth8e543b32010-12-12 08:17:55 +000011570 ExprResult Arg1 =
11571 PerformCopyInitialization(
11572 InitializedEntity::InitializeParameter(Context,
11573 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011574 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011575 if (Arg1.isInvalid())
11576 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011577 Args[0] = LHS = Arg0.getAs<Expr>();
11578 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011579 }
11580
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011581 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011582 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011583 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011584 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011585 if (FnExpr.isInvalid())
11586 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011587
Richard Smithc1564702013-11-15 02:58:23 +000011588 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011589 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011590 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11591 ResultTy = ResultTy.getNonLValueExprType(Context);
11592
John McCallb268a282010-08-23 23:25:46 +000011593 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011594 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011595 Args, ResultTy, VK, OpLoc,
11596 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011597
Alp Toker314cc812014-01-25 16:55:45 +000011598 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011599 FnDecl))
11600 return ExprError();
11601
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011602 ArrayRef<const Expr *> ArgsArray(Args, 2);
11603 // Cut off the implicit 'this'.
11604 if (isa<CXXMethodDecl>(FnDecl))
11605 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011606
11607 // Check for a self move.
11608 if (Op == OO_Equal)
11609 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11610
Douglas Gregorb4866e82015-06-19 18:13:19 +000011611 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011612 TheCall->getSourceRange(), VariadicDoesNotApply);
11613
John McCallb268a282010-08-23 23:25:46 +000011614 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011615 } else {
11616 // We matched a built-in operator. Convert the arguments, then
11617 // break out so that we will build the appropriate built-in
11618 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011619 ExprResult ArgsRes0 =
11620 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11621 Best->Conversions[0], AA_Passing);
11622 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011623 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011624 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011625
John Wiegley01296292011-04-08 18:41:53 +000011626 ExprResult ArgsRes1 =
11627 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11628 Best->Conversions[1], AA_Passing);
11629 if (ArgsRes1.isInvalid())
11630 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011631 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011632 break;
11633 }
11634 }
11635
Douglas Gregor66950a32009-09-30 21:46:01 +000011636 case OR_No_Viable_Function: {
11637 // C++ [over.match.oper]p9:
11638 // If the operator is the operator , [...] and there are no
11639 // viable functions, then the operator is assumed to be the
11640 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011641 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011642 break;
11643
Chandler Carruth8e543b32010-12-12 08:17:55 +000011644 // For class as left operand for assignment or compound assigment
11645 // operator do not fall through to handling in built-in, but report that
11646 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011647 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011648 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011649 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011650 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11651 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011652 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011653 if (Args[0]->getType()->isIncompleteType()) {
11654 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11655 << Args[0]->getType()
11656 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11657 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011658 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011659 // This is an erroneous use of an operator which can be overloaded by
11660 // a non-member function. Check for non-member operators which were
11661 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011662 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011663 // FIXME: Recover by calling the found function.
11664 return ExprError();
11665
Douglas Gregor66950a32009-09-30 21:46:01 +000011666 // No viable function; try to create a built-in operation, which will
11667 // produce an error. Then, show the non-viable candidates.
11668 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011670 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011671 "C++ binary operator overloading is missing candidates!");
11672 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011673 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011674 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011675 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011676 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011677
11678 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011679 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011680 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011681 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011682 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011683 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011684 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011685 return ExprError();
11686
11687 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011688 if (isImplicitlyDeleted(Best->Function)) {
11689 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11690 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011691 << Context.getRecordType(Method->getParent())
11692 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011693
Richard Smithde1a4872012-12-28 12:23:24 +000011694 // The user probably meant to call this special member. Just
11695 // explain why it's deleted.
11696 NoteDeletedFunction(Method);
11697 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011698 } else {
11699 Diag(OpLoc, diag::err_ovl_deleted_oper)
11700 << Best->Function->isDeleted()
11701 << BinaryOperator::getOpcodeStr(Opc)
11702 << getDeletedOrUnavailableSuffix(Best->Function)
11703 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11704 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011705 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011706 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011707 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011708 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011709
Douglas Gregor66950a32009-09-30 21:46:01 +000011710 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011711 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011712}
11713
John McCalldadc5752010-08-24 06:29:42 +000011714ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011715Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11716 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011717 Expr *Base, Expr *Idx) {
11718 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011719 DeclarationName OpName =
11720 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11721
11722 // If either side is type-dependent, create an appropriate dependent
11723 // expression.
11724 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11725
Craig Topperc3ec1492014-05-26 06:22:03 +000011726 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011727 // CHECKME: no 'operator' keyword?
11728 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11729 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011730 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011731 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011732 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011733 /*ADL*/ true, /*Overloaded*/ false,
11734 UnresolvedSetIterator(),
11735 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011736 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011737
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011738 return new (Context)
11739 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11740 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011741 }
11742
John McCall4124c492011-10-17 18:40:02 +000011743 // Handle placeholders on both operands.
11744 if (checkPlaceholderForOverload(*this, Args[0]))
11745 return ExprError();
11746 if (checkPlaceholderForOverload(*this, Args[1]))
11747 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011748
Sebastian Redladba46e2009-10-29 20:17:01 +000011749 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011750 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011751
11752 // Subscript can only be overloaded as a member function.
11753
11754 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011755 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011756
11757 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011758 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011759
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011760 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11761
Sebastian Redladba46e2009-10-29 20:17:01 +000011762 // Perform overload resolution.
11763 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011764 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011765 case OR_Success: {
11766 // We found a built-in operator or an overloaded operator.
11767 FunctionDecl *FnDecl = Best->Function;
11768
11769 if (FnDecl) {
11770 // We matched an overloaded operator. Build a call to that
11771 // operator.
11772
John McCalla0296f72010-03-19 07:35:19 +000011773 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011774
Sebastian Redladba46e2009-10-29 20:17:01 +000011775 // Convert the arguments.
11776 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011777 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011778 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011779 Best->FoundDecl, Method);
11780 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011781 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011782 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011783
Anders Carlssona68e51e2010-01-29 18:37:50 +000011784 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011785 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011786 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011787 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011788 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011789 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011790 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011791 if (InputInit.isInvalid())
11792 return ExprError();
11793
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011794 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011795
Sebastian Redladba46e2009-10-29 20:17:01 +000011796 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011797 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11798 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011799 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011800 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011801 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011802 OpLocInfo.getLoc(),
11803 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011804 if (FnExpr.isInvalid())
11805 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011806
Richard Smithc1564702013-11-15 02:58:23 +000011807 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011808 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011809 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11810 ResultTy = ResultTy.getNonLValueExprType(Context);
11811
John McCallb268a282010-08-23 23:25:46 +000011812 CXXOperatorCallExpr *TheCall =
11813 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011814 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011815 ResultTy, VK, RLoc,
11816 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011817
Alp Toker314cc812014-01-25 16:55:45 +000011818 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011819 return ExprError();
11820
John McCallb268a282010-08-23 23:25:46 +000011821 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011822 } else {
11823 // We matched a built-in operator. Convert the arguments, then
11824 // break out so that we will build the appropriate built-in
11825 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011826 ExprResult ArgsRes0 =
11827 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11828 Best->Conversions[0], AA_Passing);
11829 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011830 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011831 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011832
11833 ExprResult ArgsRes1 =
11834 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11835 Best->Conversions[1], AA_Passing);
11836 if (ArgsRes1.isInvalid())
11837 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011838 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011839
11840 break;
11841 }
11842 }
11843
11844 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011845 if (CandidateSet.empty())
11846 Diag(LLoc, diag::err_ovl_no_oper)
11847 << Args[0]->getType() << /*subscript*/ 0
11848 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11849 else
11850 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11851 << Args[0]->getType()
11852 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011853 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011854 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011855 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011856 }
11857
11858 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011859 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011860 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011861 << Args[0]->getType() << Args[1]->getType()
11862 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011863 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011864 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011865 return ExprError();
11866
11867 case OR_Deleted:
11868 Diag(LLoc, diag::err_ovl_deleted_oper)
11869 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011870 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011871 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011872 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011873 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011874 return ExprError();
11875 }
11876
11877 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011878 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011879}
11880
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011881/// BuildCallToMemberFunction - Build a call to a member
11882/// function. MemExpr is the expression that refers to the member
11883/// function (and includes the object parameter), Args/NumArgs are the
11884/// arguments to the function call (not including the object
11885/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011886/// expression refers to a non-static member function or an overloaded
11887/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011888ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011889Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011890 SourceLocation LParenLoc,
11891 MultiExprArg Args,
11892 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011893 assert(MemExprE->getType() == Context.BoundMemberTy ||
11894 MemExprE->getType() == Context.OverloadTy);
11895
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011896 // Dig out the member expression. This holds both the object
11897 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011898 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011899
John McCall0009fcc2011-04-26 20:42:42 +000011900 // Determine whether this is a call to a pointer-to-member function.
11901 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11902 assert(op->getType() == Context.BoundMemberTy);
11903 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11904
11905 QualType fnType =
11906 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11907
11908 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11909 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011910 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011911
11912 // Check that the object type isn't more qualified than the
11913 // member function we're calling.
11914 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11915
11916 QualType objectType = op->getLHS()->getType();
11917 if (op->getOpcode() == BO_PtrMemI)
11918 objectType = objectType->castAs<PointerType>()->getPointeeType();
11919 Qualifiers objectQuals = objectType.getQualifiers();
11920
11921 Qualifiers difference = objectQuals - funcQuals;
11922 difference.removeObjCGCAttr();
11923 difference.removeAddressSpace();
11924 if (difference) {
11925 std::string qualsString = difference.getAsString();
11926 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11927 << fnType.getUnqualifiedType()
11928 << qualsString
11929 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11930 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011931
John McCall0009fcc2011-04-26 20:42:42 +000011932 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011933 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011934 resultType, valueKind, RParenLoc);
11935
Alp Toker314cc812014-01-25 16:55:45 +000011936 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011937 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011938 return ExprError();
11939
Craig Topperc3ec1492014-05-26 06:22:03 +000011940 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011941 return ExprError();
11942
Richard Trieu9be9c682013-06-22 02:30:38 +000011943 if (CheckOtherCall(call, proto))
11944 return ExprError();
11945
John McCall0009fcc2011-04-26 20:42:42 +000011946 return MaybeBindToTemporary(call);
11947 }
11948
David Majnemerced8bdf2015-02-25 17:36:15 +000011949 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11950 return new (Context)
11951 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11952
John McCall4124c492011-10-17 18:40:02 +000011953 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011954 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011955 return ExprError();
11956
John McCall10eae182009-11-30 22:42:35 +000011957 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011958 CXXMethodDecl *Method = nullptr;
11959 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11960 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011961 if (isa<MemberExpr>(NakedMemExpr)) {
11962 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011963 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011964 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011965 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011966 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011967 } else {
11968 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011969 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011970
John McCall6e9f8f62009-12-03 04:06:58 +000011971 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011972 Expr::Classification ObjectClassification
11973 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11974 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011975
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011976 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011977 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11978 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011979
John McCall2d74de92009-12-01 22:10:20 +000011980 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011981 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011982 if (UnresExpr->hasExplicitTemplateArgs()) {
11983 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11984 TemplateArgs = &TemplateArgsBuffer;
11985 }
11986
John McCall10eae182009-11-30 22:42:35 +000011987 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11988 E = UnresExpr->decls_end(); I != E; ++I) {
11989
John McCall6e9f8f62009-12-03 04:06:58 +000011990 NamedDecl *Func = *I;
11991 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11992 if (isa<UsingShadowDecl>(Func))
11993 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11994
Douglas Gregor02824322011-01-26 19:30:28 +000011995
Francois Pichet64225792011-01-18 05:04:39 +000011996 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011997 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011998 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011999 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012000 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012001 // If explicit template arguments were provided, we can't call a
12002 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012003 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012004 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012005
John McCalla0296f72010-03-19 07:35:19 +000012006 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012007 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012008 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012009 } else {
John McCall10eae182009-11-30 22:42:35 +000012010 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012011 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012012 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012013 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012014 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012015 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012016 }
Mike Stump11289f42009-09-09 15:08:12 +000012017
John McCall10eae182009-11-30 22:42:35 +000012018 DeclarationName DeclName = UnresExpr->getMemberName();
12019
John McCall4124c492011-10-17 18:40:02 +000012020 UnbridgedCasts.restore();
12021
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012022 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012023 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012024 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012025 case OR_Success:
12026 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012027 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012028 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012029 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12030 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012031 // If FoundDecl is different from Method (such as if one is a template
12032 // and the other a specialization), make sure DiagnoseUseOfDecl is
12033 // called on both.
12034 // FIXME: This would be more comprehensively addressed by modifying
12035 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12036 // being used.
12037 if (Method != FoundDecl.getDecl() &&
12038 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12039 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012040 break;
12041
12042 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012043 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012044 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012045 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012046 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012047 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012048 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012049
12050 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012051 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012052 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012053 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012054 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012055 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012056
12057 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012058 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012059 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012060 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012061 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012062 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012063 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012064 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012065 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012066 }
12067
John McCall16df1e52010-03-30 21:47:33 +000012068 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012069
John McCall2d74de92009-12-01 22:10:20 +000012070 // If overload resolution picked a static member, build a
12071 // non-member call based on that function.
12072 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012073 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12074 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012075 }
12076
John McCall10eae182009-11-30 22:42:35 +000012077 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012078 }
12079
Alp Toker314cc812014-01-25 16:55:45 +000012080 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012081 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12082 ResultType = ResultType.getNonLValueExprType(Context);
12083
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012084 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012085 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012086 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012087 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012088
Eli Bendersky291a57e2014-09-25 23:59:08 +000012089 // (CUDA B.1): Check for invalid calls between targets.
12090 if (getLangOpts().CUDA) {
12091 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12092 if (CheckCUDATarget(Caller, Method)) {
12093 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12094 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12095 << IdentifyCUDATarget(Caller);
12096 return ExprError();
12097 }
12098 }
12099 }
12100
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012101 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012102 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012103 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012104 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012105
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012106 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012107 // We only need to do this if there was actually an overload; otherwise
12108 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012109 if (!Method->isStatic()) {
12110 ExprResult ObjectArg =
12111 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12112 FoundDecl, Method);
12113 if (ObjectArg.isInvalid())
12114 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012115 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012116 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012117
12118 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012119 const FunctionProtoType *Proto =
12120 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012121 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012122 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012123 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012124
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012125 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012126
Richard Smith55ce3522012-06-25 20:30:08 +000012127 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012128 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012129
George Burgess IVaea6ade2015-09-25 17:53:16 +000012130 // In the case the method to call was not selected by the overloading
12131 // resolution process, we still need to handle the enable_if attribute. Do
12132 // that here, so it will not hide previous -- and more relevant -- errors
12133 if (isa<MemberExpr>(NakedMemExpr)) {
12134 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12135 Diag(MemExprE->getLocStart(),
12136 diag::err_ovl_no_viable_member_function_in_call)
12137 << Method << Method->getSourceRange();
12138 Diag(Method->getLocation(),
12139 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12140 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12141 return ExprError();
12142 }
12143 }
12144
Anders Carlsson47061ee2011-05-06 14:25:31 +000012145 if ((isa<CXXConstructorDecl>(CurContext) ||
12146 isa<CXXDestructorDecl>(CurContext)) &&
12147 TheCall->getMethodDecl()->isPure()) {
12148 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12149
Davide Italianoccb37382015-07-14 23:36:10 +000012150 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12151 MemExpr->performsVirtualDispatch(getLangOpts())) {
12152 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012153 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12154 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12155 << MD->getParent()->getDeclName();
12156
12157 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012158 if (getLangOpts().AppleKext)
12159 Diag(MemExpr->getLocStart(),
12160 diag::note_pure_qualified_call_kext)
12161 << MD->getParent()->getDeclName()
12162 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012163 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012164 }
John McCallb268a282010-08-23 23:25:46 +000012165 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012166}
12167
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012168/// BuildCallToObjectOfClassType - Build a call to an object of class
12169/// type (C++ [over.call.object]), which can end up invoking an
12170/// overloaded function call operator (@c operator()) or performing a
12171/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012172ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012173Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012174 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012175 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012176 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012177 if (checkPlaceholderForOverload(*this, Obj))
12178 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012179 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012180
12181 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012182 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012183 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012184
Nico Weberb58e51c2014-11-19 05:21:39 +000012185 assert(Object.get()->getType()->isRecordType() &&
12186 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012187 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012188
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012189 // C++ [over.call.object]p1:
12190 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012191 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012192 // candidate functions includes at least the function call
12193 // operators of T. The function call operators of T are obtained by
12194 // ordinary lookup of the name operator() in the context of
12195 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012196 OverloadCandidateSet CandidateSet(LParenLoc,
12197 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012198 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012199
John Wiegley01296292011-04-08 18:41:53 +000012200 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012201 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012202 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012203
John McCall27b18f82009-11-17 02:14:36 +000012204 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12205 LookupQualifiedName(R, Record->getDecl());
12206 R.suppressDiagnostics();
12207
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012208 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012209 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012210 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012211 Object.get()->Classify(Context),
12212 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012213 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012215
Douglas Gregorab7897a2008-11-19 22:57:39 +000012216 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012217 // In addition, for each (non-explicit in C++0x) conversion function
12218 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012219 //
12220 // operator conversion-type-id () cv-qualifier;
12221 //
12222 // where cv-qualifier is the same cv-qualification as, or a
12223 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012224 // denotes the type "pointer to function of (P1,...,Pn) returning
12225 // R", or the type "reference to pointer to function of
12226 // (P1,...,Pn) returning R", or the type "reference to function
12227 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012228 // is also considered as a candidate function. Similarly,
12229 // surrogate call functions are added to the set of candidate
12230 // functions for each conversion function declared in an
12231 // accessible base class provided the function is not hidden
12232 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012233 const auto &Conversions =
12234 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12235 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012236 NamedDecl *D = *I;
12237 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12238 if (isa<UsingShadowDecl>(D))
12239 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012240
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012241 // Skip over templated conversion functions; they aren't
12242 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012243 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012244 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012245
John McCall6e9f8f62009-12-03 04:06:58 +000012246 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012247 if (!Conv->isExplicit()) {
12248 // Strip the reference type (if any) and then the pointer type (if
12249 // any) to get down to what might be a function type.
12250 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12251 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12252 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012253
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012254 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12255 {
12256 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012257 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012258 }
12259 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012260 }
Mike Stump11289f42009-09-09 15:08:12 +000012261
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012262 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12263
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012264 // Perform overload resolution.
12265 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012266 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012267 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012268 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012269 // Overload resolution succeeded; we'll build the appropriate call
12270 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012271 break;
12272
12273 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012274 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012275 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012276 << Object.get()->getType() << /*call*/ 1
12277 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012278 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012279 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012280 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012281 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012282 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012283 break;
12284
12285 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012286 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012287 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012288 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012289 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012290 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012291
12292 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012293 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012294 diag::err_ovl_deleted_object_call)
12295 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012296 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012297 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012298 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012299 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012300 break;
Mike Stump11289f42009-09-09 15:08:12 +000012301 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012302
Douglas Gregorb412e172010-07-25 18:17:45 +000012303 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012304 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012305
John McCall4124c492011-10-17 18:40:02 +000012306 UnbridgedCasts.restore();
12307
Craig Topperc3ec1492014-05-26 06:22:03 +000012308 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012309 // Since there is no function declaration, this is one of the
12310 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012311 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012312 = cast<CXXConversionDecl>(
12313 Best->Conversions[0].UserDefined.ConversionFunction);
12314
Craig Topperc3ec1492014-05-26 06:22:03 +000012315 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12316 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012317 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12318 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012319 assert(Conv == Best->FoundDecl.getDecl() &&
12320 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012321 // We selected one of the surrogate functions that converts the
12322 // object parameter to a function pointer. Perform the conversion
12323 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012324
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012325 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012326 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012327 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12328 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012329 if (Call.isInvalid())
12330 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012331 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012332 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12333 CK_UserDefinedConversion, Call.get(),
12334 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012335
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012336 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012337 }
12338
Craig Topperc3ec1492014-05-26 06:22:03 +000012339 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012340
Douglas Gregorab7897a2008-11-19 22:57:39 +000012341 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12342 // that calls this method, using Object for the implicit object
12343 // parameter and passing along the remaining arguments.
12344 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012345
12346 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012347 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012348 return ExprError();
12349
Chandler Carruth8e543b32010-12-12 08:17:55 +000012350 const FunctionProtoType *Proto =
12351 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012352
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012353 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012354
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012355 DeclarationNameInfo OpLocInfo(
12356 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12357 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012358 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012359 HadMultipleCandidates,
12360 OpLocInfo.getLoc(),
12361 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012362 if (NewFn.isInvalid())
12363 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012364
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012365 // Build the full argument list for the method call (the implicit object
12366 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012367 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012368 MethodArgs[0] = Object.get();
12369 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12370
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012371 // Once we've built TheCall, all of the expressions are properly
12372 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012373 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012374 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12375 ResultTy = ResultTy.getNonLValueExprType(Context);
12376
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012377 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012378 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012379 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12380 ResultTy, VK, RParenLoc, false);
12381 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012382
Alp Toker314cc812014-01-25 16:55:45 +000012383 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012384 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012385
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012386 // We may have default arguments. If so, we need to allocate more
12387 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012388 if (Args.size() < NumParams)
12389 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012390
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012391 bool IsError = false;
12392
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012393 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012394 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012395 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012396 Best->FoundDecl, Method);
12397 if (ObjRes.isInvalid())
12398 IsError = true;
12399 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012400 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012401 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012402
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012403 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012404 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012405 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012406 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012407 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012408
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012409 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012410
John McCalldadc5752010-08-24 06:29:42 +000012411 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012412 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012413 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012414 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012415 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012416
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012417 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012418 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012419 } else {
John McCalldadc5752010-08-24 06:29:42 +000012420 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012421 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12422 if (DefArg.isInvalid()) {
12423 IsError = true;
12424 break;
12425 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012426
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012427 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012428 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012429
12430 TheCall->setArg(i + 1, Arg);
12431 }
12432
12433 // If this is a variadic call, handle args passed through "...".
12434 if (Proto->isVariadic()) {
12435 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012436 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012437 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12438 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012439 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012440 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012441 }
12442 }
12443
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012444 if (IsError) return true;
12445
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012446 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012447
Richard Smith55ce3522012-06-25 20:30:08 +000012448 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012449 return true;
12450
John McCalle172be52010-08-24 06:09:16 +000012451 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012452}
12453
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012454/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012455/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012456/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012457ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012458Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12459 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012460 assert(Base->getType()->isRecordType() &&
12461 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012462
John McCall4124c492011-10-17 18:40:02 +000012463 if (checkPlaceholderForOverload(*this, Base))
12464 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012465
John McCallbc077cf2010-02-08 23:07:23 +000012466 SourceLocation Loc = Base->getExprLoc();
12467
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012468 // C++ [over.ref]p1:
12469 //
12470 // [...] An expression x->m is interpreted as (x.operator->())->m
12471 // for a class object x of type T if T::operator->() exists and if
12472 // the operator is selected as the best match function by the
12473 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012474 DeclarationName OpName =
12475 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012476 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012477 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012478
John McCallbc077cf2010-02-08 23:07:23 +000012479 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012480 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012481 return ExprError();
12482
John McCall27b18f82009-11-17 02:14:36 +000012483 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12484 LookupQualifiedName(R, BaseRecord->getDecl());
12485 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012486
12487 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012488 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012489 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012490 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012491 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012492
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012493 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12494
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012495 // Perform overload resolution.
12496 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012497 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012498 case OR_Success:
12499 // Overload resolution succeeded; we'll build the call below.
12500 break;
12501
12502 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012503 if (CandidateSet.empty()) {
12504 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012505 if (NoArrowOperatorFound) {
12506 // Report this specific error to the caller instead of emitting a
12507 // diagnostic, as requested.
12508 *NoArrowOperatorFound = true;
12509 return ExprError();
12510 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012511 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12512 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012513 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012514 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012515 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012516 }
12517 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012518 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012519 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012520 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012521 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012522
12523 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012524 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12525 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012526 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012527 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012528
12529 case OR_Deleted:
12530 Diag(OpLoc, diag::err_ovl_deleted_oper)
12531 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012532 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012533 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012534 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012535 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012536 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012537 }
12538
Craig Topperc3ec1492014-05-26 06:22:03 +000012539 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012540
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012541 // Convert the object parameter.
12542 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012543 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012544 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012545 Best->FoundDecl, Method);
12546 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012547 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012548 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012549
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012550 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012551 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012552 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012553 if (FnExpr.isInvalid())
12554 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012555
Alp Toker314cc812014-01-25 16:55:45 +000012556 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012557 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12558 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012559 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012560 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012561 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012562
Alp Toker314cc812014-01-25 16:55:45 +000012563 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012564 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012565
12566 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012567}
12568
Richard Smithbcc22fc2012-03-09 08:00:36 +000012569/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12570/// a literal operator described by the provided lookup results.
12571ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12572 DeclarationNameInfo &SuffixInfo,
12573 ArrayRef<Expr*> Args,
12574 SourceLocation LitEndLoc,
12575 TemplateArgumentListInfo *TemplateArgs) {
12576 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012577
Richard Smith100b24a2014-04-17 01:52:14 +000012578 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12579 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012580 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12581 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012582
Richard Smithbcc22fc2012-03-09 08:00:36 +000012583 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12584
Richard Smithbcc22fc2012-03-09 08:00:36 +000012585 // Perform overload resolution. This will usually be trivial, but might need
12586 // to perform substitutions for a literal operator template.
12587 OverloadCandidateSet::iterator Best;
12588 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12589 case OR_Success:
12590 case OR_Deleted:
12591 break;
12592
12593 case OR_No_Viable_Function:
12594 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12595 << R.getLookupName();
12596 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12597 return ExprError();
12598
12599 case OR_Ambiguous:
12600 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12601 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12602 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012603 }
12604
Richard Smithbcc22fc2012-03-09 08:00:36 +000012605 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012606 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12607 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012608 SuffixInfo.getLoc(),
12609 SuffixInfo.getInfo());
12610 if (Fn.isInvalid())
12611 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012612
12613 // Check the argument types. This should almost always be a no-op, except
12614 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012615 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012616 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012617 ExprResult InputInit = PerformCopyInitialization(
12618 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12619 SourceLocation(), Args[ArgIdx]);
12620 if (InputInit.isInvalid())
12621 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012622 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012623 }
12624
Alp Toker314cc812014-01-25 16:55:45 +000012625 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012626 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12627 ResultTy = ResultTy.getNonLValueExprType(Context);
12628
Richard Smithc67fdd42012-03-07 08:35:16 +000012629 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012630 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012631 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012632 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12633
Alp Toker314cc812014-01-25 16:55:45 +000012634 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012635 return ExprError();
12636
Craig Topperc3ec1492014-05-26 06:22:03 +000012637 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012638 return ExprError();
12639
12640 return MaybeBindToTemporary(UDL);
12641}
12642
Sam Panzer0f384432012-08-21 00:52:01 +000012643/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12644/// given LookupResult is non-empty, it is assumed to describe a member which
12645/// will be invoked. Otherwise, the function will be found via argument
12646/// dependent lookup.
12647/// CallExpr is set to a valid expression and FRS_Success returned on success,
12648/// otherwise CallExpr is set to ExprError() and some non-success value
12649/// is returned.
12650Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012651Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12652 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012653 const DeclarationNameInfo &NameInfo,
12654 LookupResult &MemberLookup,
12655 OverloadCandidateSet *CandidateSet,
12656 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012657 Scope *S = nullptr;
12658
Sam Panzer0f384432012-08-21 00:52:01 +000012659 CandidateSet->clear();
12660 if (!MemberLookup.empty()) {
12661 ExprResult MemberRef =
12662 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12663 /*IsPtr=*/false, CXXScopeSpec(),
12664 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012665 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012666 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012667 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012668 if (MemberRef.isInvalid()) {
12669 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012670 return FRS_DiagnosticIssued;
12671 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012672 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012673 if (CallExpr->isInvalid()) {
12674 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012675 return FRS_DiagnosticIssued;
12676 }
12677 } else {
12678 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012679 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012680 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012681 NestedNameSpecifierLoc(), NameInfo,
12682 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012683 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012684
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012685 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012686 CandidateSet, CallExpr);
12687 if (CandidateSet->empty() || CandidateSetError) {
12688 *CallExpr = ExprError();
12689 return FRS_NoViableFunction;
12690 }
12691 OverloadCandidateSet::iterator Best;
12692 OverloadingResult OverloadResult =
12693 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12694
12695 if (OverloadResult == OR_No_Viable_Function) {
12696 *CallExpr = ExprError();
12697 return FRS_NoViableFunction;
12698 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012699 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012700 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012701 OverloadResult,
12702 /*AllowTypoCorrection=*/false);
12703 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12704 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012705 return FRS_DiagnosticIssued;
12706 }
12707 }
12708 return FRS_Success;
12709}
12710
12711
Douglas Gregorcd695e52008-11-10 20:40:00 +000012712/// FixOverloadedFunctionReference - E is an expression that refers to
12713/// a C++ overloaded function (possibly with some parentheses and
12714/// perhaps a '&' around it). We have resolved the overloaded function
12715/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012716/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012717Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012718 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012719 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012720 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12721 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012722 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012723 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012724
Douglas Gregor51c538b2009-11-20 19:42:02 +000012725 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012726 }
12727
Douglas Gregor51c538b2009-11-20 19:42:02 +000012728 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012729 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12730 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012731 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012732 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012733 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012734 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012735 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012736 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012737
12738 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012739 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012740 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012741 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012742 }
12743
Douglas Gregor51c538b2009-11-20 19:42:02 +000012744 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012745 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012746 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012747 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12748 if (Method->isStatic()) {
12749 // Do nothing: static member functions aren't any different
12750 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012751 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012752 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012753 // UnresolvedLookupExpr holding an overloaded member function
12754 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012755 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12756 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012757 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012758 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012759
John McCalld14a8642009-11-21 08:51:07 +000012760 assert(isa<DeclRefExpr>(SubExpr)
12761 && "fixed to something other than a decl ref");
12762 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12763 && "fixed to a member ref with no nested name qualifier");
12764
12765 // We have taken the address of a pointer to member
12766 // function. Perform the computation here so that we get the
12767 // appropriate pointer to member type.
12768 QualType ClassType
12769 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12770 QualType MemPtrType
12771 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12772
John McCall7decc9e2010-11-18 06:31:45 +000012773 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12774 VK_RValue, OK_Ordinary,
12775 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012776 }
12777 }
John McCall16df1e52010-03-30 21:47:33 +000012778 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12779 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012780 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012781 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012782
John McCalle3027922010-08-25 11:45:40 +000012783 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012784 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012785 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012786 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012787 }
John McCalld14a8642009-11-21 08:51:07 +000012788
12789 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012790 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012791 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012792 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012793 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12794 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012795 }
12796
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012797 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12798 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012799 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012800 Fn,
John McCall113bee02012-03-10 09:33:50 +000012801 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012802 ULE->getNameLoc(),
12803 Fn->getType(),
12804 VK_LValue,
12805 Found.getDecl(),
12806 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012807 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012808 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12809 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012810 }
12811
John McCall10eae182009-11-30 22:42:35 +000012812 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012813 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012814 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012815 if (MemExpr->hasExplicitTemplateArgs()) {
12816 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12817 TemplateArgs = &TemplateArgsBuffer;
12818 }
John McCall6b51f282009-11-23 01:53:49 +000012819
John McCall2d74de92009-12-01 22:10:20 +000012820 Expr *Base;
12821
John McCall7decc9e2010-11-18 06:31:45 +000012822 // If we're filling in a static method where we used to have an
12823 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012824 if (MemExpr->isImplicitAccess()) {
12825 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012826 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12827 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012828 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012829 Fn,
John McCall113bee02012-03-10 09:33:50 +000012830 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012831 MemExpr->getMemberLoc(),
12832 Fn->getType(),
12833 VK_LValue,
12834 Found.getDecl(),
12835 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012836 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012837 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12838 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012839 } else {
12840 SourceLocation Loc = MemExpr->getMemberLoc();
12841 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012842 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012843 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012844 Base = new (Context) CXXThisExpr(Loc,
12845 MemExpr->getBaseType(),
12846 /*isImplicit=*/true);
12847 }
John McCall2d74de92009-12-01 22:10:20 +000012848 } else
John McCallc3007a22010-10-26 07:05:15 +000012849 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012850
John McCall4adb38c2011-04-27 00:36:17 +000012851 ExprValueKind valueKind;
12852 QualType type;
12853 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12854 valueKind = VK_LValue;
12855 type = Fn->getType();
12856 } else {
12857 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012858 type = Context.BoundMemberTy;
12859 }
12860
12861 MemberExpr *ME = MemberExpr::Create(
12862 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12863 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12864 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12865 OK_Ordinary);
12866 ME->setHadMultipleCandidates(true);
12867 MarkMemberReferenced(ME);
12868 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012870
John McCallc3007a22010-10-26 07:05:15 +000012871 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012872}
12873
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012874ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012875 DeclAccessPair Found,
12876 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012877 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012878}