blob: 91d02dacc82d10ae859dd9c6bd2b6176e10b8086 [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-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 Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
John McCallf89e55a2010-11-18 06:31:45 +000039/// A convenience routine for creating a decayed reference to a
40/// function.
John Wiegley429bb272011-04-08 18:41:53 +000041static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000045 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000046 VK_LValue, Loc, LocInfo);
47 if (HadMultipleCandidates)
48 DRE->setHadMultipleCandidates(true);
49 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000050 E = S.DefaultFunctionArrayConversion(E.take());
51 if (E.isInvalid())
52 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000053 return E;
John McCallf89e55a2010-11-18 06:31:45 +000054}
55
John McCall120d63c2010-08-24 20:38:10 +000056static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000058 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000059 bool CStyle,
60 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000061
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000062static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63 QualType &ToType,
64 bool InOverloadResolution,
65 StandardConversionSequence &SCS,
66 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000067static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69 UserDefinedConversionSequence& User,
70 OverloadCandidateSet& Conversions,
71 bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86 const StandardConversionSequence& SCS1,
87 const StandardConversionSequence& SCS2);
88
89
90
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000091/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000093ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094GetConversionCategory(ImplicitConversionKind Kind) {
95 static const ImplicitConversionCategory
96 Category[(int)ICK_Num_Conversion_Kinds] = {
97 ICC_Identity,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
100 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000101 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 ICC_Qualification_Adjustment,
103 ICC_Promotion,
104 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 ICC_Promotion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
112 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000113 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000114 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000115 ICC_Conversion,
116 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000117 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000118 ICC_Conversion
119 };
120 return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126 static const ImplicitConversionRank
127 Rank[(int)ICK_Num_Conversion_Kinds] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000133 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134 ICR_Promotion,
135 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000144 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000145 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000146 ICR_Conversion,
147 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000148 ICR_Complex_Real_Conversion,
149 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000150 ICR_Conversion,
151 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 };
153 return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000160 "No conversion",
161 "Lvalue-to-rvalue",
162 "Array-to-pointer",
163 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000164 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 "Qualification",
166 "Integral promotion",
167 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000168 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 "Integral conversion",
170 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000171 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 "Floating-integral conversion",
173 "Pointer conversion",
174 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000175 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000176 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000177 "Derived-to-base conversion",
178 "Vector conversion",
179 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000183 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000184 };
185 return Name[Kind];
186}
187
Douglas Gregor60d62c22008-10-31 16:23:19 +0000188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191 First = ICK_Identity;
192 Second = ICK_Identity;
193 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000194 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000195 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000196 ReferenceBinding = false;
197 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000198 IsLvalueReference = true;
199 BindsToFunctionLvalue = false;
200 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000201 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000202 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000203 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000204}
205
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210 ImplicitConversionRank Rank = ICR_Exact_Match;
211 if (GetConversionRank(First) > Rank)
212 Rank = GetConversionRank(First);
213 if (GetConversionRank(Second) > Rank)
214 Rank = GetConversionRank(Second);
215 if (GetConversionRank(Third) > Rank)
216 Rank = GetConversionRank(Third);
217 return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000222/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000224bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer or function-to-pointer implicit conversions, so
227 // check for their presence as well as checking whether FromType is
228 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000229 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000230 (getFromType()->isPointerType() ||
231 getFromType()->isObjCObjectPointerType() ||
232 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000233 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 return true;
236
237 return false;
238}
239
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000244bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000245StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000246isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000247 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000248 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000249
250 // Note that FromType has not necessarily been transformed by the
251 // array-to-pointer implicit conversion, so check for its presence
252 // and redo the conversion to get a pointer.
253 if (First == ICK_Array_To_Pointer)
254 FromType = Context.getArrayDecayedType(FromType);
255
Douglas Gregorf9af5242011-04-15 20:45:44 +0000256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258 return ToPtrType->getPointeeType()->isVoidType();
259
260 return false;
261}
262
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267 switch (ICE->getCastKind()) {
268 case CK_NoOp:
269 case CK_IntegralCast:
270 case CK_IntegralToBoolean:
271 case CK_IntegralToFloating:
272 case CK_FloatingToIntegral:
273 case CK_FloatingToBoolean:
274 case CK_FloatingCast:
275 Converted = ICE->getSubExpr();
276 continue;
277
278 default:
279 return Converted;
280 }
281 }
282
283 return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx The AST context.
290/// \param Converted The result of applying this standard conversion sequence.
291/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
292/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000293/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
294/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000295NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000298 APValue &ConstantValue,
299 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000301
302 // C++11 [dcl.init.list]p7:
303 // A narrowing conversion is an implicit conversion ...
304 QualType FromType = getToType(0);
305 QualType ToType = getToType(1);
306 switch (Second) {
307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
314 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 Smithf6028062012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-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 Smithf6028062012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000366 }
Richard Smith4c3fc9b2012-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.
378 case ICK_Boolean_Conversion: // Bools are integers too.
379 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380 // Boolean conversions can be from pointers and pointers to members
381 // [conv.bool], and those aren't considered narrowing conversions.
382 return NK_Not_Narrowing;
383 } // Otherwise, fall through to the integral case.
384 case ICK_Integral_Conversion: {
385 assert(FromType->isIntegralOrUnscopedEnumerationType());
386 assert(ToType->isIntegralOrUnscopedEnumerationType());
387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388 const unsigned FromWidth = Ctx.getIntWidth(FromType);
389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390 const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000393 (FromWidth == ToWidth && FromSigned != ToSigned) ||
394 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000395 // Not all values of FromType can be represented in ToType.
396 llvm::APSInt InitializerValue;
397 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399 // Such conversions on variables are always narrowing.
400 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000401 }
402 bool Narrowing = false;
403 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000404 // Negative -> unsigned is narrowing. Otherwise, more bits is never
405 // narrowing.
406 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000407 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000408 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000409 // Add a bit to the InitializerValue so we don't have to worry about
410 // signed vs. unsigned comparisons.
411 InitializerValue = InitializerValue.extend(
412 InitializerValue.getBitWidth() + 1);
413 // Convert the initializer to and from the target width and signed-ness.
414 llvm::APSInt ConvertedValue = InitializerValue;
415 ConvertedValue = ConvertedValue.trunc(ToWidth);
416 ConvertedValue.setIsSigned(ToSigned);
417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418 ConvertedValue.setIsSigned(InitializerValue.isSigned());
419 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 if (ConvertedValue != InitializerValue)
421 Narrowing = true;
422 }
423 if (Narrowing) {
424 ConstantType = Initializer->getType();
425 ConstantValue = APValue(InitializerValue);
426 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000427 }
428 }
429 return NK_Not_Narrowing;
430 }
431
432 default:
433 // Other kinds of conversions are not narrowings.
434 return NK_Not_Narrowing;
435 }
436}
437
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000441 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 bool PrintedSomething = false;
443 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000444 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000445 PrintedSomething = true;
446 }
447
448 if (Second != ICK_Identity) {
449 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000450 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000453
454 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000455 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000456 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000458 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000459 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000460 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Third != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000467 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000473 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 if (Before.First || Before.Second || Before.Third) {
482 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000483 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000484 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000485 if (ConversionFunction)
486 OS << '\'' << *ConversionFunction << '\'';
487 else
488 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 After.DebugPrint();
492 }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000498 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 switch (ConversionKind) {
500 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000501 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 Standard.DebugPrint();
503 break;
504 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 UserDefined.DebugPrint();
507 break;
508 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 break;
John McCall1d318332010-01-12 00:44:57 +0000511 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000512 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000513 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000515 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 break;
517 }
518
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000519 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520}
521
John McCall1d318332010-01-12 00:44:57 +0000522void AmbiguousConversionSequence::construct() {
523 new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527 conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532 FromTypePtr = O.FromTypePtr;
533 ToTypePtr = O.ToTypePtr;
534 new (&conversions()) ConversionSet(O.conversions());
535}
536
Douglas Gregora9333192010-05-08 17:41:32 +0000537namespace {
538 // Structure used by OverloadCandidate::DeductionFailureInfo to store
539 // template parameter and template argument information.
540 struct DFIParamWithArguments {
541 TemplateParameter Param;
542 TemplateArgument FirstArg;
543 TemplateArgument SecondArg;
544 };
545}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000546
Douglas Gregora9333192010-05-08 17:41:32 +0000547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000550static MakeDeductionFailureInfo(ASTContext &Context,
551 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000552 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000553 OverloadCandidate::DeductionFailureInfo Result;
554 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000555 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000556 Result.Data = 0;
557 switch (TDK) {
558 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000559 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000560 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000561 case Sema::TDK_TooManyArguments:
562 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000563 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000564
Douglas Gregora9333192010-05-08 17:41:32 +0000565 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000566 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000567 Result.Data = Info.Param.getOpaqueValue();
568 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569
Douglas Gregora9333192010-05-08 17:41:32 +0000570 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000571 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000574 Saved->Param = Info.Param;
575 Saved->FirstArg = Info.FirstArg;
576 Saved->SecondArg = Info.SecondArg;
577 Result.Data = Saved;
578 break;
579 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580
Douglas Gregora9333192010-05-08 17:41:32 +0000581 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000582 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000583 if (Info.hasSFINAEDiagnostic()) {
584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585 SourceLocation(), PartialDiagnostic::NullDiagnostic());
586 Info.takeSFINAEDiagnostic(*Diag);
587 Result.HasDiagnostic = true;
588 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000589 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregora9333192010-05-08 17:41:32 +0000591 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000592 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000594 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000595
Douglas Gregora9333192010-05-08 17:41:32 +0000596 return Result;
597}
John McCall1d318332010-01-12 00:44:57 +0000598
Douglas Gregora9333192010-05-08 17:41:32 +0000599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000608 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000611 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000612 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000613 Data = 0;
614 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000615
616 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000617 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000618 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620 Diag->~PartialDiagnosticAt();
621 HasDiagnostic = false;
622 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000625 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000627 case Sema::TDK_FailedOverloadResolution:
628 break;
629 }
630}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000631
Richard Smithb8590f32012-05-07 09:03:25 +0000632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636 return 0;
637}
638
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000643 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000644 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000645 case Sema::TDK_TooManyArguments:
646 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000647 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000648 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000649
Douglas Gregora9333192010-05-08 17:41:32 +0000650 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000651 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000653
654 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000655 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000656 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657
Douglas Gregora9333192010-05-08 17:41:32 +0000658 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000659 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000660 case Sema::TDK_FailedOverloadResolution:
661 break;
662 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000663
Douglas Gregora9333192010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000666
Douglas Gregorec20f462010-05-08 20:07:26 +0000667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000671 case Sema::TDK_Invalid:
Douglas Gregorec20f462010-05-08 20:07:26 +0000672 case Sema::TDK_InstantiationDepth:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_Incomplete:
676 case Sema::TDK_InvalidExplicitArguments:
677 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000679 return 0;
680
681 case Sema::TDK_SubstitutionFailure:
682 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000683
Douglas Gregorec20f462010-05-08 20:07:26 +0000684 // Unhandled
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 break;
688 }
689
690 return 0;
691}
692
Douglas Gregora9333192010-05-08 17:41:32 +0000693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000703 return 0;
704
Douglas Gregora9333192010-05-08 17:41:32 +0000705 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000706 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000708
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000709 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000710 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000711 case Sema::TDK_FailedOverloadResolution:
712 break;
713 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000714
Douglas Gregora9333192010-05-08 17:41:32 +0000715 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716}
Douglas Gregora9333192010-05-08 17:41:32 +0000717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 return 0;
730
Douglas Gregora9333192010-05-08 17:41:32 +0000731 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000732 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000735 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000736 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000737 case Sema::TDK_FailedOverloadResolution:
738 break;
739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000740
Douglas Gregora9333192010-05-08 17:41:32 +0000741 return 0;
742}
743
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000744void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000745 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749 i->DeductionFailure.Destroy();
750 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000751}
752
753void OverloadCandidateSet::clear() {
754 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000755 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000756 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000757 Functions.clear();
758}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000759
John McCall5acb0c92011-10-17 18:40:02 +0000760namespace {
761 class UnbridgedCastsSet {
762 struct Entry {
763 Expr **Addr;
764 Expr *Saved;
765 };
766 SmallVector<Entry, 2> Entries;
767
768 public:
769 void save(Sema &S, Expr *&E) {
770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771 Entry entry = { &E, E };
772 Entries.push_back(entry);
773 E = S.stripARCUnbridgedCast(E);
774 }
775
776 void restore() {
777 for (SmallVectorImpl<Entry>::iterator
778 i = Entries.begin(), e = Entries.end(); i != e; ++i)
779 *i->Addr = i->Saved;
780 }
781 };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788/// without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
794 // We can't handle overloaded expressions here because overload
795 // resolution might reasonably tweak them.
796 if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798 // If the context potentially accepts unbridged ARC casts, strip
799 // the unbridged cast and add it to the collection for later restoration.
800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801 unbridgedCasts) {
802 unbridgedCasts->save(S, E);
803 return false;
804 }
805
806 // Go ahead and check everything else.
807 ExprResult result = S.CheckPlaceholderExpr(E);
808 if (result.isInvalid())
809 return true;
810
811 E = result.take();
812 return false;
813 }
814
815 // Nothing to do.
816 return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822 unsigned numArgs,
823 UnbridgedCastsSet &unbridged) {
824 for (unsigned i = 0; i != numArgs; ++i)
825 if (checkPlaceholderForOverload(S, args[i], &unbridged))
826 return true;
827
828 return false;
829}
830
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000831// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with. This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000839//
840// Example: Given the following input:
841//
842// void f(int, float); // #1
843// void f(int, int); // #2
844// int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000847// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000848//
John McCall51fa86f2009-12-02 08:47:38 +0000849// When we process #2, Old contains only the FunctionDecl for #1. By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000853//
John McCall51fa86f2009-12-02 08:47:38 +0000854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration. The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000865Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000868 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000869 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000870 NamedDecl *OldD = *I;
871
872 bool OldIsUsingDecl = false;
873 if (isa<UsingShadowDecl>(OldD)) {
874 OldIsUsingDecl = true;
875
876 // We can always introduce two using declarations into the same
877 // context, even if they have identical signatures.
878 if (NewIsUsingDecl) continue;
879
880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881 }
882
883 // If either declaration was introduced by a using declaration,
884 // we'll need to use slightly different rules for matching.
885 // Essentially, these rules are the normal rules, except that
886 // function templates hide function templates with different
887 // return types or template parameter lists.
888 bool UseMemberUsingDeclRules =
889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
John McCall51fa86f2009-12-02 08:47:38 +0000891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895 continue;
896 }
897
John McCall871b2e72009-12-09 03:35:25 +0000898 Match = *I;
899 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000900 }
John McCall51fa86f2009-12-02 08:47:38 +0000901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905 continue;
906 }
907
John McCall871b2e72009-12-09 03:35:25 +0000908 Match = *I;
909 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000910 }
John McCalld7945c62010-11-10 03:01:53 +0000911 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000912 // We can overload with these, which can show up when doing
913 // redeclaration checks for UsingDecls.
914 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000915 } else if (isa<TagDecl>(OldD)) {
916 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918 // Optimistically assume that an unresolved using decl will
919 // overload; if it doesn't, we'll have to diagnose during
920 // template instantiation.
921 } else {
John McCall68263142009-11-18 22:49:29 +0000922 // (C++ 13p1):
923 // Only function declarations can be overloaded; object and type
924 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000925 Match = *I;
926 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000927 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000928 }
John McCall68263142009-11-18 22:49:29 +0000929
John McCall871b2e72009-12-09 03:35:25 +0000930 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000931}
932
Rafael Espindola78eeba82012-12-28 14:21:58 +0000933static bool canBeOverloaded(const FunctionDecl &D) {
934 if (D.getAttr<OverloadableAttr>())
935 return true;
936 if (D.hasCLanguageLinkage())
937 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000938
939 // Main cannot be overloaded (basic.start.main).
940 if (D.isMain())
941 return false;
942
Rafael Espindola78eeba82012-12-28 14:21:58 +0000943 return true;
944}
945
John McCallad00b772010-06-16 08:42:20 +0000946bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
947 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000948 // If both of the functions are extern "C", then they are not
949 // overloads.
Rafael Espindola78eeba82012-12-28 14:21:58 +0000950 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
John McCall7b492022010-08-12 07:09:11 +0000951 return false;
952
John McCall68263142009-11-18 22:49:29 +0000953 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
954 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
955
956 // C++ [temp.fct]p2:
957 // A function template can be overloaded with other function templates
958 // and with normal (non-template) functions.
959 if ((OldTemplate == 0) != (NewTemplate == 0))
960 return true;
961
962 // Is the function New an overload of the function Old?
963 QualType OldQType = Context.getCanonicalType(Old->getType());
964 QualType NewQType = Context.getCanonicalType(New->getType());
965
966 // Compare the signatures (C++ 1.3.10) of the two functions to
967 // determine whether they are overloads. If we find any mismatch
968 // in the signature, they are overloads.
969
970 // If either of these functions is a K&R-style function (no
971 // prototype), then we consider them to have matching signatures.
972 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
973 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
974 return false;
975
John McCallf4c73712011-01-19 06:33:43 +0000976 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
977 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000978
979 // The signature of a function includes the types of its
980 // parameters (C++ 1.3.10), which includes the presence or absence
981 // of the ellipsis; see C++ DR 357).
982 if (OldQType != NewQType &&
983 (OldType->getNumArgs() != NewType->getNumArgs() ||
984 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000985 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000986 return true;
987
988 // C++ [temp.over.link]p4:
989 // The signature of a function template consists of its function
990 // signature, its return type and its template parameter list. The names
991 // of the template parameters are significant only for establishing the
992 // relationship between the template parameters and the rest of the
993 // signature.
994 //
995 // We check the return type and template parameter lists for function
996 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000997 //
998 // However, we don't consider either of these when deciding whether
999 // a member introduced by a shadow declaration is hidden.
1000 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +00001001 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1002 OldTemplate->getTemplateParameters(),
1003 false, TPL_TemplateMatch) ||
1004 OldType->getResultType() != NewType->getResultType()))
1005 return true;
1006
1007 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001008 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001009 //
1010 // As part of this, also check whether one of the member functions
1011 // is static, in which case they are not overloads (C++
1012 // 13.1p2). While not part of the definition of the signature,
1013 // this check is important to determine whether these functions
1014 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001015 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1016 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001017 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001018 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1019 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1020 if (!UseUsingDeclRules &&
1021 (OldMethod->getRefQualifier() == RQ_None ||
1022 NewMethod->getRefQualifier() == RQ_None)) {
1023 // C++0x [over.load]p2:
1024 // - Member function declarations with the same name and the same
1025 // parameter-type-list as well as member function template
1026 // declarations with the same name, the same parameter-type-list, and
1027 // the same template parameter lists cannot be overloaded if any of
1028 // them, but not all, have a ref-qualifier (8.3.5).
1029 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1030 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1031 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1032 }
1033 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001034 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
Richard Smith21c8fa82013-01-14 05:37:29 +00001036 // We may not have applied the implicit const for a constexpr member
1037 // function yet (because we haven't yet resolved whether this is a static
1038 // or non-static member function). Add it now, on the assumption that this
1039 // is a redeclaration of OldMethod.
1040 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001041 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001042 NewQuals |= Qualifiers::Const;
1043 if (OldMethod->getTypeQualifiers() != NewQuals)
1044 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001045 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001046
John McCall68263142009-11-18 22:49:29 +00001047 // The signatures match; this is not an overload.
1048 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001049}
1050
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001051/// \brief Checks availability of the function depending on the current
1052/// function context. Inside an unavailable function, unavailability is ignored.
1053///
1054/// \returns true if \arg FD is unavailable and current context is inside
1055/// an available function, false otherwise.
1056bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1057 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1058}
1059
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001060/// \brief Tries a user-defined conversion from From to ToType.
1061///
1062/// Produces an implicit conversion sequence for when a standard conversion
1063/// is not an option. See TryImplicitConversion for more information.
1064static ImplicitConversionSequence
1065TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1066 bool SuppressUserConversions,
1067 bool AllowExplicit,
1068 bool InOverloadResolution,
1069 bool CStyle,
1070 bool AllowObjCWritebackConversion) {
1071 ImplicitConversionSequence ICS;
1072
1073 if (SuppressUserConversions) {
1074 // We're not in the case above, so there is no conversion that
1075 // we can perform.
1076 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1077 return ICS;
1078 }
1079
1080 // Attempt user-defined conversion.
1081 OverloadCandidateSet Conversions(From->getExprLoc());
1082 OverloadingResult UserDefResult
1083 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1084 AllowExplicit);
1085
1086 if (UserDefResult == OR_Success) {
1087 ICS.setUserDefined();
1088 // C++ [over.ics.user]p4:
1089 // A conversion of an expression of class type to the same class
1090 // type is given Exact Match rank, and a conversion of an
1091 // expression of class type to a base class of that type is
1092 // given Conversion rank, in spite of the fact that a copy
1093 // constructor (i.e., a user-defined conversion function) is
1094 // called for those cases.
1095 if (CXXConstructorDecl *Constructor
1096 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1097 QualType FromCanon
1098 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1099 QualType ToCanon
1100 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1101 if (Constructor->isCopyConstructor() &&
1102 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1103 // Turn this into a "standard" conversion sequence, so that it
1104 // gets ranked with standard conversion sequences.
1105 ICS.setStandard();
1106 ICS.Standard.setAsIdentityConversion();
1107 ICS.Standard.setFromType(From->getType());
1108 ICS.Standard.setAllToTypes(ToType);
1109 ICS.Standard.CopyConstructor = Constructor;
1110 if (ToCanon != FromCanon)
1111 ICS.Standard.Second = ICK_Derived_To_Base;
1112 }
1113 }
1114
1115 // C++ [over.best.ics]p4:
1116 // However, when considering the argument of a user-defined
1117 // conversion function that is a candidate by 13.3.1.3 when
1118 // invoked for the copying of the temporary in the second step
1119 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1120 // 13.3.1.6 in all cases, only standard conversion sequences and
1121 // ellipsis conversion sequences are allowed.
1122 if (SuppressUserConversions && ICS.isUserDefined()) {
1123 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1124 }
1125 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1126 ICS.setAmbiguous();
1127 ICS.Ambiguous.setFromType(From->getType());
1128 ICS.Ambiguous.setToType(ToType);
1129 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1130 Cand != Conversions.end(); ++Cand)
1131 if (Cand->Viable)
1132 ICS.Ambiguous.addConversion(Cand->Function);
1133 } else {
1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1135 }
1136
1137 return ICS;
1138}
1139
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001140/// TryImplicitConversion - Attempt to perform an implicit conversion
1141/// from the given expression (Expr) to the given type (ToType). This
1142/// function returns an implicit conversion sequence that can be used
1143/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001144///
1145/// void f(float f);
1146/// void g(int i) { f(i); }
1147///
1148/// this routine would produce an implicit conversion sequence to
1149/// describe the initialization of f from i, which will be a standard
1150/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1151/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1152//
1153/// Note that this routine only determines how the conversion can be
1154/// performed; it does not actually perform the conversion. As such,
1155/// it will not produce any diagnostics if no conversion is available,
1156/// but will instead return an implicit conversion sequence of kind
1157/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001158///
1159/// If @p SuppressUserConversions, then user-defined conversions are
1160/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001161/// If @p AllowExplicit, then explicit user-defined conversions are
1162/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001163///
1164/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1165/// writeback conversion, which allows __autoreleasing id* parameters to
1166/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001167static ImplicitConversionSequence
1168TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1169 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001170 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001171 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001172 bool CStyle,
1173 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001174 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001175 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001176 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001177 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001178 return ICS;
1179 }
1180
David Blaikie4e4d0842012-03-11 07:00:24 +00001181 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001182 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001183 return ICS;
1184 }
1185
Douglas Gregor604eb652010-08-11 02:15:33 +00001186 // C++ [over.ics.user]p4:
1187 // A conversion of an expression of class type to the same class
1188 // type is given Exact Match rank, and a conversion of an
1189 // expression of class type to a base class of that type is
1190 // given Conversion rank, in spite of the fact that a copy/move
1191 // constructor (i.e., a user-defined conversion function) is
1192 // called for those cases.
1193 QualType FromType = From->getType();
1194 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001195 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1196 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001197 ICS.setStandard();
1198 ICS.Standard.setAsIdentityConversion();
1199 ICS.Standard.setFromType(FromType);
1200 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001201
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001202 // We don't actually check at this point whether there is a valid
1203 // copy/move constructor, since overloading just assumes that it
1204 // exists. When we actually perform initialization, we'll find the
1205 // appropriate constructor to copy the returned object, if needed.
1206 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001207
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001208 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001209 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001210 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001211
Douglas Gregor604eb652010-08-11 02:15:33 +00001212 return ICS;
1213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001214
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001215 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1216 AllowExplicit, InOverloadResolution, CStyle,
1217 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001218}
1219
John McCallf85e1932011-06-15 23:02:42 +00001220ImplicitConversionSequence
1221Sema::TryImplicitConversion(Expr *From, QualType ToType,
1222 bool SuppressUserConversions,
1223 bool AllowExplicit,
1224 bool InOverloadResolution,
1225 bool CStyle,
1226 bool AllowObjCWritebackConversion) {
1227 return clang::TryImplicitConversion(*this, From, ToType,
1228 SuppressUserConversions, AllowExplicit,
1229 InOverloadResolution, CStyle,
1230 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001231}
1232
Douglas Gregor575c63a2010-04-16 22:27:05 +00001233/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001234/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001235/// converted expression. Flavor is the kind of conversion we're
1236/// performing, used in the error message. If @p AllowExplicit,
1237/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001238ExprResult
1239Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001240 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001241 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001242 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001243}
1244
John Wiegley429bb272011-04-08 18:41:53 +00001245ExprResult
1246Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001247 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001248 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001249 if (checkPlaceholderForOverload(*this, From))
1250 return ExprError();
1251
John McCallf85e1932011-06-15 23:02:42 +00001252 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1253 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001254 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001255 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001256
John McCall120d63c2010-08-24 20:38:10 +00001257 ICS = clang::TryImplicitConversion(*this, From, ToType,
1258 /*SuppressUserConversions=*/false,
1259 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001260 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001261 /*CStyle=*/false,
1262 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001263 return PerformImplicitConversion(From, ToType, ICS, Action);
1264}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001265
1266/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001267/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001268bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1269 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001270 if (Context.hasSameUnqualifiedType(FromType, ToType))
1271 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001272
John McCall00ccbef2010-12-21 00:44:39 +00001273 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1274 // where F adds one of the following at most once:
1275 // - a pointer
1276 // - a member pointer
1277 // - a block pointer
1278 CanQualType CanTo = Context.getCanonicalType(ToType);
1279 CanQualType CanFrom = Context.getCanonicalType(FromType);
1280 Type::TypeClass TyClass = CanTo->getTypeClass();
1281 if (TyClass != CanFrom->getTypeClass()) return false;
1282 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1283 if (TyClass == Type::Pointer) {
1284 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1285 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1286 } else if (TyClass == Type::BlockPointer) {
1287 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1288 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1289 } else if (TyClass == Type::MemberPointer) {
1290 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1291 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1292 } else {
1293 return false;
1294 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001295
John McCall00ccbef2010-12-21 00:44:39 +00001296 TyClass = CanTo->getTypeClass();
1297 if (TyClass != CanFrom->getTypeClass()) return false;
1298 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1299 return false;
1300 }
1301
1302 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1303 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1304 if (!EInfo.getNoReturn()) return false;
1305
1306 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1307 assert(QualType(FromFn, 0).isCanonical());
1308 if (QualType(FromFn, 0) != CanTo) return false;
1309
1310 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001311 return true;
1312}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001313
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001314/// \brief Determine whether the conversion from FromType to ToType is a valid
1315/// vector conversion.
1316///
1317/// \param ICK Will be set to the vector conversion kind, if this is a vector
1318/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001319static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1320 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001321 // We need at least one of these types to be a vector type to have a vector
1322 // conversion.
1323 if (!ToType->isVectorType() && !FromType->isVectorType())
1324 return false;
1325
1326 // Identical types require no conversions.
1327 if (Context.hasSameUnqualifiedType(FromType, ToType))
1328 return false;
1329
1330 // There are no conversions between extended vector types, only identity.
1331 if (ToType->isExtVectorType()) {
1332 // There are no conversions between extended vector types other than the
1333 // identity conversion.
1334 if (FromType->isExtVectorType())
1335 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001336
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001337 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001338 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001339 ICK = ICK_Vector_Splat;
1340 return true;
1341 }
1342 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001343
1344 // We can perform the conversion between vector types in the following cases:
1345 // 1)vector types are equivalent AltiVec and GCC vector types
1346 // 2)lax vector conversions are permitted and the vector types are of the
1347 // same size
1348 if (ToType->isVectorType() && FromType->isVectorType()) {
1349 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001350 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001351 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001352 ICK = ICK_Vector_Conversion;
1353 return true;
1354 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001355 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001356
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001357 return false;
1358}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregor7d000652012-04-12 20:48:09 +00001360static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1361 bool InOverloadResolution,
1362 StandardConversionSequence &SCS,
1363 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001364
Douglas Gregor60d62c22008-10-31 16:23:19 +00001365/// IsStandardConversion - Determines whether there is a standard
1366/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1367/// expression From to the type ToType. Standard conversion sequences
1368/// only consider non-class types; for conversions that involve class
1369/// types, use TryImplicitConversion. If a conversion exists, SCS will
1370/// contain the standard conversion sequence required to perform this
1371/// conversion and this routine will return true. Otherwise, this
1372/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001373static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1374 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001375 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001376 bool CStyle,
1377 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001378 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379
Douglas Gregor60d62c22008-10-31 16:23:19 +00001380 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001381 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001382 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001383 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001384 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001385 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001386
Douglas Gregorf9201e02009-02-11 23:02:49 +00001387 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001388 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001389 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001390 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001391 return false;
1392
Mike Stump1eb44332009-09-09 15:08:12 +00001393 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001394 }
1395
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001396 // The first conversion can be an lvalue-to-rvalue conversion,
1397 // array-to-pointer conversion, or function-to-pointer conversion
1398 // (C++ 4p1).
1399
John McCall120d63c2010-08-24 20:38:10 +00001400 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001401 DeclAccessPair AccessPair;
1402 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001403 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001404 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001405 // We were able to resolve the address of the overloaded function,
1406 // so we can convert to the type of that function.
1407 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001408
1409 // we can sometimes resolve &foo<int> regardless of ToType, so check
1410 // if the type matches (identity) or we are converting to bool
1411 if (!S.Context.hasSameUnqualifiedType(
1412 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1413 QualType resultTy;
1414 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001415 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001416 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1417 // otherwise, only a boolean conversion is standard
1418 if (!ToType->isBooleanType())
1419 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001420 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001421
Chandler Carruth90434232011-03-29 08:08:18 +00001422 // Check if the "from" expression is taking the address of an overloaded
1423 // function and recompute the FromType accordingly. Take advantage of the
1424 // fact that non-static member functions *must* have such an address-of
1425 // expression.
1426 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1427 if (Method && !Method->isStatic()) {
1428 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1429 "Non-unary operator on non-static member address");
1430 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1431 == UO_AddrOf &&
1432 "Non-address-of operator on non-static member address");
1433 const Type *ClassType
1434 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1435 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001436 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1437 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1438 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001439 "Non-address-of operator for overloaded function expression");
1440 FromType = S.Context.getPointerType(FromType);
1441 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001442
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001443 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001444 assert(S.Context.hasSameType(
1445 FromType,
1446 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001447 } else {
1448 return false;
1449 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001450 }
John McCall21480112011-08-30 00:57:29 +00001451 // Lvalue-to-rvalue conversion (C++11 4.1):
1452 // A glvalue (3.10) of a non-function, non-array type T can
1453 // be converted to a prvalue.
1454 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001455 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001456 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001457 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001458 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001459
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001460 // C11 6.3.2.1p2:
1461 // ... if the lvalue has atomic type, the value has the non-atomic version
1462 // of the type of the lvalue ...
1463 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1464 FromType = Atomic->getValueType();
1465
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001466 // If T is a non-class type, the type of the rvalue is the
1467 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001468 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1469 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001470 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001471 } else if (FromType->isArrayType()) {
1472 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001473 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001474
1475 // An lvalue or rvalue of type "array of N T" or "array of unknown
1476 // bound of T" can be converted to an rvalue of type "pointer to
1477 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001478 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001479
John McCall120d63c2010-08-24 20:38:10 +00001480 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001481 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001482 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001483
1484 // For the purpose of ranking in overload resolution
1485 // (13.3.3.1.1), this conversion is considered an
1486 // array-to-pointer conversion followed by a qualification
1487 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001488 SCS.Second = ICK_Identity;
1489 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001490 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001491 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001492 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001493 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001494 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001495 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001496 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001497
1498 // An lvalue of function type T can be converted to an rvalue of
1499 // type "pointer to T." The result is a pointer to the
1500 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001501 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001502 } else {
1503 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001506 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001507
1508 // The second conversion can be an integral promotion, floating
1509 // point promotion, integral conversion, floating point conversion,
1510 // floating-integral conversion, pointer conversion,
1511 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001512 // For overloading in C, this can also be a "compatible-type"
1513 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001514 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001515 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001516 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517 // The unqualified versions of the types are the same: there's no
1518 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001519 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001520 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001521 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001524 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001525 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001528 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001529 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001530 SCS.Second = ICK_Complex_Promotion;
1531 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001532 } else if (ToType->isBooleanType() &&
1533 (FromType->isArithmeticType() ||
1534 FromType->isAnyPointerType() ||
1535 FromType->isBlockPointerType() ||
1536 FromType->isMemberPointerType() ||
1537 FromType->isNullPtrType())) {
1538 // Boolean conversions (C++ 4.12).
1539 SCS.Second = ICK_Boolean_Conversion;
1540 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001541 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001542 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001543 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001544 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001545 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001546 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001547 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001548 SCS.Second = ICK_Complex_Conversion;
1549 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001550 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1551 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001552 // Complex-real conversions (C99 6.3.1.7)
1553 SCS.Second = ICK_Complex_Real;
1554 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001555 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001556 // Floating point conversions (C++ 4.8).
1557 SCS.Second = ICK_Floating_Conversion;
1558 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001559 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001560 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001561 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001562 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001563 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001564 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001565 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001566 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001567 SCS.Second = ICK_Block_Pointer_Conversion;
1568 } else if (AllowObjCWritebackConversion &&
1569 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1570 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001571 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1572 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001573 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001574 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001575 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001576 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001577 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001578 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001579 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001580 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001581 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001582 SCS.Second = SecondICK;
1583 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001584 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001585 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001586 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001587 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001588 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001589 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001590 // Treat a conversion that strips "noreturn" as an identity conversion.
1591 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001592 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1593 InOverloadResolution,
1594 SCS, CStyle)) {
1595 SCS.Second = ICK_TransparentUnionConversion;
1596 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1598 CStyle)) {
1599 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001600 // appropriately.
1601 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001602 } else {
1603 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001604 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001605 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001606 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001607
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001608 QualType CanonFrom;
1609 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001610 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001611 bool ObjCLifetimeConversion;
1612 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1613 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001614 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001615 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001616 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001617 CanonFrom = S.Context.getCanonicalType(FromType);
1618 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001619 } else {
1620 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001621 SCS.Third = ICK_Identity;
1622
Mike Stump1eb44332009-09-09 15:08:12 +00001623 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001624 // [...] Any difference in top-level cv-qualification is
1625 // subsumed by the initialization itself and does not constitute
1626 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001627 CanonFrom = S.Context.getCanonicalType(FromType);
1628 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001629 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001630 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001631 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001632 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1633 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001634 FromType = ToType;
1635 CanonFrom = CanonTo;
1636 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001637 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001638 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001639
1640 // If we have not converted the argument type to the parameter type,
1641 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001642 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001643 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001644
Douglas Gregor60d62c22008-10-31 16:23:19 +00001645 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001646}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001647
1648static bool
1649IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1650 QualType &ToType,
1651 bool InOverloadResolution,
1652 StandardConversionSequence &SCS,
1653 bool CStyle) {
1654
1655 const RecordType *UT = ToType->getAsUnionType();
1656 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1657 return false;
1658 // The field to initialize within the transparent union.
1659 RecordDecl *UD = UT->getDecl();
1660 // It's compatible if the expression matches any of the fields.
1661 for (RecordDecl::field_iterator it = UD->field_begin(),
1662 itend = UD->field_end();
1663 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001664 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1665 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001666 ToType = it->getType();
1667 return true;
1668 }
1669 }
1670 return false;
1671}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001672
1673/// IsIntegralPromotion - Determines whether the conversion from the
1674/// expression From (whose potentially-adjusted type is FromType) to
1675/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1676/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001677bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001678 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001679 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001680 if (!To) {
1681 return false;
1682 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001683
1684 // An rvalue of type char, signed char, unsigned char, short int, or
1685 // unsigned short int can be converted to an rvalue of type int if
1686 // int can represent all the values of the source type; otherwise,
1687 // the source rvalue can be converted to an rvalue of type unsigned
1688 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001689 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1690 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001691 if (// We can promote any signed, promotable integer type to an int
1692 (FromType->isSignedIntegerType() ||
1693 // We can promote any unsigned integer type whose size is
1694 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001695 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001696 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001697 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001698 }
1699
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001700 return To->getKind() == BuiltinType::UInt;
1701 }
1702
Richard Smithe7ff9192012-09-13 21:18:54 +00001703 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001704 // A prvalue of an unscoped enumeration type whose underlying type is not
1705 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1706 // following types that can represent all the values of the enumeration
1707 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1708 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001709 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001710 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001711 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712 // with lowest integer conversion rank (4.13) greater than the rank of long
1713 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001714 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001715 // C++11 [conv.prom]p4:
1716 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1717 // can be converted to a prvalue of its underlying type. Moreover, if
1718 // integral promotion can be applied to its underlying type, a prvalue of an
1719 // unscoped enumeration type whose underlying type is fixed can also be
1720 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001721 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1722 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1723 // provided for a scoped enumeration.
1724 if (FromEnumType->getDecl()->isScoped())
1725 return false;
1726
Richard Smithe7ff9192012-09-13 21:18:54 +00001727 // We can perform an integral promotion to the underlying type of the enum,
1728 // even if that's not the promoted type.
1729 if (FromEnumType->getDecl()->isFixed()) {
1730 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1731 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1732 IsIntegralPromotion(From, Underlying, ToType);
1733 }
1734
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001735 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001737 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001738 return Context.hasSameUnqualifiedType(ToType,
1739 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001740 }
John McCall842aef82009-12-09 09:09:27 +00001741
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001742 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001743 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1744 // to an rvalue a prvalue of the first of the following types that can
1745 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001746 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001747 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001748 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001750 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001751 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001752 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001753 // Determine whether the type we're converting from is signed or
1754 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001755 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001756 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001757
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001758 // The types we'll try to promote to, in the appropriate
1759 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001760 QualType PromoteTypes[6] = {
1761 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001762 Context.LongTy, Context.UnsignedLongTy ,
1763 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001764 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001765 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001766 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1767 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001768 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001769 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1770 // We found the type that we can promote to. If this is the
1771 // type we wanted, we have a promotion. Otherwise, no
1772 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001773 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001774 }
1775 }
1776 }
1777
1778 // An rvalue for an integral bit-field (9.6) can be converted to an
1779 // rvalue of type int if int can represent all the values of the
1780 // bit-field; otherwise, it can be converted to unsigned int if
1781 // unsigned int can represent all the values of the bit-field. If
1782 // the bit-field is larger yet, no integral promotion applies to
1783 // it. If the bit-field has an enumerated type, it is treated as any
1784 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001785 // FIXME: We should delay checking of bit-fields until we actually perform the
1786 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001787 using llvm::APSInt;
1788 if (From)
1789 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001790 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001791 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001792 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1793 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1794 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregor86f19402008-12-20 23:49:58 +00001796 // Are we promoting to an int from a bitfield that fits in an int?
1797 if (BitWidth < ToSize ||
1798 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1799 return To->getKind() == BuiltinType::Int;
1800 }
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregor86f19402008-12-20 23:49:58 +00001802 // Are we promoting to an unsigned int from an unsigned bitfield
1803 // that fits into an unsigned int?
1804 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1805 return To->getKind() == BuiltinType::UInt;
1806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Douglas Gregor86f19402008-12-20 23:49:58 +00001808 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001809 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001810 }
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812 // An rvalue of type bool can be converted to an rvalue of type int,
1813 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001814 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001816 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001817
1818 return false;
1819}
1820
1821/// IsFloatingPointPromotion - Determines whether the conversion from
1822/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1823/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001824bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001825 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1826 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001827 /// An rvalue of type float can be converted to an rvalue of type
1828 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001829 if (FromBuiltin->getKind() == BuiltinType::Float &&
1830 ToBuiltin->getKind() == BuiltinType::Double)
1831 return true;
1832
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001833 // C99 6.3.1.5p1:
1834 // When a float is promoted to double or long double, or a
1835 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001836 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001837 (FromBuiltin->getKind() == BuiltinType::Float ||
1838 FromBuiltin->getKind() == BuiltinType::Double) &&
1839 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1840 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001841
1842 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001843 if (!getLangOpts().NativeHalfType &&
1844 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001845 ToBuiltin->getKind() == BuiltinType::Float)
1846 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001847 }
1848
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001849 return false;
1850}
1851
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001852/// \brief Determine if a conversion is a complex promotion.
1853///
1854/// A complex promotion is defined as a complex -> complex conversion
1855/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001856/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001857bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001858 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001859 if (!FromComplex)
1860 return false;
1861
John McCall183700f2009-09-21 23:43:11 +00001862 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001863 if (!ToComplex)
1864 return false;
1865
1866 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001867 ToComplex->getElementType()) ||
1868 IsIntegralPromotion(0, FromComplex->getElementType(),
1869 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001870}
1871
Douglas Gregorcb7de522008-11-26 23:31:11 +00001872/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1873/// the pointer type FromPtr to a pointer to type ToPointee, with the
1874/// same type qualifiers as FromPtr has on its pointee type. ToType,
1875/// if non-empty, will be a pointer to ToType that may or may not have
1876/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001877///
Mike Stump1eb44332009-09-09 15:08:12 +00001878static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001879BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001880 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001881 ASTContext &Context,
1882 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001883 assert((FromPtr->getTypeClass() == Type::Pointer ||
1884 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1885 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001886
John McCallf85e1932011-06-15 23:02:42 +00001887 /// Conversions to 'id' subsume cv-qualifier conversions.
1888 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001889 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001890
1891 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001892 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001893 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001894 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001895
John McCallf85e1932011-06-15 23:02:42 +00001896 if (StripObjCLifetime)
1897 Quals.removeObjCLifetime();
1898
Mike Stump1eb44332009-09-09 15:08:12 +00001899 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001900 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001901 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001902 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001903 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001904
1905 // Build a pointer to ToPointee. It has the right qualifiers
1906 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001907 if (isa<ObjCObjectPointerType>(ToType))
1908 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001909 return Context.getPointerType(ToPointee);
1910 }
1911
1912 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001913 QualType QualifiedCanonToPointee
1914 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001915
Douglas Gregorda80f742010-12-01 21:43:58 +00001916 if (isa<ObjCObjectPointerType>(ToType))
1917 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1918 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001919}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920
Mike Stump1eb44332009-09-09 15:08:12 +00001921static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001922 bool InOverloadResolution,
1923 ASTContext &Context) {
1924 // Handle value-dependent integral null pointer constants correctly.
1925 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1926 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001927 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001928 return !InOverloadResolution;
1929
Douglas Gregorce940492009-09-25 04:25:58 +00001930 return Expr->isNullPointerConstant(Context,
1931 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1932 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001933}
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001935/// IsPointerConversion - Determines whether the conversion of the
1936/// expression From, which has the (possibly adjusted) type FromType,
1937/// can be converted to the type ToType via a pointer conversion (C++
1938/// 4.10). If so, returns true and places the converted type (that
1939/// might differ from ToType in its cv-qualifiers at some level) into
1940/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001941///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001942/// This routine also supports conversions to and from block pointers
1943/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1944/// pointers to interfaces. FIXME: Once we've determined the
1945/// appropriate overloading rules for Objective-C, we may want to
1946/// split the Objective-C checks into a different routine; however,
1947/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001948/// conversions, so for now they live here. IncompatibleObjC will be
1949/// set if the conversion is an allowed Objective-C conversion that
1950/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001951bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001952 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001953 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001954 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001955 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001956 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1957 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001958 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001959
Mike Stump1eb44332009-09-09 15:08:12 +00001960 // Conversion from a null pointer constant to any Objective-C pointer type.
1961 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001962 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001963 ConvertedType = ToType;
1964 return true;
1965 }
1966
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001967 // Blocks: Block pointers can be converted to void*.
1968 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001969 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001970 ConvertedType = ToType;
1971 return true;
1972 }
1973 // Blocks: A null pointer constant can be converted to a block
1974 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001975 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001976 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001977 ConvertedType = ToType;
1978 return true;
1979 }
1980
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001981 // If the left-hand-side is nullptr_t, the right side can be a null
1982 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001983 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001984 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001985 ConvertedType = ToType;
1986 return true;
1987 }
1988
Ted Kremenek6217b802009-07-29 21:53:49 +00001989 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001990 if (!ToTypePtr)
1991 return false;
1992
1993 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001994 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001995 ConvertedType = ToType;
1996 return true;
1997 }
Sebastian Redl07779722008-10-31 14:43:28 +00001998
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002000 // , including objective-c pointers.
2001 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002002 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002003 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002004 ConvertedType = BuildSimilarlyQualifiedPointerType(
2005 FromType->getAs<ObjCObjectPointerType>(),
2006 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002007 ToType, Context);
2008 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002009 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002010 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002011 if (!FromTypePtr)
2012 return false;
2013
2014 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002015
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002016 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002017 // pointer conversion, so don't do all of the work below.
2018 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2019 return false;
2020
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002021 // An rvalue of type "pointer to cv T," where T is an object type,
2022 // can be converted to an rvalue of type "pointer to cv void" (C++
2023 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002024 if (FromPointeeType->isIncompleteOrObjectType() &&
2025 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002026 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002027 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002028 ToType, Context,
2029 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002030 return true;
2031 }
2032
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002033 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002034 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002035 ToPointeeType->isVoidType()) {
2036 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2037 ToPointeeType,
2038 ToType, Context);
2039 return true;
2040 }
2041
Douglas Gregorf9201e02009-02-11 23:02:49 +00002042 // When we're overloading in C, we allow a special kind of pointer
2043 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002044 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002045 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002046 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002047 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002048 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002049 return true;
2050 }
2051
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002052 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002053 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002054 // An rvalue of type "pointer to cv D," where D is a class type,
2055 // can be converted to an rvalue of type "pointer to cv B," where
2056 // B is a base class (clause 10) of D. If B is an inaccessible
2057 // (clause 11) or ambiguous (10.2) base class of D, a program that
2058 // necessitates this conversion is ill-formed. The result of the
2059 // conversion is a pointer to the base class sub-object of the
2060 // derived class object. The null pointer value is converted to
2061 // the null pointer value of the destination type.
2062 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002063 // Note that we do not check for ambiguity or inaccessibility
2064 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002065 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002066 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002067 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002068 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002069 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002070 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002071 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002072 ToType, Context);
2073 return true;
2074 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002075
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002076 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2077 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2078 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2079 ToPointeeType,
2080 ToType, Context);
2081 return true;
2082 }
2083
Douglas Gregorc7887512008-12-19 19:13:09 +00002084 return false;
2085}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002086
2087/// \brief Adopt the given qualifiers for the given type.
2088static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2089 Qualifiers TQs = T.getQualifiers();
2090
2091 // Check whether qualifiers already match.
2092 if (TQs == Qs)
2093 return T;
2094
2095 if (Qs.compatiblyIncludes(TQs))
2096 return Context.getQualifiedType(T, Qs);
2097
2098 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2099}
Douglas Gregorc7887512008-12-19 19:13:09 +00002100
2101/// isObjCPointerConversion - Determines whether this is an
2102/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2103/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002104bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002105 QualType& ConvertedType,
2106 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002107 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002108 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002109
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002110 // The set of qualifiers on the type we're converting from.
2111 Qualifiers FromQualifiers = FromType.getQualifiers();
2112
Steve Naroff14108da2009-07-10 23:34:53 +00002113 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002114 const ObjCObjectPointerType* ToObjCPtr =
2115 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002116 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002117 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002118
Steve Naroff14108da2009-07-10 23:34:53 +00002119 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002120 // If the pointee types are the same (ignoring qualifications),
2121 // then this is not a pointer conversion.
2122 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2123 FromObjCPtr->getPointeeType()))
2124 return false;
2125
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002126 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002127 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002128 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002129 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002130 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002131 return true;
2132 }
2133 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002134 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002135 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002136 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002137 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002138 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002139 return true;
2140 }
2141 // Objective C++: We're able to convert from a pointer to an
2142 // interface to a pointer to a different interface.
2143 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002144 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2145 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002146 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002147 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2148 FromObjCPtr->getPointeeType()))
2149 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002150 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002151 ToObjCPtr->getPointeeType(),
2152 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002153 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002154 return true;
2155 }
2156
2157 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2158 // Okay: this is some kind of implicit downcast of Objective-C
2159 // interfaces, which is permitted. However, we're going to
2160 // complain about it.
2161 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002162 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002163 ToObjCPtr->getPointeeType(),
2164 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002165 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002166 return true;
2167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168 }
Steve Naroff14108da2009-07-10 23:34:53 +00002169 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002170 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002171 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002172 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002173 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002174 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002175 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002176 // to a block pointer type.
2177 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002178 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002179 return true;
2180 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002181 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002184 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002186 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002188 return true;
2189 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002190 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002191 return false;
2192
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002193 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002194 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002195 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002196 else if (const BlockPointerType *FromBlockPtr =
2197 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002198 FromPointeeType = FromBlockPtr->getPointeeType();
2199 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002200 return false;
2201
Douglas Gregorc7887512008-12-19 19:13:09 +00002202 // If we have pointers to pointers, recursively check whether this
2203 // is an Objective-C conversion.
2204 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2205 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2206 IncompatibleObjC)) {
2207 // We always complain about this conversion.
2208 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002209 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002211 return true;
2212 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002213 // Allow conversion of pointee being objective-c pointer to another one;
2214 // as in I* to id.
2215 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2216 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2217 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2218 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002219
Douglas Gregorda80f742010-12-01 21:43:58 +00002220 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002221 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002222 return true;
2223 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002224
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002225 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002226 // differences in the argument and result types are in Objective-C
2227 // pointer conversions. If so, we permit the conversion (but
2228 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002229 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002230 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002231 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002232 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002233 if (FromFunctionType && ToFunctionType) {
2234 // If the function types are exactly the same, this isn't an
2235 // Objective-C pointer conversion.
2236 if (Context.getCanonicalType(FromPointeeType)
2237 == Context.getCanonicalType(ToPointeeType))
2238 return false;
2239
2240 // Perform the quick checks that will tell us whether these
2241 // function types are obviously different.
2242 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2243 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2244 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2245 return false;
2246
2247 bool HasObjCConversion = false;
2248 if (Context.getCanonicalType(FromFunctionType->getResultType())
2249 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2250 // Okay, the types match exactly. Nothing to do.
2251 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2252 ToFunctionType->getResultType(),
2253 ConvertedType, IncompatibleObjC)) {
2254 // Okay, we have an Objective-C pointer conversion.
2255 HasObjCConversion = true;
2256 } else {
2257 // Function types are too different. Abort.
2258 return false;
2259 }
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Douglas Gregorc7887512008-12-19 19:13:09 +00002261 // Check argument types.
2262 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2263 ArgIdx != NumArgs; ++ArgIdx) {
2264 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2265 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2266 if (Context.getCanonicalType(FromArgType)
2267 == Context.getCanonicalType(ToArgType)) {
2268 // Okay, the types match exactly. Nothing to do.
2269 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2270 ConvertedType, IncompatibleObjC)) {
2271 // Okay, we have an Objective-C pointer conversion.
2272 HasObjCConversion = true;
2273 } else {
2274 // Argument types are too different. Abort.
2275 return false;
2276 }
2277 }
2278
2279 if (HasObjCConversion) {
2280 // We had an Objective-C conversion. Allow this pointer
2281 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002282 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002283 IncompatibleObjC = true;
2284 return true;
2285 }
2286 }
2287
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002288 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002289}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002290
John McCallf85e1932011-06-15 23:02:42 +00002291/// \brief Determine whether this is an Objective-C writeback conversion,
2292/// used for parameter passing when performing automatic reference counting.
2293///
2294/// \param FromType The type we're converting form.
2295///
2296/// \param ToType The type we're converting to.
2297///
2298/// \param ConvertedType The type that will be produced after applying
2299/// this conversion.
2300bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2301 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002302 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002303 Context.hasSameUnqualifiedType(FromType, ToType))
2304 return false;
2305
2306 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2307 QualType ToPointee;
2308 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2309 ToPointee = ToPointer->getPointeeType();
2310 else
2311 return false;
2312
2313 Qualifiers ToQuals = ToPointee.getQualifiers();
2314 if (!ToPointee->isObjCLifetimeType() ||
2315 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002316 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002317 return false;
2318
2319 // Argument must be a pointer to __strong to __weak.
2320 QualType FromPointee;
2321 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2322 FromPointee = FromPointer->getPointeeType();
2323 else
2324 return false;
2325
2326 Qualifiers FromQuals = FromPointee.getQualifiers();
2327 if (!FromPointee->isObjCLifetimeType() ||
2328 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2329 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2330 return false;
2331
2332 // Make sure that we have compatible qualifiers.
2333 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2334 if (!ToQuals.compatiblyIncludes(FromQuals))
2335 return false;
2336
2337 // Remove qualifiers from the pointee type we're converting from; they
2338 // aren't used in the compatibility check belong, and we'll be adding back
2339 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2340 FromPointee = FromPointee.getUnqualifiedType();
2341
2342 // The unqualified form of the pointee types must be compatible.
2343 ToPointee = ToPointee.getUnqualifiedType();
2344 bool IncompatibleObjC;
2345 if (Context.typesAreCompatible(FromPointee, ToPointee))
2346 FromPointee = ToPointee;
2347 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2348 IncompatibleObjC))
2349 return false;
2350
2351 /// \brief Construct the type we're converting to, which is a pointer to
2352 /// __autoreleasing pointee.
2353 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2354 ConvertedType = Context.getPointerType(FromPointee);
2355 return true;
2356}
2357
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002358bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2359 QualType& ConvertedType) {
2360 QualType ToPointeeType;
2361 if (const BlockPointerType *ToBlockPtr =
2362 ToType->getAs<BlockPointerType>())
2363 ToPointeeType = ToBlockPtr->getPointeeType();
2364 else
2365 return false;
2366
2367 QualType FromPointeeType;
2368 if (const BlockPointerType *FromBlockPtr =
2369 FromType->getAs<BlockPointerType>())
2370 FromPointeeType = FromBlockPtr->getPointeeType();
2371 else
2372 return false;
2373 // We have pointer to blocks, check whether the only
2374 // differences in the argument and result types are in Objective-C
2375 // pointer conversions. If so, we permit the conversion.
2376
2377 const FunctionProtoType *FromFunctionType
2378 = FromPointeeType->getAs<FunctionProtoType>();
2379 const FunctionProtoType *ToFunctionType
2380 = ToPointeeType->getAs<FunctionProtoType>();
2381
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002382 if (!FromFunctionType || !ToFunctionType)
2383 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002384
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002385 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002386 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002387
2388 // Perform the quick checks that will tell us whether these
2389 // function types are obviously different.
2390 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2391 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2392 return false;
2393
2394 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2395 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2396 if (FromEInfo != ToEInfo)
2397 return false;
2398
2399 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002400 if (Context.hasSameType(FromFunctionType->getResultType(),
2401 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002402 // Okay, the types match exactly. Nothing to do.
2403 } else {
2404 QualType RHS = FromFunctionType->getResultType();
2405 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002406 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002407 !RHS.hasQualifiers() && LHS.hasQualifiers())
2408 LHS = LHS.getUnqualifiedType();
2409
2410 if (Context.hasSameType(RHS,LHS)) {
2411 // OK exact match.
2412 } else if (isObjCPointerConversion(RHS, LHS,
2413 ConvertedType, IncompatibleObjC)) {
2414 if (IncompatibleObjC)
2415 return false;
2416 // Okay, we have an Objective-C pointer conversion.
2417 }
2418 else
2419 return false;
2420 }
2421
2422 // Check argument types.
2423 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2424 ArgIdx != NumArgs; ++ArgIdx) {
2425 IncompatibleObjC = false;
2426 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2427 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2428 if (Context.hasSameType(FromArgType, ToArgType)) {
2429 // Okay, the types match exactly. Nothing to do.
2430 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2431 ConvertedType, IncompatibleObjC)) {
2432 if (IncompatibleObjC)
2433 return false;
2434 // Okay, we have an Objective-C pointer conversion.
2435 } else
2436 // Argument types are too different. Abort.
2437 return false;
2438 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002439 if (LangOpts.ObjCAutoRefCount &&
2440 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2441 ToFunctionType))
2442 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002443
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002444 ConvertedType = ToType;
2445 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002446}
2447
Richard Trieu6efd4c52011-11-23 22:32:32 +00002448enum {
2449 ft_default,
2450 ft_different_class,
2451 ft_parameter_arity,
2452 ft_parameter_mismatch,
2453 ft_return_type,
2454 ft_qualifer_mismatch
2455};
2456
2457/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2458/// function types. Catches different number of parameter, mismatch in
2459/// parameter types, and different return types.
2460void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2461 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002462 // If either type is not valid, include no extra info.
2463 if (FromType.isNull() || ToType.isNull()) {
2464 PDiag << ft_default;
2465 return;
2466 }
2467
Richard Trieu6efd4c52011-11-23 22:32:32 +00002468 // Get the function type from the pointers.
2469 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2470 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2471 *ToMember = ToType->getAs<MemberPointerType>();
2472 if (FromMember->getClass() != ToMember->getClass()) {
2473 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2474 << QualType(FromMember->getClass(), 0);
2475 return;
2476 }
2477 FromType = FromMember->getPointeeType();
2478 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002479 }
2480
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002481 if (FromType->isPointerType())
2482 FromType = FromType->getPointeeType();
2483 if (ToType->isPointerType())
2484 ToType = ToType->getPointeeType();
2485
2486 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002487 FromType = FromType.getNonReferenceType();
2488 ToType = ToType.getNonReferenceType();
2489
Richard Trieu6efd4c52011-11-23 22:32:32 +00002490 // Don't print extra info for non-specialized template functions.
2491 if (FromType->isInstantiationDependentType() &&
2492 !FromType->getAs<TemplateSpecializationType>()) {
2493 PDiag << ft_default;
2494 return;
2495 }
2496
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002497 // No extra info for same types.
2498 if (Context.hasSameType(FromType, ToType)) {
2499 PDiag << ft_default;
2500 return;
2501 }
2502
Richard Trieu6efd4c52011-11-23 22:32:32 +00002503 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2504 *ToFunction = ToType->getAs<FunctionProtoType>();
2505
2506 // Both types need to be function types.
2507 if (!FromFunction || !ToFunction) {
2508 PDiag << ft_default;
2509 return;
2510 }
2511
2512 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2513 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2514 << FromFunction->getNumArgs();
2515 return;
2516 }
2517
2518 // Handle different parameter types.
2519 unsigned ArgPos;
2520 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2521 PDiag << ft_parameter_mismatch << ArgPos + 1
2522 << ToFunction->getArgType(ArgPos)
2523 << FromFunction->getArgType(ArgPos);
2524 return;
2525 }
2526
2527 // Handle different return type.
2528 if (!Context.hasSameType(FromFunction->getResultType(),
2529 ToFunction->getResultType())) {
2530 PDiag << ft_return_type << ToFunction->getResultType()
2531 << FromFunction->getResultType();
2532 return;
2533 }
2534
2535 unsigned FromQuals = FromFunction->getTypeQuals(),
2536 ToQuals = ToFunction->getTypeQuals();
2537 if (FromQuals != ToQuals) {
2538 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2539 return;
2540 }
2541
2542 // Unable to find a difference, so add no extra info.
2543 PDiag << ft_default;
2544}
2545
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002546/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002547/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002548/// they have same number of arguments. This routine assumes that Objective-C
2549/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002550/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002551/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002552bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002553 const FunctionProtoType *NewType,
2554 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002555 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002556 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2557 N = NewType->arg_type_begin(),
2558 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2559 if (!Context.hasSameType(*O, *N)) {
2560 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2561 return false;
2562 }
2563 }
2564 return true;
2565 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002566
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002567 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2568 N = NewType->arg_type_begin(),
2569 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2570 QualType ToType = (*O);
2571 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002572 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002573 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2574 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002575 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2576 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2577 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2578 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002579 continue;
2580 }
John McCallc12c5bb2010-05-15 11:32:37 +00002581 else if (const ObjCObjectPointerType *PTTo =
2582 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002584 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002585 if (Context.hasSameUnqualifiedType(
2586 PTTo->getObjectType()->getBaseType(),
2587 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002588 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002589 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002590 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002591 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002592 }
2593 }
2594 return true;
2595}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002596
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002597/// CheckPointerConversion - Check the pointer conversion from the
2598/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002599/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002600/// conversions for which IsPointerConversion has already returned
2601/// true. It returns true and produces a diagnostic if there was an
2602/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002603bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002604 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002605 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002606 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002607 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002608 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002609
John McCalldaa8e4e2010-11-15 09:13:47 +00002610 Kind = CK_BitCast;
2611
David Blaikie50800fc2012-08-08 17:33:31 +00002612 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2613 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2614 Expr::NPCK_ZeroExpression) {
2615 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2616 DiagRuntimeBehavior(From->getExprLoc(), From,
2617 PDiag(diag::warn_impcast_bool_to_null_pointer)
2618 << ToType << From->getSourceRange());
2619 else if (!isUnevaluatedContext())
2620 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2621 << ToType << From->getSourceRange();
2622 }
John McCall1d9b3b22011-09-09 05:25:32 +00002623 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2624 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002625 QualType FromPointeeType = FromPtrType->getPointeeType(),
2626 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002627
Douglas Gregor5fccd362010-03-03 23:55:11 +00002628 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2629 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002630 // We must have a derived-to-base conversion. Check an
2631 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002632 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2633 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002634 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002635 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002636 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002637
Anders Carlsson61faec12009-09-12 04:46:44 +00002638 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002639 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002640 }
2641 }
John McCall1d9b3b22011-09-09 05:25:32 +00002642 } else if (const ObjCObjectPointerType *ToPtrType =
2643 ToType->getAs<ObjCObjectPointerType>()) {
2644 if (const ObjCObjectPointerType *FromPtrType =
2645 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002646 // Objective-C++ conversions are always okay.
2647 // FIXME: We should have a different class of conversions for the
2648 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002649 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002650 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002651 } else if (FromType->isBlockPointerType()) {
2652 Kind = CK_BlockPointerToObjCPointerCast;
2653 } else {
2654 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002655 }
John McCall1d9b3b22011-09-09 05:25:32 +00002656 } else if (ToType->isBlockPointerType()) {
2657 if (!FromType->isBlockPointerType())
2658 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002659 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002660
2661 // We shouldn't fall into this case unless it's valid for other
2662 // reasons.
2663 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2664 Kind = CK_NullToPointer;
2665
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002666 return false;
2667}
2668
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002669/// IsMemberPointerConversion - Determines whether the conversion of the
2670/// expression From, which has the (possibly adjusted) type FromType, can be
2671/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2672/// If so, returns true and places the converted type (that might differ from
2673/// ToType in its cv-qualifiers at some level) into ConvertedType.
2674bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002675 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002676 bool InOverloadResolution,
2677 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002678 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002679 if (!ToTypePtr)
2680 return false;
2681
2682 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002683 if (From->isNullPointerConstant(Context,
2684 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2685 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002686 ConvertedType = ToType;
2687 return true;
2688 }
2689
2690 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002691 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002692 if (!FromTypePtr)
2693 return false;
2694
2695 // A pointer to member of B can be converted to a pointer to member of D,
2696 // where D is derived from B (C++ 4.11p2).
2697 QualType FromClass(FromTypePtr->getClass(), 0);
2698 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002699
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002700 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002701 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002702 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002703 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2704 ToClass.getTypePtr());
2705 return true;
2706 }
2707
2708 return false;
2709}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002710
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002711/// CheckMemberPointerConversion - Check the member pointer conversion from the
2712/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002713/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002714/// for which IsMemberPointerConversion has already returned true. It returns
2715/// true and produces a diagnostic if there was an error, or returns false
2716/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002717bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002718 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002719 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002720 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002721 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002722 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002723 if (!FromPtrType) {
2724 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002725 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002726 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002727 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002728 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002729 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002730 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002731
Ted Kremenek6217b802009-07-29 21:53:49 +00002732 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002733 assert(ToPtrType && "No member pointer cast has a target type "
2734 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002735
Sebastian Redl21593ac2009-01-28 18:33:18 +00002736 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2737 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002738
Sebastian Redl21593ac2009-01-28 18:33:18 +00002739 // FIXME: What about dependent types?
2740 assert(FromClass->isRecordType() && "Pointer into non-class.");
2741 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002742
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002743 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002744 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002745 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2746 assert(DerivationOkay &&
2747 "Should not have been called if derivation isn't OK.");
2748 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002749
Sebastian Redl21593ac2009-01-28 18:33:18 +00002750 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2751 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002752 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2753 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2754 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2755 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002756 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002757
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002758 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002759 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2760 << FromClass << ToClass << QualType(VBase, 0)
2761 << From->getSourceRange();
2762 return true;
2763 }
2764
John McCall6b2accb2010-02-10 09:31:12 +00002765 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002766 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2767 Paths.front(),
2768 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002769
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002770 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002771 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002772 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002773 return false;
2774}
2775
Douglas Gregor98cd5992008-10-21 23:43:52 +00002776/// IsQualificationConversion - Determines whether the conversion from
2777/// an rvalue of type FromType to ToType is a qualification conversion
2778/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002779///
2780/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2781/// when the qualification conversion involves a change in the Objective-C
2782/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002783bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002784Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002785 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002786 FromType = Context.getCanonicalType(FromType);
2787 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002788 ObjCLifetimeConversion = false;
2789
Douglas Gregor98cd5992008-10-21 23:43:52 +00002790 // If FromType and ToType are the same type, this is not a
2791 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002792 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002793 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002794
Douglas Gregor98cd5992008-10-21 23:43:52 +00002795 // (C++ 4.4p4):
2796 // A conversion can add cv-qualifiers at levels other than the first
2797 // in multi-level pointers, subject to the following rules: [...]
2798 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002799 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002800 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002801 // Within each iteration of the loop, we check the qualifiers to
2802 // determine if this still looks like a qualification
2803 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002804 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002805 // until there are no more pointers or pointers-to-members left to
2806 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002807 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002808
Douglas Gregor621c92a2011-04-25 18:40:17 +00002809 Qualifiers FromQuals = FromType.getQualifiers();
2810 Qualifiers ToQuals = ToType.getQualifiers();
2811
John McCallf85e1932011-06-15 23:02:42 +00002812 // Objective-C ARC:
2813 // Check Objective-C lifetime conversions.
2814 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2815 UnwrappedAnyPointer) {
2816 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2817 ObjCLifetimeConversion = true;
2818 FromQuals.removeObjCLifetime();
2819 ToQuals.removeObjCLifetime();
2820 } else {
2821 // Qualification conversions cannot cast between different
2822 // Objective-C lifetime qualifiers.
2823 return false;
2824 }
2825 }
2826
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002827 // Allow addition/removal of GC attributes but not changing GC attributes.
2828 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2829 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2830 FromQuals.removeObjCGCAttr();
2831 ToQuals.removeObjCGCAttr();
2832 }
2833
Douglas Gregor98cd5992008-10-21 23:43:52 +00002834 // -- for every j > 0, if const is in cv 1,j then const is in cv
2835 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002836 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002837 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Douglas Gregor98cd5992008-10-21 23:43:52 +00002839 // -- if the cv 1,j and cv 2,j are different, then const is in
2840 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002841 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002842 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002843 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Douglas Gregor98cd5992008-10-21 23:43:52 +00002845 // Keep track of whether all prior cv-qualifiers in the "to" type
2846 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002847 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002848 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002849 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002850
2851 // We are left with FromType and ToType being the pointee types
2852 // after unwrapping the original FromType and ToType the same number
2853 // of types. If we unwrapped any pointers, and if FromType and
2854 // ToType have the same unqualified type (since we checked
2855 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002856 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002857}
2858
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002859/// \brief - Determine whether this is a conversion from a scalar type to an
2860/// atomic type.
2861///
2862/// If successful, updates \c SCS's second and third steps in the conversion
2863/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002864static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2865 bool InOverloadResolution,
2866 StandardConversionSequence &SCS,
2867 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002868 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2869 if (!ToAtomic)
2870 return false;
2871
2872 StandardConversionSequence InnerSCS;
2873 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2874 InOverloadResolution, InnerSCS,
2875 CStyle, /*AllowObjCWritebackConversion=*/false))
2876 return false;
2877
2878 SCS.Second = InnerSCS.Second;
2879 SCS.setToType(1, InnerSCS.getToType(1));
2880 SCS.Third = InnerSCS.Third;
2881 SCS.QualificationIncludesObjCLifetime
2882 = InnerSCS.QualificationIncludesObjCLifetime;
2883 SCS.setToType(2, InnerSCS.getToType(2));
2884 return true;
2885}
2886
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002887static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2888 CXXConstructorDecl *Constructor,
2889 QualType Type) {
2890 const FunctionProtoType *CtorType =
2891 Constructor->getType()->getAs<FunctionProtoType>();
2892 if (CtorType->getNumArgs() > 0) {
2893 QualType FirstArg = CtorType->getArgType(0);
2894 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2895 return true;
2896 }
2897 return false;
2898}
2899
Sebastian Redl56a04282012-02-11 23:51:08 +00002900static OverloadingResult
2901IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2902 CXXRecordDecl *To,
2903 UserDefinedConversionSequence &User,
2904 OverloadCandidateSet &CandidateSet,
2905 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002906 DeclContext::lookup_result R = S.LookupConstructors(To);
2907 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002908 Con != ConEnd; ++Con) {
2909 NamedDecl *D = *Con;
2910 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2911
2912 // Find the constructor (which may be a template).
2913 CXXConstructorDecl *Constructor = 0;
2914 FunctionTemplateDecl *ConstructorTmpl
2915 = dyn_cast<FunctionTemplateDecl>(D);
2916 if (ConstructorTmpl)
2917 Constructor
2918 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2919 else
2920 Constructor = cast<CXXConstructorDecl>(D);
2921
2922 bool Usable = !Constructor->isInvalidDecl() &&
2923 S.isInitListConstructor(Constructor) &&
2924 (AllowExplicit || !Constructor->isExplicit());
2925 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002926 // If the first argument is (a reference to) the target type,
2927 // suppress conversions.
2928 bool SuppressUserConversions =
2929 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002930 if (ConstructorTmpl)
2931 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2932 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002933 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002934 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002935 else
2936 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002937 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002938 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002939 }
2940 }
2941
2942 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2943
2944 OverloadCandidateSet::iterator Best;
2945 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2946 case OR_Success: {
2947 // Record the standard conversion we used and the conversion function.
2948 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002949 QualType ThisType = Constructor->getThisType(S.Context);
2950 // Initializer lists don't have conversions as such.
2951 User.Before.setAsIdentityConversion();
2952 User.HadMultipleCandidates = HadMultipleCandidates;
2953 User.ConversionFunction = Constructor;
2954 User.FoundConversionFunction = Best->FoundDecl;
2955 User.After.setAsIdentityConversion();
2956 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2957 User.After.setAllToTypes(ToType);
2958 return OR_Success;
2959 }
2960
2961 case OR_No_Viable_Function:
2962 return OR_No_Viable_Function;
2963 case OR_Deleted:
2964 return OR_Deleted;
2965 case OR_Ambiguous:
2966 return OR_Ambiguous;
2967 }
2968
2969 llvm_unreachable("Invalid OverloadResult!");
2970}
2971
Douglas Gregor734d9862009-01-30 23:27:23 +00002972/// Determines whether there is a user-defined conversion sequence
2973/// (C++ [over.ics.user]) that converts expression From to the type
2974/// ToType. If such a conversion exists, User will contain the
2975/// user-defined conversion sequence that performs such a conversion
2976/// and this routine will return true. Otherwise, this routine returns
2977/// false and User is unspecified.
2978///
Douglas Gregor734d9862009-01-30 23:27:23 +00002979/// \param AllowExplicit true if the conversion should consider C++0x
2980/// "explicit" conversion functions as well as non-explicit conversion
2981/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002982static OverloadingResult
2983IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002984 UserDefinedConversionSequence &User,
2985 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002986 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002987 // Whether we will only visit constructors.
2988 bool ConstructorsOnly = false;
2989
2990 // If the type we are conversion to is a class type, enumerate its
2991 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002992 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002993 // C++ [over.match.ctor]p1:
2994 // When objects of class type are direct-initialized (8.5), or
2995 // copy-initialized from an expression of the same or a
2996 // derived class type (8.5), overload resolution selects the
2997 // constructor. [...] For copy-initialization, the candidate
2998 // functions are all the converting constructors (12.3.1) of
2999 // that class. The argument list is the expression-list within
3000 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003001 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003002 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003003 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003004 ConstructorsOnly = true;
3005
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003006 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003007 // RequireCompleteType may have returned true due to some invalid decl
3008 // during template instantiation, but ToType may be complete enough now
3009 // to try to recover.
3010 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003011 // We're not going to find any constructors.
3012 } else if (CXXRecordDecl *ToRecordDecl
3013 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003014
3015 Expr **Args = &From;
3016 unsigned NumArgs = 1;
3017 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003018 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003019 // But first, see if there is an init-list-contructor that will work.
3020 OverloadingResult Result = IsInitializerListConstructorConversion(
3021 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3022 if (Result != OR_No_Viable_Function)
3023 return Result;
3024 // Never mind.
3025 CandidateSet.clear();
3026
3027 // If we're list-initializing, we pass the individual elements as
3028 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003029 Args = InitList->getInits();
3030 NumArgs = InitList->getNumInits();
3031 ListInitializing = true;
3032 }
3033
David Blaikie3bc93e32012-12-19 00:45:41 +00003034 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3035 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003036 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003037 NamedDecl *D = *Con;
3038 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3039
Douglas Gregordec06662009-08-21 18:42:58 +00003040 // Find the constructor (which may be a template).
3041 CXXConstructorDecl *Constructor = 0;
3042 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003043 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003044 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003045 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003046 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3047 else
John McCall9aa472c2010-03-19 07:35:19 +00003048 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003050 bool Usable = !Constructor->isInvalidDecl();
3051 if (ListInitializing)
3052 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3053 else
3054 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3055 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003056 bool SuppressUserConversions = !ConstructorsOnly;
3057 if (SuppressUserConversions && ListInitializing) {
3058 SuppressUserConversions = false;
3059 if (NumArgs == 1) {
3060 // If the first argument is (a reference to) the target type,
3061 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003062 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3063 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003064 }
3065 }
Douglas Gregordec06662009-08-21 18:42:58 +00003066 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003067 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3068 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003069 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003070 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003071 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003072 // Allow one user-defined conversion when user specifies a
3073 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003074 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003075 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003076 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003077 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003078 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003079 }
3080 }
3081
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003082 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003083 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003084 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003085 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003086 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003087 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003088 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003089 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3090 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003091 std::pair<CXXRecordDecl::conversion_iterator,
3092 CXXRecordDecl::conversion_iterator>
3093 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3094 for (CXXRecordDecl::conversion_iterator
3095 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003096 DeclAccessPair FoundDecl = I.getPair();
3097 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003098 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3099 if (isa<UsingShadowDecl>(D))
3100 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3101
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003102 CXXConversionDecl *Conv;
3103 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003104 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3105 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003106 else
John McCall32daa422010-03-31 01:36:47 +00003107 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003108
3109 if (AllowExplicit || !Conv->isExplicit()) {
3110 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003111 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3112 ActingContext, From, ToType,
3113 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003114 else
John McCall120d63c2010-08-24 20:38:10 +00003115 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3116 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003117 }
3118 }
3119 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003120 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003121
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003122 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3123
Douglas Gregor60d62c22008-10-31 16:23:19 +00003124 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003125 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003126 case OR_Success:
3127 // Record the standard conversion we used and the conversion function.
3128 if (CXXConstructorDecl *Constructor
3129 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3130 // C++ [over.ics.user]p1:
3131 // If the user-defined conversion is specified by a
3132 // constructor (12.3.1), the initial standard conversion
3133 // sequence converts the source type to the type required by
3134 // the argument of the constructor.
3135 //
3136 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003137 if (isa<InitListExpr>(From)) {
3138 // Initializer lists don't have conversions as such.
3139 User.Before.setAsIdentityConversion();
3140 } else {
3141 if (Best->Conversions[0].isEllipsis())
3142 User.EllipsisConversion = true;
3143 else {
3144 User.Before = Best->Conversions[0].Standard;
3145 User.EllipsisConversion = false;
3146 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003147 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003148 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003149 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003150 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003151 User.After.setAsIdentityConversion();
3152 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3153 User.After.setAllToTypes(ToType);
3154 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003155 }
3156 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003157 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3158 // C++ [over.ics.user]p1:
3159 //
3160 // [...] If the user-defined conversion is specified by a
3161 // conversion function (12.3.2), the initial standard
3162 // conversion sequence converts the source type to the
3163 // implicit object parameter of the conversion function.
3164 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003165 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003166 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003167 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003168 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
John McCall120d63c2010-08-24 20:38:10 +00003170 // C++ [over.ics.user]p2:
3171 // The second standard conversion sequence converts the
3172 // result of the user-defined conversion to the target type
3173 // for the sequence. Since an implicit conversion sequence
3174 // is an initialization, the special rules for
3175 // initialization by user-defined conversion apply when
3176 // selecting the best user-defined conversion for a
3177 // user-defined conversion sequence (see 13.3.3 and
3178 // 13.3.3.1).
3179 User.After = Best->FinalConversion;
3180 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003181 }
David Blaikie7530c032012-01-17 06:56:22 +00003182 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003183
John McCall120d63c2010-08-24 20:38:10 +00003184 case OR_No_Viable_Function:
3185 return OR_No_Viable_Function;
3186 case OR_Deleted:
3187 // No conversion here! We're done.
3188 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003189
John McCall120d63c2010-08-24 20:38:10 +00003190 case OR_Ambiguous:
3191 return OR_Ambiguous;
3192 }
3193
David Blaikie7530c032012-01-17 06:56:22 +00003194 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003195}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003196
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003197bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003198Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003199 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003200 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003202 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003203 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003204 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003205 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003206 diag::err_typecheck_ambiguous_condition)
3207 << From->getType() << ToType << From->getSourceRange();
3208 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003209 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003210 diag::err_typecheck_nonviable_condition)
3211 << From->getType() << ToType << From->getSourceRange();
3212 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003213 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003214 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003216}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003217
Douglas Gregorb734e242012-02-22 17:32:19 +00003218/// \brief Compare the user-defined conversion functions or constructors
3219/// of two user-defined conversion sequences to determine whether any ordering
3220/// is possible.
3221static ImplicitConversionSequence::CompareKind
3222compareConversionFunctions(Sema &S,
3223 FunctionDecl *Function1,
3224 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003225 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003226 return ImplicitConversionSequence::Indistinguishable;
3227
3228 // Objective-C++:
3229 // If both conversion functions are implicitly-declared conversions from
3230 // a lambda closure type to a function pointer and a block pointer,
3231 // respectively, always prefer the conversion to a function pointer,
3232 // because the function pointer is more lightweight and is more likely
3233 // to keep code working.
3234 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3235 if (!Conv1)
3236 return ImplicitConversionSequence::Indistinguishable;
3237
3238 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3239 if (!Conv2)
3240 return ImplicitConversionSequence::Indistinguishable;
3241
3242 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3243 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3244 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3245 if (Block1 != Block2)
3246 return Block1? ImplicitConversionSequence::Worse
3247 : ImplicitConversionSequence::Better;
3248 }
3249
3250 return ImplicitConversionSequence::Indistinguishable;
3251}
3252
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003253/// CompareImplicitConversionSequences - Compare two implicit
3254/// conversion sequences to determine whether one is better than the
3255/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003256static ImplicitConversionSequence::CompareKind
3257CompareImplicitConversionSequences(Sema &S,
3258 const ImplicitConversionSequence& ICS1,
3259 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003260{
3261 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3262 // conversion sequences (as defined in 13.3.3.1)
3263 // -- a standard conversion sequence (13.3.3.1.1) is a better
3264 // conversion sequence than a user-defined conversion sequence or
3265 // an ellipsis conversion sequence, and
3266 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3267 // conversion sequence than an ellipsis conversion sequence
3268 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003269 //
John McCall1d318332010-01-12 00:44:57 +00003270 // C++0x [over.best.ics]p10:
3271 // For the purpose of ranking implicit conversion sequences as
3272 // described in 13.3.3.2, the ambiguous conversion sequence is
3273 // treated as a user-defined sequence that is indistinguishable
3274 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003275 if (ICS1.getKindRank() < ICS2.getKindRank())
3276 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003277 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003278 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003279
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003280 // The following checks require both conversion sequences to be of
3281 // the same kind.
3282 if (ICS1.getKind() != ICS2.getKind())
3283 return ImplicitConversionSequence::Indistinguishable;
3284
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003285 ImplicitConversionSequence::CompareKind Result =
3286 ImplicitConversionSequence::Indistinguishable;
3287
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003288 // Two implicit conversion sequences of the same form are
3289 // indistinguishable conversion sequences unless one of the
3290 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003291 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003292 Result = CompareStandardConversionSequences(S,
3293 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003294 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003295 // User-defined conversion sequence U1 is a better conversion
3296 // sequence than another user-defined conversion sequence U2 if
3297 // they contain the same user-defined conversion function or
3298 // constructor and if the second standard conversion sequence of
3299 // U1 is better than the second standard conversion sequence of
3300 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003301 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003302 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003303 Result = CompareStandardConversionSequences(S,
3304 ICS1.UserDefined.After,
3305 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003306 else
3307 Result = compareConversionFunctions(S,
3308 ICS1.UserDefined.ConversionFunction,
3309 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003310 }
3311
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003312 // List-initialization sequence L1 is a better conversion sequence than
3313 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3314 // for some X and L2 does not.
3315 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003316 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003317 ICS1.isListInitializationSequence() &&
3318 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003319 if (ICS1.isStdInitializerListElement() &&
3320 !ICS2.isStdInitializerListElement())
3321 return ImplicitConversionSequence::Better;
3322 if (!ICS1.isStdInitializerListElement() &&
3323 ICS2.isStdInitializerListElement())
3324 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003325 }
3326
3327 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003328}
3329
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003330static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3331 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3332 Qualifiers Quals;
3333 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003334 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003335 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003336
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003337 return Context.hasSameUnqualifiedType(T1, T2);
3338}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339
Douglas Gregorad323a82010-01-27 03:51:04 +00003340// Per 13.3.3.2p3, compare the given standard conversion sequences to
3341// determine if one is a proper subset of the other.
3342static ImplicitConversionSequence::CompareKind
3343compareStandardConversionSubsets(ASTContext &Context,
3344 const StandardConversionSequence& SCS1,
3345 const StandardConversionSequence& SCS2) {
3346 ImplicitConversionSequence::CompareKind Result
3347 = ImplicitConversionSequence::Indistinguishable;
3348
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003350 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003351 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3352 return ImplicitConversionSequence::Better;
3353 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3354 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003355
Douglas Gregorad323a82010-01-27 03:51:04 +00003356 if (SCS1.Second != SCS2.Second) {
3357 if (SCS1.Second == ICK_Identity)
3358 Result = ImplicitConversionSequence::Better;
3359 else if (SCS2.Second == ICK_Identity)
3360 Result = ImplicitConversionSequence::Worse;
3361 else
3362 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003363 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003364 return ImplicitConversionSequence::Indistinguishable;
3365
3366 if (SCS1.Third == SCS2.Third) {
3367 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3368 : ImplicitConversionSequence::Indistinguishable;
3369 }
3370
3371 if (SCS1.Third == ICK_Identity)
3372 return Result == ImplicitConversionSequence::Worse
3373 ? ImplicitConversionSequence::Indistinguishable
3374 : ImplicitConversionSequence::Better;
3375
3376 if (SCS2.Third == ICK_Identity)
3377 return Result == ImplicitConversionSequence::Better
3378 ? ImplicitConversionSequence::Indistinguishable
3379 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380
Douglas Gregorad323a82010-01-27 03:51:04 +00003381 return ImplicitConversionSequence::Indistinguishable;
3382}
3383
Douglas Gregor440a4832011-01-26 14:52:12 +00003384/// \brief Determine whether one of the given reference bindings is better
3385/// than the other based on what kind of bindings they are.
3386static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3387 const StandardConversionSequence &SCS2) {
3388 // C++0x [over.ics.rank]p3b4:
3389 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3390 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003392 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003393 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003394 // reference*.
3395 //
3396 // FIXME: Rvalue references. We're going rogue with the above edits,
3397 // because the semantics in the current C++0x working paper (N3225 at the
3398 // time of this writing) break the standard definition of std::forward
3399 // and std::reference_wrapper when dealing with references to functions.
3400 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003401 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3402 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3403 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003404
Douglas Gregor440a4832011-01-26 14:52:12 +00003405 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3406 SCS2.IsLvalueReference) ||
3407 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3408 !SCS2.IsLvalueReference);
3409}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003411/// CompareStandardConversionSequences - Compare two standard
3412/// conversion sequences to determine whether one is better than the
3413/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003414static ImplicitConversionSequence::CompareKind
3415CompareStandardConversionSequences(Sema &S,
3416 const StandardConversionSequence& SCS1,
3417 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003418{
3419 // Standard conversion sequence S1 is a better conversion sequence
3420 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3421
3422 // -- S1 is a proper subsequence of S2 (comparing the conversion
3423 // sequences in the canonical form defined by 13.3.3.1.1,
3424 // excluding any Lvalue Transformation; the identity conversion
3425 // sequence is considered to be a subsequence of any
3426 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003427 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003428 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003429 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003430
3431 // -- the rank of S1 is better than the rank of S2 (by the rules
3432 // defined below), or, if not that,
3433 ImplicitConversionRank Rank1 = SCS1.getRank();
3434 ImplicitConversionRank Rank2 = SCS2.getRank();
3435 if (Rank1 < Rank2)
3436 return ImplicitConversionSequence::Better;
3437 else if (Rank2 < Rank1)
3438 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003439
Douglas Gregor57373262008-10-22 14:17:15 +00003440 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3441 // are indistinguishable unless one of the following rules
3442 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Douglas Gregor57373262008-10-22 14:17:15 +00003444 // A conversion that is not a conversion of a pointer, or
3445 // pointer to member, to bool is better than another conversion
3446 // that is such a conversion.
3447 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3448 return SCS2.isPointerConversionToBool()
3449 ? ImplicitConversionSequence::Better
3450 : ImplicitConversionSequence::Worse;
3451
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003452 // C++ [over.ics.rank]p4b2:
3453 //
3454 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003455 // conversion of B* to A* is better than conversion of B* to
3456 // void*, and conversion of A* to void* is better than conversion
3457 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003458 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003459 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003460 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003461 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003462 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3463 // Exactly one of the conversion sequences is a conversion to
3464 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003465 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3466 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003467 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3468 // Neither conversion sequence converts to a void pointer; compare
3469 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003470 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003471 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003472 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003473 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3474 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003475 // Both conversion sequences are conversions to void
3476 // pointers. Compare the source types to determine if there's an
3477 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003478 QualType FromType1 = SCS1.getFromType();
3479 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003480
3481 // Adjust the types we're converting from via the array-to-pointer
3482 // conversion, if we need to.
3483 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003484 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003485 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003486 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003487
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003488 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3489 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003490
John McCall120d63c2010-08-24 20:38:10 +00003491 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003492 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003493 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003494 return ImplicitConversionSequence::Worse;
3495
3496 // Objective-C++: If one interface is more specific than the
3497 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003498 const ObjCObjectPointerType* FromObjCPtr1
3499 = FromType1->getAs<ObjCObjectPointerType>();
3500 const ObjCObjectPointerType* FromObjCPtr2
3501 = FromType2->getAs<ObjCObjectPointerType>();
3502 if (FromObjCPtr1 && FromObjCPtr2) {
3503 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3504 FromObjCPtr2);
3505 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3506 FromObjCPtr1);
3507 if (AssignLeft != AssignRight) {
3508 return AssignLeft? ImplicitConversionSequence::Better
3509 : ImplicitConversionSequence::Worse;
3510 }
Douglas Gregor01919692009-12-13 21:37:05 +00003511 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003512 }
Douglas Gregor57373262008-10-22 14:17:15 +00003513
3514 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3515 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003516 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003517 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003518 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003519
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003520 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003521 // Check for a better reference binding based on the kind of bindings.
3522 if (isBetterReferenceBindingKind(SCS1, SCS2))
3523 return ImplicitConversionSequence::Better;
3524 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3525 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003527 // C++ [over.ics.rank]p3b4:
3528 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3529 // which the references refer are the same type except for
3530 // top-level cv-qualifiers, and the type to which the reference
3531 // initialized by S2 refers is more cv-qualified than the type
3532 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003533 QualType T1 = SCS1.getToType(2);
3534 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003535 T1 = S.Context.getCanonicalType(T1);
3536 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003537 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003538 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3539 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003540 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003541 // Objective-C++ ARC: If the references refer to objects with different
3542 // lifetimes, prefer bindings that don't change lifetime.
3543 if (SCS1.ObjCLifetimeConversionBinding !=
3544 SCS2.ObjCLifetimeConversionBinding) {
3545 return SCS1.ObjCLifetimeConversionBinding
3546 ? ImplicitConversionSequence::Worse
3547 : ImplicitConversionSequence::Better;
3548 }
3549
Chandler Carruth6df868e2010-12-12 08:17:55 +00003550 // If the type is an array type, promote the element qualifiers to the
3551 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003552 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003553 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003554 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003555 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003556 if (T2.isMoreQualifiedThan(T1))
3557 return ImplicitConversionSequence::Better;
3558 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003559 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003560 }
3561 }
Douglas Gregor57373262008-10-22 14:17:15 +00003562
Francois Pichet1c98d622011-09-18 21:37:37 +00003563 // In Microsoft mode, prefer an integral conversion to a
3564 // floating-to-integral conversion if the integral conversion
3565 // is between types of the same size.
3566 // For example:
3567 // void f(float);
3568 // void f(int);
3569 // int main {
3570 // long a;
3571 // f(a);
3572 // }
3573 // Here, MSVC will call f(int) instead of generating a compile error
3574 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003575 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003576 SCS1.Second == ICK_Integral_Conversion &&
3577 SCS2.Second == ICK_Floating_Integral &&
3578 S.Context.getTypeSize(SCS1.getFromType()) ==
3579 S.Context.getTypeSize(SCS1.getToType(2)))
3580 return ImplicitConversionSequence::Better;
3581
Douglas Gregor57373262008-10-22 14:17:15 +00003582 return ImplicitConversionSequence::Indistinguishable;
3583}
3584
3585/// CompareQualificationConversions - Compares two standard conversion
3586/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003587/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3588ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003589CompareQualificationConversions(Sema &S,
3590 const StandardConversionSequence& SCS1,
3591 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003592 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003593 // -- S1 and S2 differ only in their qualification conversion and
3594 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3595 // cv-qualification signature of type T1 is a proper subset of
3596 // the cv-qualification signature of type T2, and S1 is not the
3597 // deprecated string literal array-to-pointer conversion (4.2).
3598 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3599 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3600 return ImplicitConversionSequence::Indistinguishable;
3601
3602 // FIXME: the example in the standard doesn't use a qualification
3603 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003604 QualType T1 = SCS1.getToType(2);
3605 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003606 T1 = S.Context.getCanonicalType(T1);
3607 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003608 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003609 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3610 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003611
3612 // If the types are the same, we won't learn anything by unwrapped
3613 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003614 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003615 return ImplicitConversionSequence::Indistinguishable;
3616
Chandler Carruth28e318c2009-12-29 07:16:59 +00003617 // If the type is an array type, promote the element qualifiers to the type
3618 // for comparison.
3619 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003620 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003621 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003622 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003623
Mike Stump1eb44332009-09-09 15:08:12 +00003624 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003625 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003626
3627 // Objective-C++ ARC:
3628 // Prefer qualification conversions not involving a change in lifetime
3629 // to qualification conversions that do not change lifetime.
3630 if (SCS1.QualificationIncludesObjCLifetime !=
3631 SCS2.QualificationIncludesObjCLifetime) {
3632 Result = SCS1.QualificationIncludesObjCLifetime
3633 ? ImplicitConversionSequence::Worse
3634 : ImplicitConversionSequence::Better;
3635 }
3636
John McCall120d63c2010-08-24 20:38:10 +00003637 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003638 // Within each iteration of the loop, we check the qualifiers to
3639 // determine if this still looks like a qualification
3640 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003641 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003642 // until there are no more pointers or pointers-to-members left
3643 // to unwrap. This essentially mimics what
3644 // IsQualificationConversion does, but here we're checking for a
3645 // strict subset of qualifiers.
3646 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3647 // The qualifiers are the same, so this doesn't tell us anything
3648 // about how the sequences rank.
3649 ;
3650 else if (T2.isMoreQualifiedThan(T1)) {
3651 // T1 has fewer qualifiers, so it could be the better sequence.
3652 if (Result == ImplicitConversionSequence::Worse)
3653 // Neither has qualifiers that are a subset of the other's
3654 // qualifiers.
3655 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Douglas Gregor57373262008-10-22 14:17:15 +00003657 Result = ImplicitConversionSequence::Better;
3658 } else if (T1.isMoreQualifiedThan(T2)) {
3659 // T2 has fewer qualifiers, so it could be the better sequence.
3660 if (Result == ImplicitConversionSequence::Better)
3661 // Neither has qualifiers that are a subset of the other's
3662 // qualifiers.
3663 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Douglas Gregor57373262008-10-22 14:17:15 +00003665 Result = ImplicitConversionSequence::Worse;
3666 } else {
3667 // Qualifiers are disjoint.
3668 return ImplicitConversionSequence::Indistinguishable;
3669 }
3670
3671 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003672 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003673 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003674 }
3675
Douglas Gregor57373262008-10-22 14:17:15 +00003676 // Check that the winning standard conversion sequence isn't using
3677 // the deprecated string literal array to pointer conversion.
3678 switch (Result) {
3679 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003680 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003681 Result = ImplicitConversionSequence::Indistinguishable;
3682 break;
3683
3684 case ImplicitConversionSequence::Indistinguishable:
3685 break;
3686
3687 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003688 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003689 Result = ImplicitConversionSequence::Indistinguishable;
3690 break;
3691 }
3692
3693 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003694}
3695
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003696/// CompareDerivedToBaseConversions - Compares two standard conversion
3697/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003698/// various kinds of derived-to-base conversions (C++
3699/// [over.ics.rank]p4b3). As part of these checks, we also look at
3700/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003701ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003702CompareDerivedToBaseConversions(Sema &S,
3703 const StandardConversionSequence& SCS1,
3704 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003705 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003706 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003707 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003708 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003709
3710 // Adjust the types we're converting from via the array-to-pointer
3711 // conversion, if we need to.
3712 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003713 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003714 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003715 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003716
3717 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003718 FromType1 = S.Context.getCanonicalType(FromType1);
3719 ToType1 = S.Context.getCanonicalType(ToType1);
3720 FromType2 = S.Context.getCanonicalType(FromType2);
3721 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003723 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724 //
3725 // If class B is derived directly or indirectly from class A and
3726 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003727 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003728 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003729 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003730 SCS2.Second == ICK_Pointer_Conversion &&
3731 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3732 FromType1->isPointerType() && FromType2->isPointerType() &&
3733 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003734 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003735 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003736 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003737 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003738 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003739 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003740 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003741 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003742
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003743 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003744 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003745 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003746 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003747 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003748 return ImplicitConversionSequence::Worse;
3749 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003750
3751 // -- conversion of B* to A* is better than conversion of C* to A*,
3752 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003753 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003754 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003755 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003756 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003757 }
3758 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3759 SCS2.Second == ICK_Pointer_Conversion) {
3760 const ObjCObjectPointerType *FromPtr1
3761 = FromType1->getAs<ObjCObjectPointerType>();
3762 const ObjCObjectPointerType *FromPtr2
3763 = FromType2->getAs<ObjCObjectPointerType>();
3764 const ObjCObjectPointerType *ToPtr1
3765 = ToType1->getAs<ObjCObjectPointerType>();
3766 const ObjCObjectPointerType *ToPtr2
3767 = ToType2->getAs<ObjCObjectPointerType>();
3768
3769 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3770 // Apply the same conversion ranking rules for Objective-C pointer types
3771 // that we do for C++ pointers to class types. However, we employ the
3772 // Objective-C pseudo-subtyping relationship used for assignment of
3773 // Objective-C pointer types.
3774 bool FromAssignLeft
3775 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3776 bool FromAssignRight
3777 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3778 bool ToAssignLeft
3779 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3780 bool ToAssignRight
3781 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3782
3783 // A conversion to an a non-id object pointer type or qualified 'id'
3784 // type is better than a conversion to 'id'.
3785 if (ToPtr1->isObjCIdType() &&
3786 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3787 return ImplicitConversionSequence::Worse;
3788 if (ToPtr2->isObjCIdType() &&
3789 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3790 return ImplicitConversionSequence::Better;
3791
3792 // A conversion to a non-id object pointer type is better than a
3793 // conversion to a qualified 'id' type
3794 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3795 return ImplicitConversionSequence::Worse;
3796 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3797 return ImplicitConversionSequence::Better;
3798
3799 // A conversion to an a non-Class object pointer type or qualified 'Class'
3800 // type is better than a conversion to 'Class'.
3801 if (ToPtr1->isObjCClassType() &&
3802 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3803 return ImplicitConversionSequence::Worse;
3804 if (ToPtr2->isObjCClassType() &&
3805 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3806 return ImplicitConversionSequence::Better;
3807
3808 // A conversion to a non-Class object pointer type is better than a
3809 // conversion to a qualified 'Class' type.
3810 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3811 return ImplicitConversionSequence::Worse;
3812 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3813 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003814
Douglas Gregor395cc372011-01-31 18:51:41 +00003815 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3816 if (S.Context.hasSameType(FromType1, FromType2) &&
3817 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3818 (ToAssignLeft != ToAssignRight))
3819 return ToAssignLeft? ImplicitConversionSequence::Worse
3820 : ImplicitConversionSequence::Better;
3821
3822 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3823 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3824 (FromAssignLeft != FromAssignRight))
3825 return FromAssignLeft? ImplicitConversionSequence::Better
3826 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003827 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003828 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003829
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003830 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003831 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3832 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3833 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003835 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003836 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003837 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003838 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003839 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003840 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003841 ToType2->getAs<MemberPointerType>();
3842 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3843 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3844 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3845 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3846 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3847 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3848 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3849 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003850 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003851 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003852 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003853 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003854 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003855 return ImplicitConversionSequence::Better;
3856 }
3857 // conversion of B::* to C::* is better than conversion of A::* to C::*
3858 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003859 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003860 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003861 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003862 return ImplicitConversionSequence::Worse;
3863 }
3864 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003865
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003866 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003867 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003868 // -- binding of an expression of type C to a reference of type
3869 // B& is better than binding an expression of type C to a
3870 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003871 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3872 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3873 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003874 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003875 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003876 return ImplicitConversionSequence::Worse;
3877 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003878
Douglas Gregor225c41e2008-11-03 19:09:14 +00003879 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003880 // -- binding of an expression of type B to a reference of type
3881 // A& is better than binding an expression of type C to a
3882 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003883 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3884 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3885 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003886 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003887 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003888 return ImplicitConversionSequence::Worse;
3889 }
3890 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003891
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003892 return ImplicitConversionSequence::Indistinguishable;
3893}
3894
Douglas Gregorabe183d2010-04-13 16:31:36 +00003895/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3896/// determine whether they are reference-related,
3897/// reference-compatible, reference-compatible with added
3898/// qualification, or incompatible, for use in C++ initialization by
3899/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3900/// type, and the first type (T1) is the pointee type of the reference
3901/// type being initialized.
3902Sema::ReferenceCompareResult
3903Sema::CompareReferenceRelationship(SourceLocation Loc,
3904 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003905 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003906 bool &ObjCConversion,
3907 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003908 assert(!OrigT1->isReferenceType() &&
3909 "T1 must be the pointee type of the reference type");
3910 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3911
3912 QualType T1 = Context.getCanonicalType(OrigT1);
3913 QualType T2 = Context.getCanonicalType(OrigT2);
3914 Qualifiers T1Quals, T2Quals;
3915 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3916 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3917
3918 // C++ [dcl.init.ref]p4:
3919 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3920 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3921 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003922 DerivedToBase = false;
3923 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003924 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003925 if (UnqualT1 == UnqualT2) {
3926 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003927 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003928 IsDerivedFrom(UnqualT2, UnqualT1))
3929 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003930 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3931 UnqualT2->isObjCObjectOrInterfaceType() &&
3932 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3933 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003934 else
3935 return Ref_Incompatible;
3936
3937 // At this point, we know that T1 and T2 are reference-related (at
3938 // least).
3939
3940 // If the type is an array type, promote the element qualifiers to the type
3941 // for comparison.
3942 if (isa<ArrayType>(T1) && T1Quals)
3943 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3944 if (isa<ArrayType>(T2) && T2Quals)
3945 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3946
3947 // C++ [dcl.init.ref]p4:
3948 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3949 // reference-related to T2 and cv1 is the same cv-qualification
3950 // as, or greater cv-qualification than, cv2. For purposes of
3951 // overload resolution, cases for which cv1 is greater
3952 // cv-qualification than cv2 are identified as
3953 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003954 //
3955 // Note that we also require equivalence of Objective-C GC and address-space
3956 // qualifiers when performing these computations, so that e.g., an int in
3957 // address space 1 is not reference-compatible with an int in address
3958 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003959 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3960 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3961 T1Quals.removeObjCLifetime();
3962 T2Quals.removeObjCLifetime();
3963 ObjCLifetimeConversion = true;
3964 }
3965
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003966 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003967 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003968 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003969 return Ref_Compatible_With_Added_Qualification;
3970 else
3971 return Ref_Related;
3972}
3973
Douglas Gregor604eb652010-08-11 02:15:33 +00003974/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003975/// with DeclType. Return true if something definite is found.
3976static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003977FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3978 QualType DeclType, SourceLocation DeclLoc,
3979 Expr *Init, QualType T2, bool AllowRvalues,
3980 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003981 assert(T2->isRecordType() && "Can only find conversions of record types.");
3982 CXXRecordDecl *T2RecordDecl
3983 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3984
3985 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003986 std::pair<CXXRecordDecl::conversion_iterator,
3987 CXXRecordDecl::conversion_iterator>
3988 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3989 for (CXXRecordDecl::conversion_iterator
3990 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003991 NamedDecl *D = *I;
3992 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3993 if (isa<UsingShadowDecl>(D))
3994 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3995
3996 FunctionTemplateDecl *ConvTemplate
3997 = dyn_cast<FunctionTemplateDecl>(D);
3998 CXXConversionDecl *Conv;
3999 if (ConvTemplate)
4000 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4001 else
4002 Conv = cast<CXXConversionDecl>(D);
4003
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004005 // explicit conversions, skip it.
4006 if (!AllowExplicit && Conv->isExplicit())
4007 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004008
Douglas Gregor604eb652010-08-11 02:15:33 +00004009 if (AllowRvalues) {
4010 bool DerivedToBase = false;
4011 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004012 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004013
4014 // If we are initializing an rvalue reference, don't permit conversion
4015 // functions that return lvalues.
4016 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4017 const ReferenceType *RefType
4018 = Conv->getConversionType()->getAs<LValueReferenceType>();
4019 if (RefType && !RefType->getPointeeType()->isFunctionType())
4020 continue;
4021 }
4022
Douglas Gregor604eb652010-08-11 02:15:33 +00004023 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004024 S.CompareReferenceRelationship(
4025 DeclLoc,
4026 Conv->getConversionType().getNonReferenceType()
4027 .getUnqualifiedType(),
4028 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004029 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004030 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004031 continue;
4032 } else {
4033 // If the conversion function doesn't return a reference type,
4034 // it can't be considered for this conversion. An rvalue reference
4035 // is only acceptable if its referencee is a function type.
4036
4037 const ReferenceType *RefType =
4038 Conv->getConversionType()->getAs<ReferenceType>();
4039 if (!RefType ||
4040 (!RefType->isLValueReferenceType() &&
4041 !RefType->getPointeeType()->isFunctionType()))
4042 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004043 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
Douglas Gregor604eb652010-08-11 02:15:33 +00004045 if (ConvTemplate)
4046 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004047 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004048 else
4049 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004050 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004051 }
4052
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004053 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4054
Sebastian Redl4680bf22010-06-30 18:13:39 +00004055 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004056 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004057 case OR_Success:
4058 // C++ [over.ics.ref]p1:
4059 //
4060 // [...] If the parameter binds directly to the result of
4061 // applying a conversion function to the argument
4062 // expression, the implicit conversion sequence is a
4063 // user-defined conversion sequence (13.3.3.1.2), with the
4064 // second standard conversion sequence either an identity
4065 // conversion or, if the conversion function returns an
4066 // entity of a type that is a derived class of the parameter
4067 // type, a derived-to-base Conversion.
4068 if (!Best->FinalConversion.DirectBinding)
4069 return false;
4070
4071 ICS.setUserDefined();
4072 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4073 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004074 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004075 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004076 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004077 ICS.UserDefined.EllipsisConversion = false;
4078 assert(ICS.UserDefined.After.ReferenceBinding &&
4079 ICS.UserDefined.After.DirectBinding &&
4080 "Expected a direct reference binding!");
4081 return true;
4082
4083 case OR_Ambiguous:
4084 ICS.setAmbiguous();
4085 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4086 Cand != CandidateSet.end(); ++Cand)
4087 if (Cand->Viable)
4088 ICS.Ambiguous.addConversion(Cand->Function);
4089 return true;
4090
4091 case OR_No_Viable_Function:
4092 case OR_Deleted:
4093 // There was no suitable conversion, or we found a deleted
4094 // conversion; continue with other checks.
4095 return false;
4096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004097
David Blaikie7530c032012-01-17 06:56:22 +00004098 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004099}
4100
Douglas Gregorabe183d2010-04-13 16:31:36 +00004101/// \brief Compute an implicit conversion sequence for reference
4102/// initialization.
4103static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004104TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004105 SourceLocation DeclLoc,
4106 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004107 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004108 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4109
4110 // Most paths end in a failed conversion.
4111 ImplicitConversionSequence ICS;
4112 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4113
4114 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4115 QualType T2 = Init->getType();
4116
4117 // If the initializer is the address of an overloaded function, try
4118 // to resolve the overloaded function. If all goes well, T2 is the
4119 // type of the resulting function.
4120 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4121 DeclAccessPair Found;
4122 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4123 false, Found))
4124 T2 = Fn->getType();
4125 }
4126
4127 // Compute some basic properties of the types and the initializer.
4128 bool isRValRef = DeclType->isRValueReferenceType();
4129 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004130 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004131 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004132 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004133 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004134 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004135 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004136
Douglas Gregorabe183d2010-04-13 16:31:36 +00004137
Sebastian Redl4680bf22010-06-30 18:13:39 +00004138 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004139 // A reference to type "cv1 T1" is initialized by an expression
4140 // of type "cv2 T2" as follows:
4141
Sebastian Redl4680bf22010-06-30 18:13:39 +00004142 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004143 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004144 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4145 // reference-compatible with "cv2 T2," or
4146 //
4147 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4148 if (InitCategory.isLValue() &&
4149 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004150 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004151 // When a parameter of reference type binds directly (8.5.3)
4152 // to an argument expression, the implicit conversion sequence
4153 // is the identity conversion, unless the argument expression
4154 // has a type that is a derived class of the parameter type,
4155 // in which case the implicit conversion sequence is a
4156 // derived-to-base Conversion (13.3.3.1).
4157 ICS.setStandard();
4158 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004159 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4160 : ObjCConversion? ICK_Compatible_Conversion
4161 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 ICS.Standard.Third = ICK_Identity;
4163 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4164 ICS.Standard.setToType(0, T2);
4165 ICS.Standard.setToType(1, T1);
4166 ICS.Standard.setToType(2, T1);
4167 ICS.Standard.ReferenceBinding = true;
4168 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004169 ICS.Standard.IsLvalueReference = !isRValRef;
4170 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4171 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004172 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004173 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004174 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004175
Sebastian Redl4680bf22010-06-30 18:13:39 +00004176 // Nothing more to do: the inaccessibility/ambiguity check for
4177 // derived-to-base conversions is suppressed when we're
4178 // computing the implicit conversion sequence (C++
4179 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004180 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004181 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004182
Sebastian Redl4680bf22010-06-30 18:13:39 +00004183 // -- has a class type (i.e., T2 is a class type), where T1 is
4184 // not reference-related to T2, and can be implicitly
4185 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4186 // is reference-compatible with "cv3 T3" 92) (this
4187 // conversion is selected by enumerating the applicable
4188 // conversion functions (13.3.1.6) and choosing the best
4189 // one through overload resolution (13.3)),
4190 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004192 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004193 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4194 Init, T2, /*AllowRvalues=*/false,
4195 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004196 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004197 }
4198 }
4199
Sebastian Redl4680bf22010-06-30 18:13:39 +00004200 // -- Otherwise, the reference shall be an lvalue reference to a
4201 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004202 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004203 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004204 // We actually handle one oddity of C++ [over.ics.ref] at this
4205 // point, which is that, due to p2 (which short-circuits reference
4206 // binding by only attempting a simple conversion for non-direct
4207 // bindings) and p3's strange wording, we allow a const volatile
4208 // reference to bind to an rvalue. Hence the check for the presence
4209 // of "const" rather than checking for "const" being the only
4210 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004211 // This is also the point where rvalue references and lvalue inits no longer
4212 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004213 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004214 return ICS;
4215
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004216 // -- If the initializer expression
4217 //
4218 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004219 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004220 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4221 (InitCategory.isXValue() ||
4222 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4223 (InitCategory.isLValue() && T2->isFunctionType()))) {
4224 ICS.setStandard();
4225 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004227 : ObjCConversion? ICK_Compatible_Conversion
4228 : ICK_Identity;
4229 ICS.Standard.Third = ICK_Identity;
4230 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4231 ICS.Standard.setToType(0, T2);
4232 ICS.Standard.setToType(1, T1);
4233 ICS.Standard.setToType(2, T1);
4234 ICS.Standard.ReferenceBinding = true;
4235 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4236 // binding unless we're binding to a class prvalue.
4237 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4238 // allow the use of rvalue references in C++98/03 for the benefit of
4239 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004240 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004241 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004242 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004243 ICS.Standard.IsLvalueReference = !isRValRef;
4244 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004245 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004246 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004247 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004248 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004249 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004252 // -- has a class type (i.e., T2 is a class type), where T1 is not
4253 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004254 // an xvalue, class prvalue, or function lvalue of type
4255 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004256 // "cv3 T3",
4257 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004259 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004261 // class subobject).
4262 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004264 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4265 Init, T2, /*AllowRvalues=*/true,
4266 AllowExplicit)) {
4267 // In the second case, if the reference is an rvalue reference
4268 // and the second standard conversion sequence of the
4269 // user-defined conversion sequence includes an lvalue-to-rvalue
4270 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004271 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004272 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4273 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4274
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004275 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004276 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004277
Douglas Gregorabe183d2010-04-13 16:31:36 +00004278 // -- Otherwise, a temporary of type "cv1 T1" is created and
4279 // initialized from the initializer expression using the
4280 // rules for a non-reference copy initialization (8.5). The
4281 // reference is then bound to the temporary. If T1 is
4282 // reference-related to T2, cv1 must be the same
4283 // cv-qualification as, or greater cv-qualification than,
4284 // cv2; otherwise, the program is ill-formed.
4285 if (RefRelationship == Sema::Ref_Related) {
4286 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4287 // we would be reference-compatible or reference-compatible with
4288 // added qualification. But that wasn't the case, so the reference
4289 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004290 //
4291 // Note that we only want to check address spaces and cvr-qualifiers here.
4292 // ObjC GC and lifetime qualifiers aren't important.
4293 Qualifiers T1Quals = T1.getQualifiers();
4294 Qualifiers T2Quals = T2.getQualifiers();
4295 T1Quals.removeObjCGCAttr();
4296 T1Quals.removeObjCLifetime();
4297 T2Quals.removeObjCGCAttr();
4298 T2Quals.removeObjCLifetime();
4299 if (!T1Quals.compatiblyIncludes(T2Quals))
4300 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004301 }
4302
4303 // If at least one of the types is a class type, the types are not
4304 // related, and we aren't allowed any user conversions, the
4305 // reference binding fails. This case is important for breaking
4306 // recursion, since TryImplicitConversion below will attempt to
4307 // create a temporary through the use of a copy constructor.
4308 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4309 (T1->isRecordType() || T2->isRecordType()))
4310 return ICS;
4311
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004312 // If T1 is reference-related to T2 and the reference is an rvalue
4313 // reference, the initializer expression shall not be an lvalue.
4314 if (RefRelationship >= Sema::Ref_Related &&
4315 isRValRef && Init->Classify(S.Context).isLValue())
4316 return ICS;
4317
Douglas Gregorabe183d2010-04-13 16:31:36 +00004318 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004319 // When a parameter of reference type is not bound directly to
4320 // an argument expression, the conversion sequence is the one
4321 // required to convert the argument expression to the
4322 // underlying type of the reference according to
4323 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4324 // to copy-initializing a temporary of the underlying type with
4325 // the argument expression. Any difference in top-level
4326 // cv-qualification is subsumed by the initialization itself
4327 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004328 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4329 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004330 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004331 /*CStyle=*/false,
4332 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004333
4334 // Of course, that's still a reference binding.
4335 if (ICS.isStandard()) {
4336 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004337 ICS.Standard.IsLvalueReference = !isRValRef;
4338 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4339 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004340 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004341 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004342 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004343 // Don't allow rvalue references to bind to lvalues.
4344 if (DeclType->isRValueReferenceType()) {
4345 if (const ReferenceType *RefType
4346 = ICS.UserDefined.ConversionFunction->getResultType()
4347 ->getAs<LValueReferenceType>()) {
4348 if (!RefType->getPointeeType()->isFunctionType()) {
4349 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4350 DeclType);
4351 return ICS;
4352 }
4353 }
4354 }
4355
Douglas Gregorabe183d2010-04-13 16:31:36 +00004356 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004357 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4358 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4359 ICS.UserDefined.After.BindsToRvalue = true;
4360 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4361 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004362 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004363
Douglas Gregorabe183d2010-04-13 16:31:36 +00004364 return ICS;
4365}
4366
Sebastian Redl5405b812011-10-16 18:19:34 +00004367static ImplicitConversionSequence
4368TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4369 bool SuppressUserConversions,
4370 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004371 bool AllowObjCWritebackConversion,
4372 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004373
4374/// TryListConversion - Try to copy-initialize a value of type ToType from the
4375/// initializer list From.
4376static ImplicitConversionSequence
4377TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4378 bool SuppressUserConversions,
4379 bool InOverloadResolution,
4380 bool AllowObjCWritebackConversion) {
4381 // C++11 [over.ics.list]p1:
4382 // When an argument is an initializer list, it is not an expression and
4383 // special rules apply for converting it to a parameter type.
4384
4385 ImplicitConversionSequence Result;
4386 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004387 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004388
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004389 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004390 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004391 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004392 return Result;
4393
Sebastian Redl5405b812011-10-16 18:19:34 +00004394 // C++11 [over.ics.list]p2:
4395 // If the parameter type is std::initializer_list<X> or "array of X" and
4396 // all the elements can be implicitly converted to X, the implicit
4397 // conversion sequence is the worst conversion necessary to convert an
4398 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004399 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004400 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004401 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004402 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004403 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004404 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004405 if (!X.isNull()) {
4406 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4407 Expr *Init = From->getInit(i);
4408 ImplicitConversionSequence ICS =
4409 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4410 InOverloadResolution,
4411 AllowObjCWritebackConversion);
4412 // If a single element isn't convertible, fail.
4413 if (ICS.isBad()) {
4414 Result = ICS;
4415 break;
4416 }
4417 // Otherwise, look for the worst conversion.
4418 if (Result.isBad() ||
4419 CompareImplicitConversionSequences(S, ICS, Result) ==
4420 ImplicitConversionSequence::Worse)
4421 Result = ICS;
4422 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004423
4424 // For an empty list, we won't have computed any conversion sequence.
4425 // Introduce the identity conversion sequence.
4426 if (From->getNumInits() == 0) {
4427 Result.setStandard();
4428 Result.Standard.setAsIdentityConversion();
4429 Result.Standard.setFromType(ToType);
4430 Result.Standard.setAllToTypes(ToType);
4431 }
4432
Sebastian Redlfe592282012-01-17 22:49:48 +00004433 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004434 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004435 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004436 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004437
4438 // C++11 [over.ics.list]p3:
4439 // Otherwise, if the parameter is a non-aggregate class X and overload
4440 // resolution chooses a single best constructor [...] the implicit
4441 // conversion sequence is a user-defined conversion sequence. If multiple
4442 // constructors are viable but none is better than the others, the
4443 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004444 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4445 // This function can deal with initializer lists.
4446 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4447 /*AllowExplicit=*/false,
4448 InOverloadResolution, /*CStyle=*/false,
4449 AllowObjCWritebackConversion);
4450 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004451 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004452 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004453
4454 // C++11 [over.ics.list]p4:
4455 // Otherwise, if the parameter has an aggregate type which can be
4456 // initialized from the initializer list [...] the implicit conversion
4457 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004458 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004459 // Type is an aggregate, argument is an init list. At this point it comes
4460 // down to checking whether the initialization works.
4461 // FIXME: Find out whether this parameter is consumed or not.
4462 InitializedEntity Entity =
4463 InitializedEntity::InitializeParameter(S.Context, ToType,
4464 /*Consumed=*/false);
4465 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4466 Result.setUserDefined();
4467 Result.UserDefined.Before.setAsIdentityConversion();
4468 // Initializer lists don't have a type.
4469 Result.UserDefined.Before.setFromType(QualType());
4470 Result.UserDefined.Before.setAllToTypes(QualType());
4471
4472 Result.UserDefined.After.setAsIdentityConversion();
4473 Result.UserDefined.After.setFromType(ToType);
4474 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004475 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004476 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004477 return Result;
4478 }
4479
4480 // C++11 [over.ics.list]p5:
4481 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004482 if (ToType->isReferenceType()) {
4483 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4484 // mention initializer lists in any way. So we go by what list-
4485 // initialization would do and try to extrapolate from that.
4486
4487 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4488
4489 // If the initializer list has a single element that is reference-related
4490 // to the parameter type, we initialize the reference from that.
4491 if (From->getNumInits() == 1) {
4492 Expr *Init = From->getInit(0);
4493
4494 QualType T2 = Init->getType();
4495
4496 // If the initializer is the address of an overloaded function, try
4497 // to resolve the overloaded function. If all goes well, T2 is the
4498 // type of the resulting function.
4499 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4500 DeclAccessPair Found;
4501 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4502 Init, ToType, false, Found))
4503 T2 = Fn->getType();
4504 }
4505
4506 // Compute some basic properties of the types and the initializer.
4507 bool dummy1 = false;
4508 bool dummy2 = false;
4509 bool dummy3 = false;
4510 Sema::ReferenceCompareResult RefRelationship
4511 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4512 dummy2, dummy3);
4513
4514 if (RefRelationship >= Sema::Ref_Related)
4515 return TryReferenceInit(S, Init, ToType,
4516 /*FIXME:*/From->getLocStart(),
4517 SuppressUserConversions,
4518 /*AllowExplicit=*/false);
4519 }
4520
4521 // Otherwise, we bind the reference to a temporary created from the
4522 // initializer list.
4523 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4524 InOverloadResolution,
4525 AllowObjCWritebackConversion);
4526 if (Result.isFailure())
4527 return Result;
4528 assert(!Result.isEllipsis() &&
4529 "Sub-initialization cannot result in ellipsis conversion.");
4530
4531 // Can we even bind to a temporary?
4532 if (ToType->isRValueReferenceType() ||
4533 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4534 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4535 Result.UserDefined.After;
4536 SCS.ReferenceBinding = true;
4537 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4538 SCS.BindsToRvalue = true;
4539 SCS.BindsToFunctionLvalue = false;
4540 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4541 SCS.ObjCLifetimeConversionBinding = false;
4542 } else
4543 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4544 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004545 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004546 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004547
4548 // C++11 [over.ics.list]p6:
4549 // Otherwise, if the parameter type is not a class:
4550 if (!ToType->isRecordType()) {
4551 // - if the initializer list has one element, the implicit conversion
4552 // sequence is the one required to convert the element to the
4553 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004554 unsigned NumInits = From->getNumInits();
4555 if (NumInits == 1)
4556 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4557 SuppressUserConversions,
4558 InOverloadResolution,
4559 AllowObjCWritebackConversion);
4560 // - if the initializer list has no elements, the implicit conversion
4561 // sequence is the identity conversion.
4562 else if (NumInits == 0) {
4563 Result.setStandard();
4564 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004565 Result.Standard.setFromType(ToType);
4566 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004567 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004568 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004569 return Result;
4570 }
4571
4572 // C++11 [over.ics.list]p7:
4573 // In all cases other than those enumerated above, no conversion is possible
4574 return Result;
4575}
4576
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004577/// TryCopyInitialization - Try to copy-initialize a value of type
4578/// ToType from the expression From. Return the implicit conversion
4579/// sequence required to pass this argument, which may be a bad
4580/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004581/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004582/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004583static ImplicitConversionSequence
4584TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004585 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004586 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004587 bool AllowObjCWritebackConversion,
4588 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004589 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4590 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4591 InOverloadResolution,AllowObjCWritebackConversion);
4592
Douglas Gregorabe183d2010-04-13 16:31:36 +00004593 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004594 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004595 /*FIXME:*/From->getLocStart(),
4596 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004597 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004598
John McCall120d63c2010-08-24 20:38:10 +00004599 return TryImplicitConversion(S, From, ToType,
4600 SuppressUserConversions,
4601 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004602 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004603 /*CStyle=*/false,
4604 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004605}
4606
Anna Zaksf3546ee2011-07-28 19:46:48 +00004607static bool TryCopyInitialization(const CanQualType FromQTy,
4608 const CanQualType ToQTy,
4609 Sema &S,
4610 SourceLocation Loc,
4611 ExprValueKind FromVK) {
4612 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4613 ImplicitConversionSequence ICS =
4614 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4615
4616 return !ICS.isBad();
4617}
4618
Douglas Gregor96176b32008-11-18 23:14:02 +00004619/// TryObjectArgumentInitialization - Try to initialize the object
4620/// parameter of the given member function (@c Method) from the
4621/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004622static ImplicitConversionSequence
4623TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004624 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004625 CXXMethodDecl *Method,
4626 CXXRecordDecl *ActingContext) {
4627 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004628 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4629 // const volatile object.
4630 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4631 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004632 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004633
4634 // Set up the conversion sequence as a "bad" conversion, to allow us
4635 // to exit early.
4636 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004637
4638 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004639 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004640 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004641 FromType = PT->getPointeeType();
4642
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004643 // When we had a pointer, it's implicitly dereferenced, so we
4644 // better have an lvalue.
4645 assert(FromClassification.isLValue());
4646 }
4647
Anders Carlssona552f7c2009-05-01 18:34:30 +00004648 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004649
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004650 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004651 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004652 // parameter is
4653 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004654 // - "lvalue reference to cv X" for functions declared without a
4655 // ref-qualifier or with the & ref-qualifier
4656 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004657 // ref-qualifier
4658 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004660 // cv-qualification on the member function declaration.
4661 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004663 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004664 // (C++ [over.match.funcs]p5). We perform a simplified version of
4665 // reference binding here, that allows class rvalues to bind to
4666 // non-constant references.
4667
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004668 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004669 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004670 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004671 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004672 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004673 ICS.setBad(BadConversionSequence::bad_qualifiers,
4674 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004675 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004676 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004677
4678 // Check that we have either the same type or a derived type. It
4679 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004680 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004681 ImplicitConversionKind SecondKind;
4682 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4683 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004684 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004685 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004686 else {
John McCallb1bdc622010-02-25 01:37:24 +00004687 ICS.setBad(BadConversionSequence::unrelated_class,
4688 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004689 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004690 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004691
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004692 // Check the ref-qualifier.
4693 switch (Method->getRefQualifier()) {
4694 case RQ_None:
4695 // Do nothing; we don't care about lvalueness or rvalueness.
4696 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004697
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004698 case RQ_LValue:
4699 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4700 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004701 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004702 ImplicitParamType);
4703 return ICS;
4704 }
4705 break;
4706
4707 case RQ_RValue:
4708 if (!FromClassification.isRValue()) {
4709 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004710 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004711 ImplicitParamType);
4712 return ICS;
4713 }
4714 break;
4715 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004716
Douglas Gregor96176b32008-11-18 23:14:02 +00004717 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004718 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004719 ICS.Standard.setAsIdentityConversion();
4720 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004721 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004722 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004723 ICS.Standard.ReferenceBinding = true;
4724 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004725 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004726 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004727 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4728 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4729 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004730 return ICS;
4731}
4732
4733/// PerformObjectArgumentInitialization - Perform initialization of
4734/// the implicit object parameter for the given Method with the given
4735/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004736ExprResult
4737Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004738 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004739 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004740 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004741 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004742 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004743 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004745 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004746 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004747 FromRecordType = PT->getPointeeType();
4748 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004749 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004750 } else {
4751 FromRecordType = From->getType();
4752 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004753 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004754 }
4755
John McCall701c89e2009-12-03 04:06:58 +00004756 // Note that we always use the true parent context when performing
4757 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004758 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004759 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4760 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004761 if (ICS.isBad()) {
4762 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4763 Qualifiers FromQs = FromRecordType.getQualifiers();
4764 Qualifiers ToQs = DestType.getQualifiers();
4765 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4766 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004767 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004768 diag::err_member_function_call_bad_cvr)
4769 << Method->getDeclName() << FromRecordType << (CVR - 1)
4770 << From->getSourceRange();
4771 Diag(Method->getLocation(), diag::note_previous_decl)
4772 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004773 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004774 }
4775 }
4776
Daniel Dunbar96a00142012-03-09 18:35:03 +00004777 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004778 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004779 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781
John Wiegley429bb272011-04-08 18:41:53 +00004782 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4783 ExprResult FromRes =
4784 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4785 if (FromRes.isInvalid())
4786 return ExprError();
4787 From = FromRes.take();
4788 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004789
Douglas Gregor5fccd362010-03-03 23:55:11 +00004790 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004791 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004792 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004793 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004794}
4795
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004796/// TryContextuallyConvertToBool - Attempt to contextually convert the
4797/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004798static ImplicitConversionSequence
4799TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004800 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004801 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004802 // FIXME: Are these flags correct?
4803 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004804 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004805 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004806 /*CStyle=*/false,
4807 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004808}
4809
4810/// PerformContextuallyConvertToBool - Perform a contextual conversion
4811/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004812ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004813 if (checkPlaceholderForOverload(*this, From))
4814 return ExprError();
4815
John McCall120d63c2010-08-24 20:38:10 +00004816 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004817 if (!ICS.isBad())
4818 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004819
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004820 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004821 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004822 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004823 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004824 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004825}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826
Richard Smith8ef7b202012-01-18 23:55:52 +00004827/// Check that the specified conversion is permitted in a converted constant
4828/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4829/// is acceptable.
4830static bool CheckConvertedConstantConversions(Sema &S,
4831 StandardConversionSequence &SCS) {
4832 // Since we know that the target type is an integral or unscoped enumeration
4833 // type, most conversion kinds are impossible. All possible First and Third
4834 // conversions are fine.
4835 switch (SCS.Second) {
4836 case ICK_Identity:
4837 case ICK_Integral_Promotion:
4838 case ICK_Integral_Conversion:
4839 return true;
4840
4841 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004842 // Conversion from an integral or unscoped enumeration type to bool is
4843 // classified as ICK_Boolean_Conversion, but it's also an integral
4844 // conversion, so it's permitted in a converted constant expression.
4845 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4846 SCS.getToType(2)->isBooleanType();
4847
Richard Smith8ef7b202012-01-18 23:55:52 +00004848 case ICK_Floating_Integral:
4849 case ICK_Complex_Real:
4850 return false;
4851
4852 case ICK_Lvalue_To_Rvalue:
4853 case ICK_Array_To_Pointer:
4854 case ICK_Function_To_Pointer:
4855 case ICK_NoReturn_Adjustment:
4856 case ICK_Qualification:
4857 case ICK_Compatible_Conversion:
4858 case ICK_Vector_Conversion:
4859 case ICK_Vector_Splat:
4860 case ICK_Derived_To_Base:
4861 case ICK_Pointer_Conversion:
4862 case ICK_Pointer_Member:
4863 case ICK_Block_Pointer_Conversion:
4864 case ICK_Writeback_Conversion:
4865 case ICK_Floating_Promotion:
4866 case ICK_Complex_Promotion:
4867 case ICK_Complex_Conversion:
4868 case ICK_Floating_Conversion:
4869 case ICK_TransparentUnionConversion:
4870 llvm_unreachable("unexpected second conversion kind");
4871
4872 case ICK_Num_Conversion_Kinds:
4873 break;
4874 }
4875
4876 llvm_unreachable("unknown conversion kind");
4877}
4878
4879/// CheckConvertedConstantExpression - Check that the expression From is a
4880/// converted constant expression of type T, perform the conversion and produce
4881/// the converted expression, per C++11 [expr.const]p3.
4882ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4883 llvm::APSInt &Value,
4884 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004885 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004886 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4887
4888 if (checkPlaceholderForOverload(*this, From))
4889 return ExprError();
4890
4891 // C++11 [expr.const]p3 with proposed wording fixes:
4892 // A converted constant expression of type T is a core constant expression,
4893 // implicitly converted to a prvalue of type T, where the converted
4894 // expression is a literal constant expression and the implicit conversion
4895 // sequence contains only user-defined conversions, lvalue-to-rvalue
4896 // conversions, integral promotions, and integral conversions other than
4897 // narrowing conversions.
4898 ImplicitConversionSequence ICS =
4899 TryImplicitConversion(From, T,
4900 /*SuppressUserConversions=*/false,
4901 /*AllowExplicit=*/false,
4902 /*InOverloadResolution=*/false,
4903 /*CStyle=*/false,
4904 /*AllowObjcWritebackConversion=*/false);
4905 StandardConversionSequence *SCS = 0;
4906 switch (ICS.getKind()) {
4907 case ImplicitConversionSequence::StandardConversion:
4908 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004909 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004910 diag::err_typecheck_converted_constant_expression_disallowed)
4911 << From->getType() << From->getSourceRange() << T;
4912 SCS = &ICS.Standard;
4913 break;
4914 case ImplicitConversionSequence::UserDefinedConversion:
4915 // We are converting from class type to an integral or enumeration type, so
4916 // the Before sequence must be trivial.
4917 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004918 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004919 diag::err_typecheck_converted_constant_expression_disallowed)
4920 << From->getType() << From->getSourceRange() << T;
4921 SCS = &ICS.UserDefined.After;
4922 break;
4923 case ImplicitConversionSequence::AmbiguousConversion:
4924 case ImplicitConversionSequence::BadConversion:
4925 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004926 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004927 diag::err_typecheck_converted_constant_expression)
4928 << From->getType() << From->getSourceRange() << T;
4929 return ExprError();
4930
4931 case ImplicitConversionSequence::EllipsisConversion:
4932 llvm_unreachable("ellipsis conversion in converted constant expression");
4933 }
4934
4935 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4936 if (Result.isInvalid())
4937 return Result;
4938
4939 // Check for a narrowing implicit conversion.
4940 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004941 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004942 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4943 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004944 case NK_Variable_Narrowing:
4945 // Implicit conversion to a narrower type, and the value is not a constant
4946 // expression. We'll diagnose this in a moment.
4947 case NK_Not_Narrowing:
4948 break;
4949
4950 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004951 Diag(From->getLocStart(),
4952 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4953 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004954 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004955 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004956 break;
4957
4958 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004959 Diag(From->getLocStart(),
4960 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4961 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004962 << CCE << /*Constant*/0 << From->getType() << T;
4963 break;
4964 }
4965
4966 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004967 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00004968 Expr::EvalResult Eval;
4969 Eval.Diag = &Notes;
4970
4971 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4972 // The expression can't be folded, so we can't keep it at this position in
4973 // the AST.
4974 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004975 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004976 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004977
4978 if (Notes.empty()) {
4979 // It's a constant expression.
4980 return Result;
4981 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004982 }
4983
4984 // It's not a constant expression. Produce an appropriate diagnostic.
4985 if (Notes.size() == 1 &&
4986 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4987 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4988 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004989 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004990 << CCE << From->getSourceRange();
4991 for (unsigned I = 0; I < Notes.size(); ++I)
4992 Diag(Notes[I].first, Notes[I].second);
4993 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004994 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004995}
4996
John McCall0bcc9bc2011-09-09 06:11:02 +00004997/// dropPointerConversions - If the given standard conversion sequence
4998/// involves any pointer conversions, remove them. This may change
4999/// the result type of the conversion sequence.
5000static void dropPointerConversion(StandardConversionSequence &SCS) {
5001 if (SCS.Second == ICK_Pointer_Conversion) {
5002 SCS.Second = ICK_Identity;
5003 SCS.Third = ICK_Identity;
5004 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5005 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005006}
John McCall120d63c2010-08-24 20:38:10 +00005007
John McCall0bcc9bc2011-09-09 06:11:02 +00005008/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5009/// convert the expression From to an Objective-C pointer type.
5010static ImplicitConversionSequence
5011TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5012 // Do an implicit conversion to 'id'.
5013 QualType Ty = S.Context.getObjCIdType();
5014 ImplicitConversionSequence ICS
5015 = TryImplicitConversion(S, From, Ty,
5016 // FIXME: Are these flags correct?
5017 /*SuppressUserConversions=*/false,
5018 /*AllowExplicit=*/true,
5019 /*InOverloadResolution=*/false,
5020 /*CStyle=*/false,
5021 /*AllowObjCWritebackConversion=*/false);
5022
5023 // Strip off any final conversions to 'id'.
5024 switch (ICS.getKind()) {
5025 case ImplicitConversionSequence::BadConversion:
5026 case ImplicitConversionSequence::AmbiguousConversion:
5027 case ImplicitConversionSequence::EllipsisConversion:
5028 break;
5029
5030 case ImplicitConversionSequence::UserDefinedConversion:
5031 dropPointerConversion(ICS.UserDefined.After);
5032 break;
5033
5034 case ImplicitConversionSequence::StandardConversion:
5035 dropPointerConversion(ICS.Standard);
5036 break;
5037 }
5038
5039 return ICS;
5040}
5041
5042/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5043/// conversion of the expression From to an Objective-C pointer type.
5044ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005045 if (checkPlaceholderForOverload(*this, From))
5046 return ExprError();
5047
John McCallc12c5bb2010-05-15 11:32:37 +00005048 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005049 ImplicitConversionSequence ICS =
5050 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005051 if (!ICS.isBad())
5052 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005053 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005054}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005055
Richard Smithf39aec12012-02-04 07:07:42 +00005056/// Determine whether the provided type is an integral type, or an enumeration
5057/// type of a permitted flavor.
5058static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5059 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5060 : T->isIntegralOrUnscopedEnumerationType();
5061}
5062
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005063/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005064/// enumeration type.
5065///
5066/// This routine will attempt to convert an expression of class type to an
5067/// integral or enumeration type, if that class type only has a single
5068/// conversion to an integral or enumeration type.
5069///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005070/// \param Loc The source location of the construct that requires the
5071/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005072///
James Dennett40ae6662012-06-22 08:52:37 +00005073/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005074///
James Dennett40ae6662012-06-22 08:52:37 +00005075/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005076///
Richard Smithf39aec12012-02-04 07:07:42 +00005077/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5078/// enumerations should be considered.
5079///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005080/// \returns The expression, converted to an integral or enumeration type if
5081/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005083Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005084 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005085 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005086 // We can't perform any more checking for type-dependent expressions.
5087 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005088 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089
Eli Friedmanceccab92012-01-26 00:26:18 +00005090 // Process placeholders immediately.
5091 if (From->hasPlaceholderType()) {
5092 ExprResult result = CheckPlaceholderExpr(From);
5093 if (result.isInvalid()) return result;
5094 From = result.take();
5095 }
5096
Douglas Gregorc30614b2010-06-29 23:17:37 +00005097 // If the expression already has integral or enumeration type, we're golden.
5098 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005099 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005100 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005101
5102 // FIXME: Check for missing '()' if T is a function type?
5103
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00005105 // expression of integral or enumeration type.
5106 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005107 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005108 if (!Diagnoser.Suppress)
5109 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005110 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005112
Douglas Gregorc30614b2010-06-29 23:17:37 +00005113 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005114 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005115 ICEConvertDiagnoser &Diagnoser;
5116 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005117
Douglas Gregorab41fe92012-05-04 22:38:52 +00005118 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5119 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005120
5121 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005122 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005123 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005124 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005125
5126 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005127 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005128
Douglas Gregorc30614b2010-06-29 23:17:37 +00005129 // Look for a conversion to an integral or enumeration type.
5130 UnresolvedSet<4> ViableConversions;
5131 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005132 std::pair<CXXRecordDecl::conversion_iterator,
5133 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005134 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005135
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005136 bool HadMultipleCandidates
5137 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005138
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005139 for (CXXRecordDecl::conversion_iterator
5140 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005141 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005142 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5143 if (isIntegralOrEnumerationType(
5144 Conversion->getConversionType().getNonReferenceType(),
5145 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005146 if (Conversion->isExplicit())
5147 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5148 else
5149 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5150 }
Richard Smithf39aec12012-02-04 07:07:42 +00005151 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005152 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005153
Douglas Gregorc30614b2010-06-29 23:17:37 +00005154 switch (ViableConversions.size()) {
5155 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005156 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005157 DeclAccessPair Found = ExplicitConversions[0];
5158 CXXConversionDecl *Conversion
5159 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005160
Douglas Gregorc30614b2010-06-29 23:17:37 +00005161 // The user probably meant to invoke the given explicit
5162 // conversion; use it.
5163 QualType ConvTy
5164 = Conversion->getConversionType().getNonReferenceType();
5165 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005166 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005167
Douglas Gregorab41fe92012-05-04 22:38:52 +00005168 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005169 << FixItHint::CreateInsertion(From->getLocStart(),
5170 "static_cast<" + TypeStr + ">(")
5171 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5172 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005173 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005174
5175 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005176 // explicit conversion function.
5177 if (isSFINAEContext())
5178 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005179
Douglas Gregorc30614b2010-06-29 23:17:37 +00005180 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005181 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5182 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005183 if (Result.isInvalid())
5184 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005185 // Record usage of conversion in an implicit cast.
5186 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5187 CK_UserDefinedConversion,
5188 Result.get(), 0,
5189 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005190 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005191
Douglas Gregorc30614b2010-06-29 23:17:37 +00005192 // We'll complain below about a non-integral condition type.
5193 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005194
Douglas Gregorc30614b2010-06-29 23:17:37 +00005195 case 1: {
5196 // Apply this conversion.
5197 DeclAccessPair Found = ViableConversions[0];
5198 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005199
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005200 CXXConversionDecl *Conversion
5201 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5202 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005203 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005204 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005205 if (isSFINAEContext())
5206 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005207
Douglas Gregorab41fe92012-05-04 22:38:52 +00005208 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5209 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005211
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005212 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5213 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005214 if (Result.isInvalid())
5215 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005216 // Record usage of conversion in an implicit cast.
5217 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5218 CK_UserDefinedConversion,
5219 Result.get(), 0,
5220 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005221 break;
5222 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223
Douglas Gregorc30614b2010-06-29 23:17:37 +00005224 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005225 if (Diagnoser.Suppress)
5226 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005227
Douglas Gregorab41fe92012-05-04 22:38:52 +00005228 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005229 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5230 CXXConversionDecl *Conv
5231 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5232 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005233 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005234 }
John McCall9ae2f072010-08-23 23:25:46 +00005235 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005236 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005237
Richard Smith282e7e62012-02-04 09:53:13 +00005238 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005239 !Diagnoser.Suppress) {
5240 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5241 << From->getSourceRange();
5242 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005243
Eli Friedmanceccab92012-01-26 00:26:18 +00005244 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005245}
5246
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005247/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005248/// candidate functions, using the given function call arguments. If
5249/// @p SuppressUserConversions, then don't allow user-defined
5250/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005251///
James Dennett699c9042012-06-15 07:13:21 +00005252/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005253/// based on an incomplete set of function arguments. This feature is used by
5254/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005255void
5256Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005257 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005258 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005259 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005260 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005261 bool PartialOverloading,
5262 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005263 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005264 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005265 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005266 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005267 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Douglas Gregor88a35142008-12-22 05:46:06 +00005269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005270 if (!isa<CXXConstructorDecl>(Method)) {
5271 // If we get here, it's because we're calling a member function
5272 // that is named without a member access expression (e.g.,
5273 // "this->f") that was either written explicitly or created
5274 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005275 // function, e.g., X::f(). We use an empty type for the implied
5276 // object argument (C++ [over.call.func]p3), and the acting context
5277 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005278 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005279 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005280 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005281 return;
5282 }
5283 // We treat a constructor like a non-member function, since its object
5284 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005285 }
5286
Douglas Gregorfd476482009-11-13 23:59:09 +00005287 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005288 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005289
Douglas Gregor7edfb692009-11-23 12:27:39 +00005290 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005291 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005292
Douglas Gregor66724ea2009-11-14 01:20:54 +00005293 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5294 // C++ [class.copy]p3:
5295 // A member function template is never instantiated to perform the copy
5296 // of a class object to an object of its class type.
5297 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005298 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005299 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005300 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5301 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005302 return;
5303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005304
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005305 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005306 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005307 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005308 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005309 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005310 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005311 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005312 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005313
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005314 unsigned NumArgsInProto = Proto->getNumArgs();
5315
5316 // (C++ 13.3.2p2): A candidate function having fewer than m
5317 // parameters is viable only if it has an ellipsis in its parameter
5318 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005319 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005320 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005321 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005322 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005323 return;
5324 }
5325
5326 // (C++ 13.3.2p2): A candidate function having more than m parameters
5327 // is viable only if the (m+1)st parameter has a default argument
5328 // (8.3.6). For the purposes of overload resolution, the
5329 // parameter list is truncated on the right, so that there are
5330 // exactly m parameters.
5331 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005332 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005333 // Not enough arguments.
5334 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005335 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005336 return;
5337 }
5338
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005339 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005340 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005341 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5342 if (CheckCUDATarget(Caller, Function)) {
5343 Candidate.Viable = false;
5344 Candidate.FailureKind = ovl_fail_bad_target;
5345 return;
5346 }
5347
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005348 // Determine the implicit conversion sequences for each of the
5349 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005350 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005351 if (ArgIdx < NumArgsInProto) {
5352 // (C++ 13.3.2p3): for F to be a viable function, there shall
5353 // exist for each argument an implicit conversion sequence
5354 // (13.3.3.1) that converts that argument to the corresponding
5355 // parameter of F.
5356 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005357 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005358 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005359 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005360 /*InOverloadResolution=*/true,
5361 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005362 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005363 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005364 if (Candidate.Conversions[ArgIdx].isBad()) {
5365 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005366 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005367 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005368 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005369 } else {
5370 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5371 // argument for which there is no corresponding parameter is
5372 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005373 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005374 }
5375 }
5376}
5377
Douglas Gregor063daf62009-03-13 18:40:31 +00005378/// \brief Add all of the function declarations in the given function set to
5379/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005380void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005381 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005382 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005383 bool SuppressUserConversions,
5384 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005385 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005386 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5387 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005388 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005389 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005390 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005391 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005392 Args.slice(1), CandidateSet,
5393 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005394 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005395 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005396 SuppressUserConversions);
5397 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005398 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005399 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5400 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005401 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005402 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005403 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005404 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005405 Args[0]->Classify(Context), Args.slice(1),
5406 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005407 else
John McCall9aa472c2010-03-19 07:35:19 +00005408 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005409 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005410 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005411 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005412 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005413}
5414
John McCall314be4e2009-11-17 07:50:12 +00005415/// AddMethodCandidate - Adds a named decl (which is some kind of
5416/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005417void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005418 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005419 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005420 Expr **Args, unsigned NumArgs,
5421 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005422 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005423 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005424 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005425
5426 if (isa<UsingShadowDecl>(Decl))
5427 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005428
John McCall314be4e2009-11-17 07:50:12 +00005429 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5430 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5431 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005432 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5433 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005434 ObjectType, ObjectClassification,
5435 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005436 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005437 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005438 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005439 ObjectType, ObjectClassification,
5440 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005441 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005442 }
5443}
5444
Douglas Gregor96176b32008-11-18 23:14:02 +00005445/// AddMethodCandidate - Adds the given C++ member function to the set
5446/// of candidate functions, using the given function call arguments
5447/// and the object argument (@c Object). For example, in a call
5448/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5449/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5450/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005451/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005452void
John McCall9aa472c2010-03-19 07:35:19 +00005453Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005454 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005455 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005456 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005457 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005458 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005459 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005460 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005461 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005462 assert(!isa<CXXConstructorDecl>(Method) &&
5463 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005464
Douglas Gregor3f396022009-09-28 04:47:19 +00005465 if (!CandidateSet.isNewCandidate(Method))
5466 return;
5467
Douglas Gregor7edfb692009-11-23 12:27:39 +00005468 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005469 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005470
Douglas Gregor96176b32008-11-18 23:14:02 +00005471 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005472 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005473 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005474 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005475 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005476 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005477 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005478
5479 unsigned NumArgsInProto = Proto->getNumArgs();
5480
5481 // (C++ 13.3.2p2): A candidate function having fewer than m
5482 // parameters is viable only if it has an ellipsis in its parameter
5483 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005484 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005485 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005486 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005487 return;
5488 }
5489
5490 // (C++ 13.3.2p2): A candidate function having more than m parameters
5491 // is viable only if the (m+1)st parameter has a default argument
5492 // (8.3.6). For the purposes of overload resolution, the
5493 // parameter list is truncated on the right, so that there are
5494 // exactly m parameters.
5495 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005496 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005497 // Not enough arguments.
5498 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005499 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005500 return;
5501 }
5502
5503 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005504
John McCall701c89e2009-12-03 04:06:58 +00005505 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005506 // The implicit object argument is ignored.
5507 Candidate.IgnoreObjectArgument = true;
5508 else {
5509 // Determine the implicit conversion sequence for the object
5510 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005511 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005512 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5513 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005514 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005515 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005516 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005517 return;
5518 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005519 }
5520
5521 // Determine the implicit conversion sequences for each of the
5522 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005523 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005524 if (ArgIdx < NumArgsInProto) {
5525 // (C++ 13.3.2p3): for F to be a viable function, there shall
5526 // exist for each argument an implicit conversion sequence
5527 // (13.3.3.1) that converts that argument to the corresponding
5528 // parameter of F.
5529 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005530 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005531 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005533 /*InOverloadResolution=*/true,
5534 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005535 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005536 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005537 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005538 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005539 break;
5540 }
5541 } else {
5542 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5543 // argument for which there is no corresponding parameter is
5544 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005545 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005546 }
5547 }
5548}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005549
Douglas Gregor6b906862009-08-21 00:16:32 +00005550/// \brief Add a C++ member function template as a candidate to the candidate
5551/// set, using template argument deduction to produce an appropriate member
5552/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005553void
Douglas Gregor6b906862009-08-21 00:16:32 +00005554Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005555 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005556 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005557 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005558 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005559 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005560 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005561 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005562 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005563 if (!CandidateSet.isNewCandidate(MethodTmpl))
5564 return;
5565
Douglas Gregor6b906862009-08-21 00:16:32 +00005566 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005567 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005568 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005569 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005570 // candidate functions in the usual way.113) A given name can refer to one
5571 // or more function templates and also to a set of overloaded non-template
5572 // functions. In such a case, the candidate functions generated from each
5573 // function template are combined with the set of non-template candidate
5574 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005575 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005576 FunctionDecl *Specialization = 0;
5577 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005578 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5579 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005580 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005581 Candidate.FoundDecl = FoundDecl;
5582 Candidate.Function = MethodTmpl->getTemplatedDecl();
5583 Candidate.Viable = false;
5584 Candidate.FailureKind = ovl_fail_bad_deduction;
5585 Candidate.IsSurrogate = false;
5586 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005587 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005588 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005589 Info);
5590 return;
5591 }
Mike Stump1eb44332009-09-09 15:08:12 +00005592
Douglas Gregor6b906862009-08-21 00:16:32 +00005593 // Add the function template specialization produced by template argument
5594 // deduction as a candidate.
5595 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005596 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005597 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005598 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005599 ActingContext, ObjectType, ObjectClassification, Args,
5600 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005601}
5602
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005603/// \brief Add a C++ function template specialization as a candidate
5604/// in the candidate set, using template argument deduction to produce
5605/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005606void
Douglas Gregore53060f2009-06-25 22:08:12 +00005607Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005608 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005609 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005610 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005611 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005612 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005613 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5614 return;
5615
Douglas Gregore53060f2009-06-25 22:08:12 +00005616 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005617 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005618 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005619 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005620 // candidate functions in the usual way.113) A given name can refer to one
5621 // or more function templates and also to a set of overloaded non-template
5622 // functions. In such a case, the candidate functions generated from each
5623 // function template are combined with the set of non-template candidate
5624 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005625 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005626 FunctionDecl *Specialization = 0;
5627 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005628 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5629 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005630 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005631 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005632 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5633 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005634 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005635 Candidate.IsSurrogate = false;
5636 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005637 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005638 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005639 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005640 return;
5641 }
Mike Stump1eb44332009-09-09 15:08:12 +00005642
Douglas Gregore53060f2009-06-25 22:08:12 +00005643 // Add the function template specialization produced by template argument
5644 // deduction as a candidate.
5645 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005646 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005647 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005648}
Mike Stump1eb44332009-09-09 15:08:12 +00005649
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005650/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005651/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005652/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005653/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005654/// (which may or may not be the same type as the type that the
5655/// conversion function produces).
5656void
5657Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005658 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005659 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005660 Expr *From, QualType ToType,
5661 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005662 assert(!Conversion->getDescribedFunctionTemplate() &&
5663 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005664 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005665 if (!CandidateSet.isNewCandidate(Conversion))
5666 return;
5667
Douglas Gregor7edfb692009-11-23 12:27:39 +00005668 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005669 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005670
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005671 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005672 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005673 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005674 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005675 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005676 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005677 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005678 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005679 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005680 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005681 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005682
Douglas Gregorbca39322010-08-19 15:37:02 +00005683 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005684 // For conversion functions, the function is considered to be a member of
5685 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005686 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005687 //
5688 // Determine the implicit conversion sequence for the implicit
5689 // object parameter.
5690 QualType ImplicitParamType = From->getType();
5691 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5692 ImplicitParamType = FromPtrType->getPointeeType();
5693 CXXRecordDecl *ConversionContext
5694 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005695
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005696 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005697 = TryObjectArgumentInitialization(*this, From->getType(),
5698 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005699 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005700
John McCall1d318332010-01-12 00:44:57 +00005701 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005702 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005703 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005704 return;
5705 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005706
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005707 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005708 // derived to base as such conversions are given Conversion Rank. They only
5709 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5710 QualType FromCanon
5711 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5712 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5713 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5714 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005715 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005716 return;
5717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005718
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005719 // To determine what the conversion from the result of calling the
5720 // conversion function to the type we're eventually trying to
5721 // convert to (ToType), we need to synthesize a call to the
5722 // conversion function and attempt copy initialization from it. This
5723 // makes sure that we get the right semantics with respect to
5724 // lvalues/rvalues and the type. Fortunately, we can allocate this
5725 // call on the stack and we don't need its arguments to be
5726 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005727 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005728 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005729 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5730 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005731 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005732 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005733
Richard Smith87c1f1f2011-07-13 22:53:21 +00005734 QualType ConversionType = Conversion->getConversionType();
5735 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005736 Candidate.Viable = false;
5737 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5738 return;
5739 }
5740
Richard Smith87c1f1f2011-07-13 22:53:21 +00005741 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005742
Mike Stump1eb44332009-09-09 15:08:12 +00005743 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005744 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5745 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005746 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005747 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005748 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005749 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005750 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005751 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005752 /*InOverloadResolution=*/false,
5753 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005754
John McCall1d318332010-01-12 00:44:57 +00005755 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005756 case ImplicitConversionSequence::StandardConversion:
5757 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005758
Douglas Gregorc520c842010-04-12 23:42:09 +00005759 // C++ [over.ics.user]p3:
5760 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005761 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005762 // shall have exact match rank.
5763 if (Conversion->getPrimaryTemplate() &&
5764 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5765 Candidate.Viable = false;
5766 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005768
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005769 // C++0x [dcl.init.ref]p5:
5770 // In the second case, if the reference is an rvalue reference and
5771 // the second standard conversion sequence of the user-defined
5772 // conversion sequence includes an lvalue-to-rvalue conversion, the
5773 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005774 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005775 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5776 Candidate.Viable = false;
5777 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5778 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005779 break;
5780
5781 case ImplicitConversionSequence::BadConversion:
5782 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005783 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005784 break;
5785
5786 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005787 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005788 "Can only end up with a standard conversion sequence or failure");
5789 }
5790}
5791
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005792/// \brief Adds a conversion function template specialization
5793/// candidate to the overload set, using template argument deduction
5794/// to deduce the template arguments of the conversion function
5795/// template from the type that we are converting to (C++
5796/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005797void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005798Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005799 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005800 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005801 Expr *From, QualType ToType,
5802 OverloadCandidateSet &CandidateSet) {
5803 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5804 "Only conversion function templates permitted here");
5805
Douglas Gregor3f396022009-09-28 04:47:19 +00005806 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5807 return;
5808
Craig Topper93e45992012-09-19 02:26:47 +00005809 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005810 CXXConversionDecl *Specialization = 0;
5811 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005812 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005813 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005814 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005815 Candidate.FoundDecl = FoundDecl;
5816 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5817 Candidate.Viable = false;
5818 Candidate.FailureKind = ovl_fail_bad_deduction;
5819 Candidate.IsSurrogate = false;
5820 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005821 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005822 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005823 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005824 return;
5825 }
Mike Stump1eb44332009-09-09 15:08:12 +00005826
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005827 // Add the conversion function template specialization produced by
5828 // template argument deduction as a candidate.
5829 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005830 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005831 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005832}
5833
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005834/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5835/// converts the given @c Object to a function pointer via the
5836/// conversion function @c Conversion, and then attempts to call it
5837/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5838/// the type of function that we'll eventually be calling.
5839void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005840 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005841 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005842 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005843 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005844 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005845 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005846 if (!CandidateSet.isNewCandidate(Conversion))
5847 return;
5848
Douglas Gregor7edfb692009-11-23 12:27:39 +00005849 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005850 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005851
Ahmed Charles13a140c2012-02-25 11:00:22 +00005852 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005853 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005854 Candidate.Function = 0;
5855 Candidate.Surrogate = Conversion;
5856 Candidate.Viable = true;
5857 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005858 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005859 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005860
5861 // Determine the implicit conversion sequence for the implicit
5862 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005863 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005865 Object->Classify(Context),
5866 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005867 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005868 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005869 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005870 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005871 return;
5872 }
5873
5874 // The first conversion is actually a user-defined conversion whose
5875 // first conversion is ObjectInit's standard conversion (which is
5876 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005877 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005878 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005879 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005880 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005881 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005882 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005883 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005884 = Candidate.Conversions[0].UserDefined.Before;
5885 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5886
Mike Stump1eb44332009-09-09 15:08:12 +00005887 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005888 unsigned NumArgsInProto = Proto->getNumArgs();
5889
5890 // (C++ 13.3.2p2): A candidate function having fewer than m
5891 // parameters is viable only if it has an ellipsis in its parameter
5892 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005893 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005894 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005895 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005896 return;
5897 }
5898
5899 // Function types don't have any default arguments, so just check if
5900 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005901 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005902 // Not enough arguments.
5903 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005904 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005905 return;
5906 }
5907
5908 // Determine the implicit conversion sequences for each of the
5909 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005910 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005911 if (ArgIdx < NumArgsInProto) {
5912 // (C++ 13.3.2p3): for F to be a viable function, there shall
5913 // exist for each argument an implicit conversion sequence
5914 // (13.3.3.1) that converts that argument to the corresponding
5915 // parameter of F.
5916 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005917 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005918 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005919 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005920 /*InOverloadResolution=*/false,
5921 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005922 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005923 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005924 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005925 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005926 break;
5927 }
5928 } else {
5929 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5930 // argument for which there is no corresponding parameter is
5931 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005932 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005933 }
5934 }
5935}
5936
Douglas Gregor063daf62009-03-13 18:40:31 +00005937/// \brief Add overload candidates for overloaded operators that are
5938/// member functions.
5939///
5940/// Add the overloaded operator candidates that are member functions
5941/// for the operator Op that was used in an operator expression such
5942/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5943/// CandidateSet will store the added overload candidates. (C++
5944/// [over.match.oper]).
5945void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5946 SourceLocation OpLoc,
5947 Expr **Args, unsigned NumArgs,
5948 OverloadCandidateSet& CandidateSet,
5949 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005950 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5951
5952 // C++ [over.match.oper]p3:
5953 // For a unary operator @ with an operand of a type whose
5954 // cv-unqualified version is T1, and for a binary operator @ with
5955 // a left operand of a type whose cv-unqualified version is T1 and
5956 // a right operand of a type whose cv-unqualified version is T2,
5957 // three sets of candidate functions, designated member
5958 // candidates, non-member candidates and built-in candidates, are
5959 // constructed as follows:
5960 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005961
5962 // -- If T1 is a class type, the set of member candidates is the
5963 // result of the qualified lookup of T1::operator@
5964 // (13.3.1.1.1); otherwise, the set of member candidates is
5965 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005966 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005967 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005968 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005969 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005970
John McCalla24dc2e2009-11-17 02:14:36 +00005971 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5972 LookupQualifiedName(Operators, T1Rec->getDecl());
5973 Operators.suppressDiagnostics();
5974
Mike Stump1eb44332009-09-09 15:08:12 +00005975 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005976 OperEnd = Operators.end();
5977 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005978 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005979 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005980 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005981 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005982 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005983 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005984}
5985
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005986/// AddBuiltinCandidate - Add a candidate for a built-in
5987/// operator. ResultTy and ParamTys are the result and parameter types
5988/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005989/// arguments being passed to the candidate. IsAssignmentOperator
5990/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005991/// operator. NumContextualBoolArguments is the number of arguments
5992/// (at the beginning of the argument list) that will be contextually
5993/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005994void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005995 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005996 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005997 bool IsAssignmentOperator,
5998 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005999 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006000 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006001
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006002 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006003 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006004 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006005 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006006 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006007 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006008 Candidate.BuiltinTypes.ResultTy = ResultTy;
6009 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6010 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6011
6012 // Determine the implicit conversion sequences for each of the
6013 // arguments.
6014 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006015 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006016 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006017 // C++ [over.match.oper]p4:
6018 // For the built-in assignment operators, conversions of the
6019 // left operand are restricted as follows:
6020 // -- no temporaries are introduced to hold the left operand, and
6021 // -- no user-defined conversions are applied to the left
6022 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006023 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006024 //
6025 // We block these conversions by turning off user-defined
6026 // conversions, since that is the only way that initialization of
6027 // a reference to a non-class type can occur from something that
6028 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006029 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006030 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006031 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006032 Candidate.Conversions[ArgIdx]
6033 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006034 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006035 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006036 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006037 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006038 /*InOverloadResolution=*/false,
6039 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006040 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006041 }
John McCall1d318332010-01-12 00:44:57 +00006042 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006043 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006044 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006045 break;
6046 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006047 }
6048}
6049
6050/// BuiltinCandidateTypeSet - A set of types that will be used for the
6051/// candidate operator functions for built-in operators (C++
6052/// [over.built]). The types are separated into pointer types and
6053/// enumeration types.
6054class BuiltinCandidateTypeSet {
6055 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006056 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006057
6058 /// PointerTypes - The set of pointer types that will be used in the
6059 /// built-in candidates.
6060 TypeSet PointerTypes;
6061
Sebastian Redl78eb8742009-04-19 21:53:20 +00006062 /// MemberPointerTypes - The set of member pointer types that will be
6063 /// used in the built-in candidates.
6064 TypeSet MemberPointerTypes;
6065
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006066 /// EnumerationTypes - The set of enumeration types that will be
6067 /// used in the built-in candidates.
6068 TypeSet EnumerationTypes;
6069
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006070 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006071 /// candidates.
6072 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006073
6074 /// \brief A flag indicating non-record types are viable candidates
6075 bool HasNonRecordTypes;
6076
6077 /// \brief A flag indicating whether either arithmetic or enumeration types
6078 /// were present in the candidate set.
6079 bool HasArithmeticOrEnumeralTypes;
6080
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006081 /// \brief A flag indicating whether the nullptr type was present in the
6082 /// candidate set.
6083 bool HasNullPtrType;
6084
Douglas Gregor5842ba92009-08-24 15:23:48 +00006085 /// Sema - The semantic analysis instance where we are building the
6086 /// candidate type set.
6087 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006088
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006089 /// Context - The AST context in which we will build the type sets.
6090 ASTContext &Context;
6091
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006092 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6093 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006094 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095
6096public:
6097 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006098 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006099
Mike Stump1eb44332009-09-09 15:08:12 +00006100 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006101 : HasNonRecordTypes(false),
6102 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006103 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006104 SemaRef(SemaRef),
6105 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006106
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006107 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006108 SourceLocation Loc,
6109 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006110 bool AllowExplicitConversions,
6111 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006112
6113 /// pointer_begin - First pointer type found;
6114 iterator pointer_begin() { return PointerTypes.begin(); }
6115
Sebastian Redl78eb8742009-04-19 21:53:20 +00006116 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006117 iterator pointer_end() { return PointerTypes.end(); }
6118
Sebastian Redl78eb8742009-04-19 21:53:20 +00006119 /// member_pointer_begin - First member pointer type found;
6120 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6121
6122 /// member_pointer_end - Past the last member pointer type found;
6123 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6124
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006125 /// enumeration_begin - First enumeration type found;
6126 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6127
Sebastian Redl78eb8742009-04-19 21:53:20 +00006128 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006129 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006130
Douglas Gregor26bcf672010-05-19 03:21:00 +00006131 iterator vector_begin() { return VectorTypes.begin(); }
6132 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006133
6134 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6135 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006136 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006137};
6138
Sebastian Redl78eb8742009-04-19 21:53:20 +00006139/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006140/// the set of pointer types along with any more-qualified variants of
6141/// that type. For example, if @p Ty is "int const *", this routine
6142/// will add "int const *", "int const volatile *", "int const
6143/// restrict *", and "int const volatile restrict *" to the set of
6144/// pointer types. Returns true if the add of @p Ty itself succeeded,
6145/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006146///
6147/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006148bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006149BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6150 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006151
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006152 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006153 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006154 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006155
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006156 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006157 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006158 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006159 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006160 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6161 PointeeTy = PTy->getPointeeType();
6162 buildObjCPtr = true;
6163 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006164 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006165 }
6166
Sebastian Redla9efada2009-11-18 20:39:26 +00006167 // Don't add qualified variants of arrays. For one, they're not allowed
6168 // (the qualifier would sink to the element type), and for another, the
6169 // only overload situation where it matters is subscript or pointer +- int,
6170 // and those shouldn't have qualifier variants anyway.
6171 if (PointeeTy->isArrayType())
6172 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006173
John McCall0953e762009-09-24 19:53:00 +00006174 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006175 bool hasVolatile = VisibleQuals.hasVolatile();
6176 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006177
John McCall0953e762009-09-24 19:53:00 +00006178 // Iterate through all strict supersets of BaseCVR.
6179 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6180 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006181 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006182 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006183
6184 // Skip over restrict if no restrict found anywhere in the types, or if
6185 // the type cannot be restrict-qualified.
6186 if ((CVR & Qualifiers::Restrict) &&
6187 (!hasRestrict ||
6188 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6189 continue;
6190
6191 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006192 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006193
6194 // Build qualified pointer type.
6195 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006196 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006197 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006198 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006199 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6200
6201 // Insert qualified pointer type.
6202 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006203 }
6204
6205 return true;
6206}
6207
Sebastian Redl78eb8742009-04-19 21:53:20 +00006208/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6209/// to the set of pointer types along with any more-qualified variants of
6210/// that type. For example, if @p Ty is "int const *", this routine
6211/// will add "int const *", "int const volatile *", "int const
6212/// restrict *", and "int const volatile restrict *" to the set of
6213/// pointer types. Returns true if the add of @p Ty itself succeeded,
6214/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006215///
6216/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006217bool
6218BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6219 QualType Ty) {
6220 // Insert this type.
6221 if (!MemberPointerTypes.insert(Ty))
6222 return false;
6223
John McCall0953e762009-09-24 19:53:00 +00006224 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6225 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006226
John McCall0953e762009-09-24 19:53:00 +00006227 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006228 // Don't add qualified variants of arrays. For one, they're not allowed
6229 // (the qualifier would sink to the element type), and for another, the
6230 // only overload situation where it matters is subscript or pointer +- int,
6231 // and those shouldn't have qualifier variants anyway.
6232 if (PointeeTy->isArrayType())
6233 return true;
John McCall0953e762009-09-24 19:53:00 +00006234 const Type *ClassTy = PointerTy->getClass();
6235
6236 // Iterate through all strict supersets of the pointee type's CVR
6237 // qualifiers.
6238 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6239 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6240 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006241
John McCall0953e762009-09-24 19:53:00 +00006242 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006243 MemberPointerTypes.insert(
6244 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006245 }
6246
6247 return true;
6248}
6249
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006250/// AddTypesConvertedFrom - Add each of the types to which the type @p
6251/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006252/// primarily interested in pointer types and enumeration types. We also
6253/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006254/// AllowUserConversions is true if we should look at the conversion
6255/// functions of a class type, and AllowExplicitConversions if we
6256/// should also include the explicit conversion functions of a class
6257/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006258void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006259BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006260 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006261 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006262 bool AllowExplicitConversions,
6263 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006264 // Only deal with canonical types.
6265 Ty = Context.getCanonicalType(Ty);
6266
6267 // Look through reference types; they aren't part of the type of an
6268 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006269 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006270 Ty = RefTy->getPointeeType();
6271
John McCall3b657512011-01-19 10:06:00 +00006272 // If we're dealing with an array type, decay to the pointer.
6273 if (Ty->isArrayType())
6274 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6275
6276 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006277 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006278
Chandler Carruth6a577462010-12-13 01:44:01 +00006279 // Flag if we ever add a non-record type.
6280 const RecordType *TyRec = Ty->getAs<RecordType>();
6281 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6282
Chandler Carruth6a577462010-12-13 01:44:01 +00006283 // Flag if we encounter an arithmetic type.
6284 HasArithmeticOrEnumeralTypes =
6285 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6286
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006287 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6288 PointerTypes.insert(Ty);
6289 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006290 // Insert our type, and its more-qualified variants, into the set
6291 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006292 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006293 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006294 } else if (Ty->isMemberPointerType()) {
6295 // Member pointers are far easier, since the pointee can't be converted.
6296 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6297 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006298 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006299 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006300 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006301 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006302 // We treat vector types as arithmetic types in many contexts as an
6303 // extension.
6304 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006305 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006306 } else if (Ty->isNullPtrType()) {
6307 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006308 } else if (AllowUserConversions && TyRec) {
6309 // No conversion functions in incomplete types.
6310 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6311 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006312
Chandler Carruth6a577462010-12-13 01:44:01 +00006313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006314 std::pair<CXXRecordDecl::conversion_iterator,
6315 CXXRecordDecl::conversion_iterator>
6316 Conversions = ClassDecl->getVisibleConversionFunctions();
6317 for (CXXRecordDecl::conversion_iterator
6318 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006319 NamedDecl *D = I.getDecl();
6320 if (isa<UsingShadowDecl>(D))
6321 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006322
Chandler Carruth6a577462010-12-13 01:44:01 +00006323 // Skip conversion function templates; they don't tell us anything
6324 // about which builtin types we can convert to.
6325 if (isa<FunctionTemplateDecl>(D))
6326 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006327
Chandler Carruth6a577462010-12-13 01:44:01 +00006328 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6329 if (AllowExplicitConversions || !Conv->isExplicit()) {
6330 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6331 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006332 }
6333 }
6334 }
6335}
6336
Douglas Gregor19b7b152009-08-24 13:43:27 +00006337/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6338/// the volatile- and non-volatile-qualified assignment operators for the
6339/// given type to the candidate set.
6340static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6341 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006342 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006343 unsigned NumArgs,
6344 OverloadCandidateSet &CandidateSet) {
6345 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006346
Douglas Gregor19b7b152009-08-24 13:43:27 +00006347 // T& operator=(T&, T)
6348 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6349 ParamTypes[1] = T;
6350 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6351 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006352
Douglas Gregor19b7b152009-08-24 13:43:27 +00006353 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6354 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006355 ParamTypes[0]
6356 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006357 ParamTypes[1] = T;
6358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006359 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006360 }
6361}
Mike Stump1eb44332009-09-09 15:08:12 +00006362
Sebastian Redl9994a342009-10-25 17:03:50 +00006363/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6364/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006365static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6366 Qualifiers VRQuals;
6367 const RecordType *TyRec;
6368 if (const MemberPointerType *RHSMPType =
6369 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006370 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006371 else
6372 TyRec = ArgExpr->getType()->getAs<RecordType>();
6373 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006374 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006375 VRQuals.addVolatile();
6376 VRQuals.addRestrict();
6377 return VRQuals;
6378 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006379
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006380 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006381 if (!ClassDecl->hasDefinition())
6382 return VRQuals;
6383
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006384 std::pair<CXXRecordDecl::conversion_iterator,
6385 CXXRecordDecl::conversion_iterator>
6386 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006387
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006388 for (CXXRecordDecl::conversion_iterator
6389 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006390 NamedDecl *D = I.getDecl();
6391 if (isa<UsingShadowDecl>(D))
6392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6393 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006394 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6395 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6396 CanTy = ResTypeRef->getPointeeType();
6397 // Need to go down the pointer/mempointer chain and add qualifiers
6398 // as see them.
6399 bool done = false;
6400 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006401 if (CanTy.isRestrictQualified())
6402 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006403 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6404 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006405 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006406 CanTy->getAs<MemberPointerType>())
6407 CanTy = ResTypeMPtr->getPointeeType();
6408 else
6409 done = true;
6410 if (CanTy.isVolatileQualified())
6411 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006412 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6413 return VRQuals;
6414 }
6415 }
6416 }
6417 return VRQuals;
6418}
John McCall00071ec2010-11-13 05:51:15 +00006419
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006420namespace {
John McCall00071ec2010-11-13 05:51:15 +00006421
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006422/// \brief Helper class to manage the addition of builtin operator overload
6423/// candidates. It provides shared state and utility methods used throughout
6424/// the process, as well as a helper method to add each group of builtin
6425/// operator overloads from the standard to a candidate set.
6426class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006427 // Common instance state available to all overload candidate addition methods.
6428 Sema &S;
6429 Expr **Args;
6430 unsigned NumArgs;
6431 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006432 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006433 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006434 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006435
Chandler Carruth6d695582010-12-12 10:35:00 +00006436 // Define some constants used to index and iterate over the arithemetic types
6437 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006438 // The "promoted arithmetic types" are the arithmetic
6439 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006440 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006441 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006442 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006443 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006444 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006445 LastPromotedArithmeticType = 11;
6446 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006447
Chandler Carruth6d695582010-12-12 10:35:00 +00006448 /// \brief Get the canonical type for a given arithmetic type index.
6449 CanQualType getArithmeticType(unsigned index) {
6450 assert(index < NumArithmeticTypes);
6451 static CanQualType ASTContext::* const
6452 ArithmeticTypes[NumArithmeticTypes] = {
6453 // Start of promoted types.
6454 &ASTContext::FloatTy,
6455 &ASTContext::DoubleTy,
6456 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006457
Chandler Carruth6d695582010-12-12 10:35:00 +00006458 // Start of integral types.
6459 &ASTContext::IntTy,
6460 &ASTContext::LongTy,
6461 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006462 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006463 &ASTContext::UnsignedIntTy,
6464 &ASTContext::UnsignedLongTy,
6465 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006466 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006467 // End of promoted types.
6468
6469 &ASTContext::BoolTy,
6470 &ASTContext::CharTy,
6471 &ASTContext::WCharTy,
6472 &ASTContext::Char16Ty,
6473 &ASTContext::Char32Ty,
6474 &ASTContext::SignedCharTy,
6475 &ASTContext::ShortTy,
6476 &ASTContext::UnsignedCharTy,
6477 &ASTContext::UnsignedShortTy,
6478 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006479 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006480 };
6481 return S.Context.*ArithmeticTypes[index];
6482 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006483
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006484 /// \brief Gets the canonical type resulting from the usual arithemetic
6485 /// converions for the given arithmetic types.
6486 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6487 // Accelerator table for performing the usual arithmetic conversions.
6488 // The rules are basically:
6489 // - if either is floating-point, use the wider floating-point
6490 // - if same signedness, use the higher rank
6491 // - if same size, use unsigned of the higher rank
6492 // - use the larger type
6493 // These rules, together with the axiom that higher ranks are
6494 // never smaller, are sufficient to precompute all of these results
6495 // *except* when dealing with signed types of higher rank.
6496 // (we could precompute SLL x UI for all known platforms, but it's
6497 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006498 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006499 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006500 Dep=-1,
6501 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006502 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006503 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006504 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006505/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6506/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6507/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6508/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6509/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6510/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6511/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6512/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6513/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6514/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6515/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006516 };
6517
6518 assert(L < LastPromotedArithmeticType);
6519 assert(R < LastPromotedArithmeticType);
6520 int Idx = ConversionsTable[L][R];
6521
6522 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006523 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006524
6525 // Slow path: we need to compare widths.
6526 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006527 CanQualType LT = getArithmeticType(L),
6528 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006529 unsigned LW = S.Context.getIntWidth(LT),
6530 RW = S.Context.getIntWidth(RT);
6531
6532 // If they're different widths, use the signed type.
6533 if (LW > RW) return LT;
6534 else if (LW < RW) return RT;
6535
6536 // Otherwise, use the unsigned type of the signed type's rank.
6537 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6538 assert(L == SLL || R == SLL);
6539 return S.Context.UnsignedLongLongTy;
6540 }
6541
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006542 /// \brief Helper method to factor out the common pattern of adding overloads
6543 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006544 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006545 bool HasVolatile,
6546 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006547 QualType ParamTypes[2] = {
6548 S.Context.getLValueReferenceType(CandidateTy),
6549 S.Context.IntTy
6550 };
6551
6552 // Non-volatile version.
6553 if (NumArgs == 1)
6554 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6555 else
6556 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6557
6558 // Use a heuristic to reduce number of builtin candidates in the set:
6559 // add volatile version only if there are conversions to a volatile type.
6560 if (HasVolatile) {
6561 ParamTypes[0] =
6562 S.Context.getLValueReferenceType(
6563 S.Context.getVolatileType(CandidateTy));
6564 if (NumArgs == 1)
6565 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6566 else
6567 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6568 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006569
6570 // Add restrict version only if there are conversions to a restrict type
6571 // and our candidate type is a non-restrict-qualified pointer.
6572 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6573 !CandidateTy.isRestrictQualified()) {
6574 ParamTypes[0]
6575 = S.Context.getLValueReferenceType(
6576 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6577 if (NumArgs == 1)
6578 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6579 else
6580 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6581
6582 if (HasVolatile) {
6583 ParamTypes[0]
6584 = S.Context.getLValueReferenceType(
6585 S.Context.getCVRQualifiedType(CandidateTy,
6586 (Qualifiers::Volatile |
6587 Qualifiers::Restrict)));
6588 if (NumArgs == 1)
6589 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6590 CandidateSet);
6591 else
6592 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6593 }
6594 }
6595
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006596 }
6597
6598public:
6599 BuiltinOperatorOverloadBuilder(
6600 Sema &S, Expr **Args, unsigned NumArgs,
6601 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006602 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006603 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006604 OverloadCandidateSet &CandidateSet)
6605 : S(S), Args(Args), NumArgs(NumArgs),
6606 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006607 HasArithmeticOrEnumeralCandidateType(
6608 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006609 CandidateTypes(CandidateTypes),
6610 CandidateSet(CandidateSet) {
6611 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006612 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006613 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006614 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006615 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006616 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006617 assert(getArithmeticType(FirstPromotedArithmeticType)
6618 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006619 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006620 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006621 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006622 "Invalid last promoted arithmetic type");
6623 }
6624
6625 // C++ [over.built]p3:
6626 //
6627 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6628 // is either volatile or empty, there exist candidate operator
6629 // functions of the form
6630 //
6631 // VQ T& operator++(VQ T&);
6632 // T operator++(VQ T&, int);
6633 //
6634 // C++ [over.built]p4:
6635 //
6636 // For every pair (T, VQ), where T is an arithmetic type other
6637 // than bool, and VQ is either volatile or empty, there exist
6638 // candidate operator functions of the form
6639 //
6640 // VQ T& operator--(VQ T&);
6641 // T operator--(VQ T&, int);
6642 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006643 if (!HasArithmeticOrEnumeralCandidateType)
6644 return;
6645
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006646 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6647 Arith < NumArithmeticTypes; ++Arith) {
6648 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006649 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006650 VisibleTypeConversionsQuals.hasVolatile(),
6651 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006652 }
6653 }
6654
6655 // C++ [over.built]p5:
6656 //
6657 // For every pair (T, VQ), where T is a cv-qualified or
6658 // cv-unqualified object type, and VQ is either volatile or
6659 // empty, there exist candidate operator functions of the form
6660 //
6661 // T*VQ& operator++(T*VQ&);
6662 // T*VQ& operator--(T*VQ&);
6663 // T* operator++(T*VQ&, int);
6664 // T* operator--(T*VQ&, int);
6665 void addPlusPlusMinusMinusPointerOverloads() {
6666 for (BuiltinCandidateTypeSet::iterator
6667 Ptr = CandidateTypes[0].pointer_begin(),
6668 PtrEnd = CandidateTypes[0].pointer_end();
6669 Ptr != PtrEnd; ++Ptr) {
6670 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006671 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006672 continue;
6673
6674 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006675 (!(*Ptr).isVolatileQualified() &&
6676 VisibleTypeConversionsQuals.hasVolatile()),
6677 (!(*Ptr).isRestrictQualified() &&
6678 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006679 }
6680 }
6681
6682 // C++ [over.built]p6:
6683 // For every cv-qualified or cv-unqualified object type T, there
6684 // exist candidate operator functions of the form
6685 //
6686 // T& operator*(T*);
6687 //
6688 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006689 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006690 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006691 // T& operator*(T*);
6692 void addUnaryStarPointerOverloads() {
6693 for (BuiltinCandidateTypeSet::iterator
6694 Ptr = CandidateTypes[0].pointer_begin(),
6695 PtrEnd = CandidateTypes[0].pointer_end();
6696 Ptr != PtrEnd; ++Ptr) {
6697 QualType ParamTy = *Ptr;
6698 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006699 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6700 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006701
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006702 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6703 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6704 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006705
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006706 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6707 &ParamTy, Args, 1, CandidateSet);
6708 }
6709 }
6710
6711 // C++ [over.built]p9:
6712 // For every promoted arithmetic type T, there exist candidate
6713 // operator functions of the form
6714 //
6715 // T operator+(T);
6716 // T operator-(T);
6717 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006718 if (!HasArithmeticOrEnumeralCandidateType)
6719 return;
6720
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006721 for (unsigned Arith = FirstPromotedArithmeticType;
6722 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006723 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006724 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6725 }
6726
6727 // Extension: We also add these operators for vector types.
6728 for (BuiltinCandidateTypeSet::iterator
6729 Vec = CandidateTypes[0].vector_begin(),
6730 VecEnd = CandidateTypes[0].vector_end();
6731 Vec != VecEnd; ++Vec) {
6732 QualType VecTy = *Vec;
6733 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6734 }
6735 }
6736
6737 // C++ [over.built]p8:
6738 // For every type T, there exist candidate operator functions of
6739 // the form
6740 //
6741 // T* operator+(T*);
6742 void addUnaryPlusPointerOverloads() {
6743 for (BuiltinCandidateTypeSet::iterator
6744 Ptr = CandidateTypes[0].pointer_begin(),
6745 PtrEnd = CandidateTypes[0].pointer_end();
6746 Ptr != PtrEnd; ++Ptr) {
6747 QualType ParamTy = *Ptr;
6748 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6749 }
6750 }
6751
6752 // C++ [over.built]p10:
6753 // For every promoted integral type T, there exist candidate
6754 // operator functions of the form
6755 //
6756 // T operator~(T);
6757 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006758 if (!HasArithmeticOrEnumeralCandidateType)
6759 return;
6760
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006761 for (unsigned Int = FirstPromotedIntegralType;
6762 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006763 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006764 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6765 }
6766
6767 // Extension: We also add this operator for vector types.
6768 for (BuiltinCandidateTypeSet::iterator
6769 Vec = CandidateTypes[0].vector_begin(),
6770 VecEnd = CandidateTypes[0].vector_end();
6771 Vec != VecEnd; ++Vec) {
6772 QualType VecTy = *Vec;
6773 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6774 }
6775 }
6776
6777 // C++ [over.match.oper]p16:
6778 // For every pointer to member type T, there exist candidate operator
6779 // functions of the form
6780 //
6781 // bool operator==(T,T);
6782 // bool operator!=(T,T);
6783 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6784 /// Set of (canonical) types that we've already handled.
6785 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6786
6787 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6788 for (BuiltinCandidateTypeSet::iterator
6789 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6790 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6791 MemPtr != MemPtrEnd;
6792 ++MemPtr) {
6793 // Don't add the same builtin candidate twice.
6794 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6795 continue;
6796
6797 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6798 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6799 CandidateSet);
6800 }
6801 }
6802 }
6803
6804 // C++ [over.built]p15:
6805 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006806 // For every T, where T is an enumeration type, a pointer type, or
6807 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006808 //
6809 // bool operator<(T, T);
6810 // bool operator>(T, T);
6811 // bool operator<=(T, T);
6812 // bool operator>=(T, T);
6813 // bool operator==(T, T);
6814 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006815 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006816 // C++ [over.match.oper]p3:
6817 // [...]the built-in candidates include all of the candidate operator
6818 // functions defined in 13.6 that, compared to the given operator, [...]
6819 // do not have the same parameter-type-list as any non-template non-member
6820 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006821 //
Eli Friedman97c67392012-09-18 21:52:24 +00006822 // Note that in practice, this only affects enumeration types because there
6823 // aren't any built-in candidates of record type, and a user-defined operator
6824 // must have an operand of record or enumeration type. Also, the only other
6825 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006826 // cannot be overloaded for enumeration types, so this is the only place
6827 // where we must suppress candidates like this.
6828 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6829 UserDefinedBinaryOperators;
6830
6831 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6832 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6833 CandidateTypes[ArgIdx].enumeration_end()) {
6834 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6835 CEnd = CandidateSet.end();
6836 C != CEnd; ++C) {
6837 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6838 continue;
6839
Eli Friedman97c67392012-09-18 21:52:24 +00006840 if (C->Function->isFunctionTemplateSpecialization())
6841 continue;
6842
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006843 QualType FirstParamType =
6844 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6845 QualType SecondParamType =
6846 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6847
6848 // Skip if either parameter isn't of enumeral type.
6849 if (!FirstParamType->isEnumeralType() ||
6850 !SecondParamType->isEnumeralType())
6851 continue;
6852
6853 // Add this operator to the set of known user-defined operators.
6854 UserDefinedBinaryOperators.insert(
6855 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6856 S.Context.getCanonicalType(SecondParamType)));
6857 }
6858 }
6859 }
6860
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006861 /// Set of (canonical) types that we've already handled.
6862 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6863
6864 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6865 for (BuiltinCandidateTypeSet::iterator
6866 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6867 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6868 Ptr != PtrEnd; ++Ptr) {
6869 // Don't add the same builtin candidate twice.
6870 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6871 continue;
6872
6873 QualType ParamTypes[2] = { *Ptr, *Ptr };
6874 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6875 CandidateSet);
6876 }
6877 for (BuiltinCandidateTypeSet::iterator
6878 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6879 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6880 Enum != EnumEnd; ++Enum) {
6881 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6882
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006883 // Don't add the same builtin candidate twice, or if a user defined
6884 // candidate exists.
6885 if (!AddedTypes.insert(CanonType) ||
6886 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6887 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006888 continue;
6889
6890 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006891 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6892 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006893 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006894
6895 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6896 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6897 if (AddedTypes.insert(NullPtrTy) &&
6898 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6899 NullPtrTy))) {
6900 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6901 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6902 CandidateSet);
6903 }
6904 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006905 }
6906 }
6907
6908 // C++ [over.built]p13:
6909 //
6910 // For every cv-qualified or cv-unqualified object type T
6911 // there exist candidate operator functions of the form
6912 //
6913 // T* operator+(T*, ptrdiff_t);
6914 // T& operator[](T*, ptrdiff_t); [BELOW]
6915 // T* operator-(T*, ptrdiff_t);
6916 // T* operator+(ptrdiff_t, T*);
6917 // T& operator[](ptrdiff_t, T*); [BELOW]
6918 //
6919 // C++ [over.built]p14:
6920 //
6921 // For every T, where T is a pointer to object type, there
6922 // exist candidate operator functions of the form
6923 //
6924 // ptrdiff_t operator-(T, T);
6925 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6926 /// Set of (canonical) types that we've already handled.
6927 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6928
6929 for (int Arg = 0; Arg < 2; ++Arg) {
6930 QualType AsymetricParamTypes[2] = {
6931 S.Context.getPointerDiffType(),
6932 S.Context.getPointerDiffType(),
6933 };
6934 for (BuiltinCandidateTypeSet::iterator
6935 Ptr = CandidateTypes[Arg].pointer_begin(),
6936 PtrEnd = CandidateTypes[Arg].pointer_end();
6937 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006938 QualType PointeeTy = (*Ptr)->getPointeeType();
6939 if (!PointeeTy->isObjectType())
6940 continue;
6941
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006942 AsymetricParamTypes[Arg] = *Ptr;
6943 if (Arg == 0 || Op == OO_Plus) {
6944 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6945 // T* operator+(ptrdiff_t, T*);
6946 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6947 CandidateSet);
6948 }
6949 if (Op == OO_Minus) {
6950 // ptrdiff_t operator-(T, T);
6951 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6952 continue;
6953
6954 QualType ParamTypes[2] = { *Ptr, *Ptr };
6955 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6956 Args, 2, CandidateSet);
6957 }
6958 }
6959 }
6960 }
6961
6962 // C++ [over.built]p12:
6963 //
6964 // For every pair of promoted arithmetic types L and R, there
6965 // exist candidate operator functions of the form
6966 //
6967 // LR operator*(L, R);
6968 // LR operator/(L, R);
6969 // LR operator+(L, R);
6970 // LR operator-(L, R);
6971 // bool operator<(L, R);
6972 // bool operator>(L, R);
6973 // bool operator<=(L, R);
6974 // bool operator>=(L, R);
6975 // bool operator==(L, R);
6976 // bool operator!=(L, R);
6977 //
6978 // where LR is the result of the usual arithmetic conversions
6979 // between types L and R.
6980 //
6981 // C++ [over.built]p24:
6982 //
6983 // For every pair of promoted arithmetic types L and R, there exist
6984 // candidate operator functions of the form
6985 //
6986 // LR operator?(bool, L, R);
6987 //
6988 // where LR is the result of the usual arithmetic conversions
6989 // between types L and R.
6990 // Our candidates ignore the first parameter.
6991 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006992 if (!HasArithmeticOrEnumeralCandidateType)
6993 return;
6994
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006995 for (unsigned Left = FirstPromotedArithmeticType;
6996 Left < LastPromotedArithmeticType; ++Left) {
6997 for (unsigned Right = FirstPromotedArithmeticType;
6998 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006999 QualType LandR[2] = { getArithmeticType(Left),
7000 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007001 QualType Result =
7002 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007003 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007004 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7005 }
7006 }
7007
7008 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7009 // conditional operator for vector types.
7010 for (BuiltinCandidateTypeSet::iterator
7011 Vec1 = CandidateTypes[0].vector_begin(),
7012 Vec1End = CandidateTypes[0].vector_end();
7013 Vec1 != Vec1End; ++Vec1) {
7014 for (BuiltinCandidateTypeSet::iterator
7015 Vec2 = CandidateTypes[1].vector_begin(),
7016 Vec2End = CandidateTypes[1].vector_end();
7017 Vec2 != Vec2End; ++Vec2) {
7018 QualType LandR[2] = { *Vec1, *Vec2 };
7019 QualType Result = S.Context.BoolTy;
7020 if (!isComparison) {
7021 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7022 Result = *Vec1;
7023 else
7024 Result = *Vec2;
7025 }
7026
7027 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7028 }
7029 }
7030 }
7031
7032 // C++ [over.built]p17:
7033 //
7034 // For every pair of promoted integral types L and R, there
7035 // exist candidate operator functions of the form
7036 //
7037 // LR operator%(L, R);
7038 // LR operator&(L, R);
7039 // LR operator^(L, R);
7040 // LR operator|(L, R);
7041 // L operator<<(L, R);
7042 // L operator>>(L, R);
7043 //
7044 // where LR is the result of the usual arithmetic conversions
7045 // between types L and R.
7046 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007047 if (!HasArithmeticOrEnumeralCandidateType)
7048 return;
7049
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007050 for (unsigned Left = FirstPromotedIntegralType;
7051 Left < LastPromotedIntegralType; ++Left) {
7052 for (unsigned Right = FirstPromotedIntegralType;
7053 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007054 QualType LandR[2] = { getArithmeticType(Left),
7055 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007056 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7057 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007058 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007059 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7060 }
7061 }
7062 }
7063
7064 // C++ [over.built]p20:
7065 //
7066 // For every pair (T, VQ), where T is an enumeration or
7067 // pointer to member type and VQ is either volatile or
7068 // empty, there exist candidate operator functions of the form
7069 //
7070 // VQ T& operator=(VQ T&, T);
7071 void addAssignmentMemberPointerOrEnumeralOverloads() {
7072 /// Set of (canonical) types that we've already handled.
7073 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7074
7075 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7076 for (BuiltinCandidateTypeSet::iterator
7077 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7078 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7079 Enum != EnumEnd; ++Enum) {
7080 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7081 continue;
7082
7083 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7084 CandidateSet);
7085 }
7086
7087 for (BuiltinCandidateTypeSet::iterator
7088 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7089 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7090 MemPtr != MemPtrEnd; ++MemPtr) {
7091 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7092 continue;
7093
7094 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7095 CandidateSet);
7096 }
7097 }
7098 }
7099
7100 // C++ [over.built]p19:
7101 //
7102 // For every pair (T, VQ), where T is any type and VQ is either
7103 // volatile or empty, there exist candidate operator functions
7104 // of the form
7105 //
7106 // T*VQ& operator=(T*VQ&, T*);
7107 //
7108 // C++ [over.built]p21:
7109 //
7110 // For every pair (T, VQ), where T is a cv-qualified or
7111 // cv-unqualified object type and VQ is either volatile or
7112 // empty, there exist candidate operator functions of the form
7113 //
7114 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7115 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7116 void addAssignmentPointerOverloads(bool isEqualOp) {
7117 /// Set of (canonical) types that we've already handled.
7118 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7119
7120 for (BuiltinCandidateTypeSet::iterator
7121 Ptr = CandidateTypes[0].pointer_begin(),
7122 PtrEnd = CandidateTypes[0].pointer_end();
7123 Ptr != PtrEnd; ++Ptr) {
7124 // If this is operator=, keep track of the builtin candidates we added.
7125 if (isEqualOp)
7126 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007127 else if (!(*Ptr)->getPointeeType()->isObjectType())
7128 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007129
7130 // non-volatile version
7131 QualType ParamTypes[2] = {
7132 S.Context.getLValueReferenceType(*Ptr),
7133 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7134 };
7135 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7136 /*IsAssigmentOperator=*/ isEqualOp);
7137
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007138 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7139 VisibleTypeConversionsQuals.hasVolatile();
7140 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007141 // volatile version
7142 ParamTypes[0] =
7143 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7145 /*IsAssigmentOperator=*/isEqualOp);
7146 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007147
7148 if (!(*Ptr).isRestrictQualified() &&
7149 VisibleTypeConversionsQuals.hasRestrict()) {
7150 // restrict version
7151 ParamTypes[0]
7152 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7153 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7154 /*IsAssigmentOperator=*/isEqualOp);
7155
7156 if (NeedVolatile) {
7157 // volatile restrict version
7158 ParamTypes[0]
7159 = S.Context.getLValueReferenceType(
7160 S.Context.getCVRQualifiedType(*Ptr,
7161 (Qualifiers::Volatile |
7162 Qualifiers::Restrict)));
7163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7164 CandidateSet,
7165 /*IsAssigmentOperator=*/isEqualOp);
7166 }
7167 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007168 }
7169
7170 if (isEqualOp) {
7171 for (BuiltinCandidateTypeSet::iterator
7172 Ptr = CandidateTypes[1].pointer_begin(),
7173 PtrEnd = CandidateTypes[1].pointer_end();
7174 Ptr != PtrEnd; ++Ptr) {
7175 // Make sure we don't add the same candidate twice.
7176 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7177 continue;
7178
Chandler Carruth6df868e2010-12-12 08:17:55 +00007179 QualType ParamTypes[2] = {
7180 S.Context.getLValueReferenceType(*Ptr),
7181 *Ptr,
7182 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007183
7184 // non-volatile version
7185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7186 /*IsAssigmentOperator=*/true);
7187
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007188 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7189 VisibleTypeConversionsQuals.hasVolatile();
7190 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007191 // volatile version
7192 ParamTypes[0] =
7193 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007194 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7195 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007196 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007197
7198 if (!(*Ptr).isRestrictQualified() &&
7199 VisibleTypeConversionsQuals.hasRestrict()) {
7200 // restrict version
7201 ParamTypes[0]
7202 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7203 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7204 CandidateSet, /*IsAssigmentOperator=*/true);
7205
7206 if (NeedVolatile) {
7207 // volatile restrict version
7208 ParamTypes[0]
7209 = S.Context.getLValueReferenceType(
7210 S.Context.getCVRQualifiedType(*Ptr,
7211 (Qualifiers::Volatile |
7212 Qualifiers::Restrict)));
7213 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7214 CandidateSet, /*IsAssigmentOperator=*/true);
7215
7216 }
7217 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007218 }
7219 }
7220 }
7221
7222 // C++ [over.built]p18:
7223 //
7224 // For every triple (L, VQ, R), where L is an arithmetic type,
7225 // VQ is either volatile or empty, and R is a promoted
7226 // arithmetic type, there exist candidate operator functions of
7227 // the form
7228 //
7229 // VQ L& operator=(VQ L&, R);
7230 // VQ L& operator*=(VQ L&, R);
7231 // VQ L& operator/=(VQ L&, R);
7232 // VQ L& operator+=(VQ L&, R);
7233 // VQ L& operator-=(VQ L&, R);
7234 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007235 if (!HasArithmeticOrEnumeralCandidateType)
7236 return;
7237
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007238 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7239 for (unsigned Right = FirstPromotedArithmeticType;
7240 Right < LastPromotedArithmeticType; ++Right) {
7241 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007242 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243
7244 // Add this built-in operator as a candidate (VQ is empty).
7245 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007246 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007247 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7248 /*IsAssigmentOperator=*/isEqualOp);
7249
7250 // Add this built-in operator as a candidate (VQ is 'volatile').
7251 if (VisibleTypeConversionsQuals.hasVolatile()) {
7252 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007253 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007254 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007255 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7256 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007257 /*IsAssigmentOperator=*/isEqualOp);
7258 }
7259 }
7260 }
7261
7262 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7263 for (BuiltinCandidateTypeSet::iterator
7264 Vec1 = CandidateTypes[0].vector_begin(),
7265 Vec1End = CandidateTypes[0].vector_end();
7266 Vec1 != Vec1End; ++Vec1) {
7267 for (BuiltinCandidateTypeSet::iterator
7268 Vec2 = CandidateTypes[1].vector_begin(),
7269 Vec2End = CandidateTypes[1].vector_end();
7270 Vec2 != Vec2End; ++Vec2) {
7271 QualType ParamTypes[2];
7272 ParamTypes[1] = *Vec2;
7273 // Add this built-in operator as a candidate (VQ is empty).
7274 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7275 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7276 /*IsAssigmentOperator=*/isEqualOp);
7277
7278 // Add this built-in operator as a candidate (VQ is 'volatile').
7279 if (VisibleTypeConversionsQuals.hasVolatile()) {
7280 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7281 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007282 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7283 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007284 /*IsAssigmentOperator=*/isEqualOp);
7285 }
7286 }
7287 }
7288 }
7289
7290 // C++ [over.built]p22:
7291 //
7292 // For every triple (L, VQ, R), where L is an integral type, VQ
7293 // is either volatile or empty, and R is a promoted integral
7294 // type, there exist candidate operator functions of the form
7295 //
7296 // VQ L& operator%=(VQ L&, R);
7297 // VQ L& operator<<=(VQ L&, R);
7298 // VQ L& operator>>=(VQ L&, R);
7299 // VQ L& operator&=(VQ L&, R);
7300 // VQ L& operator^=(VQ L&, R);
7301 // VQ L& operator|=(VQ L&, R);
7302 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007303 if (!HasArithmeticOrEnumeralCandidateType)
7304 return;
7305
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007306 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7307 for (unsigned Right = FirstPromotedIntegralType;
7308 Right < LastPromotedIntegralType; ++Right) {
7309 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007310 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007311
7312 // Add this built-in operator as a candidate (VQ is empty).
7313 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007314 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7316 if (VisibleTypeConversionsQuals.hasVolatile()) {
7317 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007318 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007319 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7320 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7321 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7322 CandidateSet);
7323 }
7324 }
7325 }
7326 }
7327
7328 // C++ [over.operator]p23:
7329 //
7330 // There also exist candidate operator functions of the form
7331 //
7332 // bool operator!(bool);
7333 // bool operator&&(bool, bool);
7334 // bool operator||(bool, bool);
7335 void addExclaimOverload() {
7336 QualType ParamTy = S.Context.BoolTy;
7337 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7338 /*IsAssignmentOperator=*/false,
7339 /*NumContextualBoolArguments=*/1);
7340 }
7341 void addAmpAmpOrPipePipeOverload() {
7342 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7343 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7344 /*IsAssignmentOperator=*/false,
7345 /*NumContextualBoolArguments=*/2);
7346 }
7347
7348 // C++ [over.built]p13:
7349 //
7350 // For every cv-qualified or cv-unqualified object type T there
7351 // exist candidate operator functions of the form
7352 //
7353 // T* operator+(T*, ptrdiff_t); [ABOVE]
7354 // T& operator[](T*, ptrdiff_t);
7355 // T* operator-(T*, ptrdiff_t); [ABOVE]
7356 // T* operator+(ptrdiff_t, T*); [ABOVE]
7357 // T& operator[](ptrdiff_t, T*);
7358 void addSubscriptOverloads() {
7359 for (BuiltinCandidateTypeSet::iterator
7360 Ptr = CandidateTypes[0].pointer_begin(),
7361 PtrEnd = CandidateTypes[0].pointer_end();
7362 Ptr != PtrEnd; ++Ptr) {
7363 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7364 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007365 if (!PointeeType->isObjectType())
7366 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007367
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007368 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7369
7370 // T& operator[](T*, ptrdiff_t)
7371 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7372 }
7373
7374 for (BuiltinCandidateTypeSet::iterator
7375 Ptr = CandidateTypes[1].pointer_begin(),
7376 PtrEnd = CandidateTypes[1].pointer_end();
7377 Ptr != PtrEnd; ++Ptr) {
7378 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7379 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007380 if (!PointeeType->isObjectType())
7381 continue;
7382
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007383 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7384
7385 // T& operator[](ptrdiff_t, T*)
7386 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7387 }
7388 }
7389
7390 // C++ [over.built]p11:
7391 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7392 // C1 is the same type as C2 or is a derived class of C2, T is an object
7393 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7394 // there exist candidate operator functions of the form
7395 //
7396 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7397 //
7398 // where CV12 is the union of CV1 and CV2.
7399 void addArrowStarOverloads() {
7400 for (BuiltinCandidateTypeSet::iterator
7401 Ptr = CandidateTypes[0].pointer_begin(),
7402 PtrEnd = CandidateTypes[0].pointer_end();
7403 Ptr != PtrEnd; ++Ptr) {
7404 QualType C1Ty = (*Ptr);
7405 QualType C1;
7406 QualifierCollector Q1;
7407 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7408 if (!isa<RecordType>(C1))
7409 continue;
7410 // heuristic to reduce number of builtin candidates in the set.
7411 // Add volatile/restrict version only if there are conversions to a
7412 // volatile/restrict type.
7413 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7414 continue;
7415 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7416 continue;
7417 for (BuiltinCandidateTypeSet::iterator
7418 MemPtr = CandidateTypes[1].member_pointer_begin(),
7419 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7420 MemPtr != MemPtrEnd; ++MemPtr) {
7421 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7422 QualType C2 = QualType(mptr->getClass(), 0);
7423 C2 = C2.getUnqualifiedType();
7424 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7425 break;
7426 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7427 // build CV12 T&
7428 QualType T = mptr->getPointeeType();
7429 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7430 T.isVolatileQualified())
7431 continue;
7432 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7433 T.isRestrictQualified())
7434 continue;
7435 T = Q1.apply(S.Context, T);
7436 QualType ResultTy = S.Context.getLValueReferenceType(T);
7437 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7438 }
7439 }
7440 }
7441
7442 // Note that we don't consider the first argument, since it has been
7443 // contextually converted to bool long ago. The candidates below are
7444 // therefore added as binary.
7445 //
7446 // C++ [over.built]p25:
7447 // For every type T, where T is a pointer, pointer-to-member, or scoped
7448 // enumeration type, there exist candidate operator functions of the form
7449 //
7450 // T operator?(bool, T, T);
7451 //
7452 void addConditionalOperatorOverloads() {
7453 /// Set of (canonical) types that we've already handled.
7454 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7455
7456 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7457 for (BuiltinCandidateTypeSet::iterator
7458 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7459 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7460 Ptr != PtrEnd; ++Ptr) {
7461 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7462 continue;
7463
7464 QualType ParamTypes[2] = { *Ptr, *Ptr };
7465 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7466 }
7467
7468 for (BuiltinCandidateTypeSet::iterator
7469 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7470 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7471 MemPtr != MemPtrEnd; ++MemPtr) {
7472 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7473 continue;
7474
7475 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7476 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7477 }
7478
Richard Smith80ad52f2013-01-02 11:42:31 +00007479 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007480 for (BuiltinCandidateTypeSet::iterator
7481 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7482 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7483 Enum != EnumEnd; ++Enum) {
7484 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7485 continue;
7486
7487 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7488 continue;
7489
7490 QualType ParamTypes[2] = { *Enum, *Enum };
7491 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7492 }
7493 }
7494 }
7495 }
7496};
7497
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007498} // end anonymous namespace
7499
7500/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7501/// operator overloads to the candidate set (C++ [over.built]), based
7502/// on the operator @p Op and the arguments given. For example, if the
7503/// operator is a binary '+', this routine might add "int
7504/// operator+(int, int)" to cover integer addition.
7505void
7506Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7507 SourceLocation OpLoc,
7508 Expr **Args, unsigned NumArgs,
7509 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007510 // Find all of the types that the arguments can convert to, but only
7511 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007512 // that make use of these types. Also record whether we encounter non-record
7513 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007514 Qualifiers VisibleTypeConversionsQuals;
7515 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007516 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7517 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007518
7519 bool HasNonRecordCandidateType = false;
7520 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007521 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007522 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7523 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7524 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7525 OpLoc,
7526 true,
7527 (Op == OO_Exclaim ||
7528 Op == OO_AmpAmp ||
7529 Op == OO_PipePipe),
7530 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007531 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7532 CandidateTypes[ArgIdx].hasNonRecordTypes();
7533 HasArithmeticOrEnumeralCandidateType =
7534 HasArithmeticOrEnumeralCandidateType ||
7535 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007536 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007537
Chandler Carruth6a577462010-12-13 01:44:01 +00007538 // Exit early when no non-record types have been added to the candidate set
7539 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007540 //
7541 // We can't exit early for !, ||, or &&, since there we have always have
7542 // 'bool' overloads.
7543 if (!HasNonRecordCandidateType &&
7544 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007545 return;
7546
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007547 // Setup an object to manage the common state for building overloads.
7548 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7549 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007550 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007551 CandidateTypes, CandidateSet);
7552
7553 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007554 switch (Op) {
7555 case OO_None:
7556 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007557 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007558
Chandler Carruthabb71842010-12-12 08:51:33 +00007559 case OO_New:
7560 case OO_Delete:
7561 case OO_Array_New:
7562 case OO_Array_Delete:
7563 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007564 llvm_unreachable(
7565 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007566
7567 case OO_Comma:
7568 case OO_Arrow:
7569 // C++ [over.match.oper]p3:
7570 // -- For the operator ',', the unary operator '&', or the
7571 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007572 break;
7573
7574 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007575 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007576 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007577 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007578
7579 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007580 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007581 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007582 } else {
7583 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7584 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7585 }
Douglas Gregor74253732008-11-19 15:42:04 +00007586 break;
7587
Chandler Carruthabb71842010-12-12 08:51:33 +00007588 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007589 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007590 OpBuilder.addUnaryStarPointerOverloads();
7591 else
7592 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7593 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007594
Chandler Carruthabb71842010-12-12 08:51:33 +00007595 case OO_Slash:
7596 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007597 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007598
7599 case OO_PlusPlus:
7600 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007601 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7602 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007603 break;
7604
Douglas Gregor19b7b152009-08-24 13:43:27 +00007605 case OO_EqualEqual:
7606 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007607 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007608 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007609
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007610 case OO_Less:
7611 case OO_Greater:
7612 case OO_LessEqual:
7613 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007614 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007615 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7616 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007617
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007618 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007619 case OO_Caret:
7620 case OO_Pipe:
7621 case OO_LessLess:
7622 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007623 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007624 break;
7625
Chandler Carruthabb71842010-12-12 08:51:33 +00007626 case OO_Amp: // '&' is either unary or binary
7627 if (NumArgs == 1)
7628 // C++ [over.match.oper]p3:
7629 // -- For the operator ',', the unary operator '&', or the
7630 // operator '->', the built-in candidates set is empty.
7631 break;
7632
7633 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7634 break;
7635
7636 case OO_Tilde:
7637 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7638 break;
7639
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007640 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007641 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007642 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007643
7644 case OO_PlusEqual:
7645 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007646 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007647 // Fall through.
7648
7649 case OO_StarEqual:
7650 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007651 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007652 break;
7653
7654 case OO_PercentEqual:
7655 case OO_LessLessEqual:
7656 case OO_GreaterGreaterEqual:
7657 case OO_AmpEqual:
7658 case OO_CaretEqual:
7659 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007660 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007661 break;
7662
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007663 case OO_Exclaim:
7664 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007665 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007666
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007667 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007668 case OO_PipePipe:
7669 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007670 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007671
7672 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007673 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007674 break;
7675
7676 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007677 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007678 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007679
7680 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007681 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007682 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7683 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007684 }
7685}
7686
Douglas Gregorfa047642009-02-04 00:32:51 +00007687/// \brief Add function candidates found via argument-dependent lookup
7688/// to the set of overloading candidates.
7689///
7690/// This routine performs argument-dependent name lookup based on the
7691/// given function name (which may also be an operator name) and adds
7692/// all of the overload candidates found by ADL to the overload
7693/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007694void
Douglas Gregorfa047642009-02-04 00:32:51 +00007695Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007696 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007697 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007698 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007699 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007700 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007701 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007702
John McCalla113e722010-01-26 06:04:06 +00007703 // FIXME: This approach for uniquing ADL results (and removing
7704 // redundant candidates from the set) relies on pointer-equality,
7705 // which means we need to key off the canonical decl. However,
7706 // always going back to the canonical decl might not get us the
7707 // right set of default arguments. What default arguments are
7708 // we supposed to consider on ADL candidates, anyway?
7709
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007710 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007711 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007712
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007713 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007714 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7715 CandEnd = CandidateSet.end();
7716 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007717 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007718 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007719 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007720 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007721 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007722
7723 // For each of the ADL candidates we found, add it to the overload
7724 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007725 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007726 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007727 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007728 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007729 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007730
Ahmed Charles13a140c2012-02-25 11:00:22 +00007731 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7732 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007733 } else
John McCall6e266892010-01-26 03:27:55 +00007734 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007735 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007736 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007737 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007738}
7739
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007740/// isBetterOverloadCandidate - Determines whether the first overload
7741/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007742bool
John McCall120d63c2010-08-24 20:38:10 +00007743isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007744 const OverloadCandidate &Cand1,
7745 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007746 SourceLocation Loc,
7747 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007748 // Define viable functions to be better candidates than non-viable
7749 // functions.
7750 if (!Cand2.Viable)
7751 return Cand1.Viable;
7752 else if (!Cand1.Viable)
7753 return false;
7754
Douglas Gregor88a35142008-12-22 05:46:06 +00007755 // C++ [over.match.best]p1:
7756 //
7757 // -- if F is a static member function, ICS1(F) is defined such
7758 // that ICS1(F) is neither better nor worse than ICS1(G) for
7759 // any function G, and, symmetrically, ICS1(G) is neither
7760 // better nor worse than ICS1(F).
7761 unsigned StartArg = 0;
7762 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7763 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007764
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007765 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007766 // A viable function F1 is defined to be a better function than another
7767 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007768 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007769 unsigned NumArgs = Cand1.NumConversions;
7770 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007771 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007772 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007773 switch (CompareImplicitConversionSequences(S,
7774 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007775 Cand2.Conversions[ArgIdx])) {
7776 case ImplicitConversionSequence::Better:
7777 // Cand1 has a better conversion sequence.
7778 HasBetterConversion = true;
7779 break;
7780
7781 case ImplicitConversionSequence::Worse:
7782 // Cand1 can't be better than Cand2.
7783 return false;
7784
7785 case ImplicitConversionSequence::Indistinguishable:
7786 // Do nothing.
7787 break;
7788 }
7789 }
7790
Mike Stump1eb44332009-09-09 15:08:12 +00007791 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007792 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007793 if (HasBetterConversion)
7794 return true;
7795
Mike Stump1eb44332009-09-09 15:08:12 +00007796 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007797 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007798 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007799 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7800 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007801
7802 // -- F1 and F2 are function template specializations, and the function
7803 // template for F1 is more specialized than the template for F2
7804 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007805 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007806 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007807 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007808 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007809 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7810 Cand2.Function->getPrimaryTemplate(),
7811 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007812 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007813 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007814 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007815 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007816 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007817
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007818 // -- the context is an initialization by user-defined conversion
7819 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7820 // from the return type of F1 to the destination type (i.e.,
7821 // the type of the entity being initialized) is a better
7822 // conversion sequence than the standard conversion sequence
7823 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007824 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007825 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007826 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007827 // First check whether we prefer one of the conversion functions over the
7828 // other. This only distinguishes the results in non-standard, extension
7829 // cases such as the conversion from a lambda closure type to a function
7830 // pointer or block.
7831 ImplicitConversionSequence::CompareKind FuncResult
7832 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7833 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7834 return FuncResult;
7835
John McCall120d63c2010-08-24 20:38:10 +00007836 switch (CompareStandardConversionSequences(S,
7837 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007838 Cand2.FinalConversion)) {
7839 case ImplicitConversionSequence::Better:
7840 // Cand1 has a better conversion sequence.
7841 return true;
7842
7843 case ImplicitConversionSequence::Worse:
7844 // Cand1 can't be better than Cand2.
7845 return false;
7846
7847 case ImplicitConversionSequence::Indistinguishable:
7848 // Do nothing
7849 break;
7850 }
7851 }
7852
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007853 return false;
7854}
7855
Mike Stump1eb44332009-09-09 15:08:12 +00007856/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007857/// within an overload candidate set.
7858///
James Dennettefce31f2012-06-22 08:10:18 +00007859/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007860/// which overload resolution occurs.
7861///
James Dennettefce31f2012-06-22 08:10:18 +00007862/// \param Best If overload resolution was successful or found a deleted
7863/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007864///
7865/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007866OverloadingResult
7867OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007868 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007869 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007870 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007871 Best = end();
7872 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7873 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007874 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007875 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007876 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007877 }
7878
7879 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007880 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007881 return OR_No_Viable_Function;
7882
7883 // Make sure that this function is better than every other viable
7884 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007885 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007886 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007887 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007888 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007889 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007890 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007891 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007892 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007893 }
Mike Stump1eb44332009-09-09 15:08:12 +00007894
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007895 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007896 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007897 (Best->Function->isDeleted() ||
7898 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007899 return OR_Deleted;
7900
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007901 return OR_Success;
7902}
7903
John McCall3c80f572010-01-12 02:15:36 +00007904namespace {
7905
7906enum OverloadCandidateKind {
7907 oc_function,
7908 oc_method,
7909 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007910 oc_function_template,
7911 oc_method_template,
7912 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007913 oc_implicit_default_constructor,
7914 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007915 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007916 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007917 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007918 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007919};
7920
John McCall220ccbf2010-01-13 00:25:19 +00007921OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7922 FunctionDecl *Fn,
7923 std::string &Description) {
7924 bool isTemplate = false;
7925
7926 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7927 isTemplate = true;
7928 Description = S.getTemplateArgumentBindingsText(
7929 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7930 }
John McCallb1622a12010-01-06 09:43:14 +00007931
7932 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007933 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007934 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007935
Sebastian Redlf677ea32011-02-05 19:23:19 +00007936 if (Ctor->getInheritedConstructor())
7937 return oc_implicit_inherited_constructor;
7938
Sean Hunt82713172011-05-25 23:16:36 +00007939 if (Ctor->isDefaultConstructor())
7940 return oc_implicit_default_constructor;
7941
7942 if (Ctor->isMoveConstructor())
7943 return oc_implicit_move_constructor;
7944
7945 assert(Ctor->isCopyConstructor() &&
7946 "unexpected sort of implicit constructor");
7947 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007948 }
7949
7950 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7951 // This actually gets spelled 'candidate function' for now, but
7952 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007953 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007954 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007955
Sean Hunt82713172011-05-25 23:16:36 +00007956 if (Meth->isMoveAssignmentOperator())
7957 return oc_implicit_move_assignment;
7958
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007959 if (Meth->isCopyAssignmentOperator())
7960 return oc_implicit_copy_assignment;
7961
7962 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7963 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007964 }
7965
John McCall220ccbf2010-01-13 00:25:19 +00007966 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007967}
7968
Sebastian Redlf677ea32011-02-05 19:23:19 +00007969void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7970 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7971 if (!Ctor) return;
7972
7973 Ctor = Ctor->getInheritedConstructor();
7974 if (!Ctor) return;
7975
7976 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7977}
7978
John McCall3c80f572010-01-12 02:15:36 +00007979} // end anonymous namespace
7980
7981// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007982void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007983 std::string FnDesc;
7984 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007985 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7986 << (unsigned) K << FnDesc;
7987 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7988 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007989 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007990}
7991
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007992//Notes the location of all overload candidates designated through
7993// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007994void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007995 assert(OverloadedExpr->getType() == Context.OverloadTy);
7996
7997 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7998 OverloadExpr *OvlExpr = Ovl.Expression;
7999
8000 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8001 IEnd = OvlExpr->decls_end();
8002 I != IEnd; ++I) {
8003 if (FunctionTemplateDecl *FunTmpl =
8004 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008005 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008006 } else if (FunctionDecl *Fun
8007 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008008 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008009 }
8010 }
8011}
8012
John McCall1d318332010-01-12 00:44:57 +00008013/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8014/// "lead" diagnostic; it will be given two arguments, the source and
8015/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008016void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8017 Sema &S,
8018 SourceLocation CaretLoc,
8019 const PartialDiagnostic &PDiag) const {
8020 S.Diag(CaretLoc, PDiag)
8021 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008022 // FIXME: The note limiting machinery is borrowed from
8023 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8024 // refactoring here.
8025 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8026 unsigned CandsShown = 0;
8027 AmbiguousConversionSequence::const_iterator I, E;
8028 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8029 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8030 break;
8031 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008032 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008033 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008034 if (I != E)
8035 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008036}
8037
John McCall1d318332010-01-12 00:44:57 +00008038namespace {
8039
John McCalladbb8f82010-01-13 09:16:55 +00008040void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8041 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8042 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008043 assert(Cand->Function && "for now, candidate must be a function");
8044 FunctionDecl *Fn = Cand->Function;
8045
8046 // There's a conversion slot for the object argument if this is a
8047 // non-constructor method. Note that 'I' corresponds the
8048 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008049 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008050 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008051 if (I == 0)
8052 isObjectArgument = true;
8053 else
8054 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008055 }
8056
John McCall220ccbf2010-01-13 00:25:19 +00008057 std::string FnDesc;
8058 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8059
John McCalladbb8f82010-01-13 09:16:55 +00008060 Expr *FromExpr = Conv.Bad.FromExpr;
8061 QualType FromTy = Conv.Bad.getFromType();
8062 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008063
John McCall5920dbb2010-02-02 02:42:52 +00008064 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008065 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008066 Expr *E = FromExpr->IgnoreParens();
8067 if (isa<UnaryOperator>(E))
8068 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008069 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008070
8071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8072 << (unsigned) FnKind << FnDesc
8073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8074 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008075 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008076 return;
8077 }
8078
John McCall258b2032010-01-23 08:10:49 +00008079 // Do some hand-waving analysis to see if the non-viability is due
8080 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008081 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8082 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8083 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8084 CToTy = RT->getPointeeType();
8085 else {
8086 // TODO: detect and diagnose the full richness of const mismatches.
8087 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8088 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8089 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8090 }
8091
8092 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8093 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008094 Qualifiers FromQs = CFromTy.getQualifiers();
8095 Qualifiers ToQs = CToTy.getQualifiers();
8096
8097 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8099 << (unsigned) FnKind << FnDesc
8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8101 << FromTy
8102 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8103 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008104 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008105 return;
8106 }
8107
John McCallf85e1932011-06-15 23:02:42 +00008108 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008110 << (unsigned) FnKind << FnDesc
8111 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8112 << FromTy
8113 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8114 << (unsigned) isObjectArgument << I+1;
8115 MaybeEmitInheritedConstructorNote(S, Fn);
8116 return;
8117 }
8118
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008119 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8121 << (unsigned) FnKind << FnDesc
8122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8123 << FromTy
8124 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8125 << (unsigned) isObjectArgument << I+1;
8126 MaybeEmitInheritedConstructorNote(S, Fn);
8127 return;
8128 }
8129
John McCall651f3ee2010-01-14 03:28:57 +00008130 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8131 assert(CVR && "unexpected qualifiers mismatch");
8132
8133 if (isObjectArgument) {
8134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8135 << (unsigned) FnKind << FnDesc
8136 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8137 << FromTy << (CVR - 1);
8138 } else {
8139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8140 << (unsigned) FnKind << FnDesc
8141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8142 << FromTy << (CVR - 1) << I+1;
8143 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008144 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008145 return;
8146 }
8147
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008148 // Special diagnostic for failure to convert an initializer list, since
8149 // telling the user that it has type void is not useful.
8150 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8152 << (unsigned) FnKind << FnDesc
8153 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8154 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8155 MaybeEmitInheritedConstructorNote(S, Fn);
8156 return;
8157 }
8158
John McCall258b2032010-01-23 08:10:49 +00008159 // Diagnose references or pointers to incomplete types differently,
8160 // since it's far from impossible that the incompleteness triggered
8161 // the failure.
8162 QualType TempFromTy = FromTy.getNonReferenceType();
8163 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8164 TempFromTy = PTy->getPointeeType();
8165 if (TempFromTy->isIncompleteType()) {
8166 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8167 << (unsigned) FnKind << FnDesc
8168 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8169 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008170 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008171 return;
8172 }
8173
Douglas Gregor85789812010-06-30 23:01:39 +00008174 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008175 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008176 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8177 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8178 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8179 FromPtrTy->getPointeeType()) &&
8180 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8181 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008182 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008183 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008184 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008185 }
8186 } else if (const ObjCObjectPointerType *FromPtrTy
8187 = FromTy->getAs<ObjCObjectPointerType>()) {
8188 if (const ObjCObjectPointerType *ToPtrTy
8189 = ToTy->getAs<ObjCObjectPointerType>())
8190 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8191 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8192 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8193 FromPtrTy->getPointeeType()) &&
8194 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008195 BaseToDerivedConversion = 2;
8196 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008197 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8198 !FromTy->isIncompleteType() &&
8199 !ToRefTy->getPointeeType()->isIncompleteType() &&
8200 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8201 BaseToDerivedConversion = 3;
8202 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8203 ToTy.getNonReferenceType().getCanonicalType() ==
8204 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008205 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8206 << (unsigned) FnKind << FnDesc
8207 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8208 << (unsigned) isObjectArgument << I + 1;
8209 MaybeEmitInheritedConstructorNote(S, Fn);
8210 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008211 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008212 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008213
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008214 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008215 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008216 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008217 << (unsigned) FnKind << FnDesc
8218 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008219 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008220 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008221 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008222 return;
8223 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008224
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008225 if (isa<ObjCObjectPointerType>(CFromTy) &&
8226 isa<PointerType>(CToTy)) {
8227 Qualifiers FromQs = CFromTy.getQualifiers();
8228 Qualifiers ToQs = CToTy.getQualifiers();
8229 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8231 << (unsigned) FnKind << FnDesc
8232 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8233 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8234 MaybeEmitInheritedConstructorNote(S, Fn);
8235 return;
8236 }
8237 }
8238
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008239 // Emit the generic diagnostic and, optionally, add the hints to it.
8240 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8241 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008242 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008243 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8244 << (unsigned) (Cand->Fix.Kind);
8245
8246 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008247 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8248 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008249 FDiag << *HI;
8250 S.Diag(Fn->getLocation(), FDiag);
8251
Sebastian Redlf677ea32011-02-05 19:23:19 +00008252 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008253}
8254
8255void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8256 unsigned NumFormalArgs) {
8257 // TODO: treat calls to a missing default constructor as a special case
8258
8259 FunctionDecl *Fn = Cand->Function;
8260 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8261
8262 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008263
Douglas Gregor439d3c32011-05-05 00:13:13 +00008264 // With invalid overloaded operators, it's possible that we think we
8265 // have an arity mismatch when it fact it looks like we have the
8266 // right number of arguments, because only overloaded operators have
8267 // the weird behavior of overloading member and non-member functions.
8268 // Just don't report anything.
8269 if (Fn->isInvalidDecl() &&
8270 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8271 return;
8272
John McCalladbb8f82010-01-13 09:16:55 +00008273 // at least / at most / exactly
8274 unsigned mode, modeCount;
8275 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008276 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8277 (Cand->FailureKind == ovl_fail_bad_deduction &&
8278 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008279 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008280 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008281 mode = 0; // "at least"
8282 else
8283 mode = 2; // "exactly"
8284 modeCount = MinParams;
8285 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008286 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8287 (Cand->FailureKind == ovl_fail_bad_deduction &&
8288 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008289 if (MinParams != FnTy->getNumArgs())
8290 mode = 1; // "at most"
8291 else
8292 mode = 2; // "exactly"
8293 modeCount = FnTy->getNumArgs();
8294 }
8295
8296 std::string Description;
8297 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8298
Richard Smithf7b80562012-05-11 05:16:41 +00008299 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8301 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8302 << Fn->getParamDecl(0) << NumFormalArgs;
8303 else
8304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8305 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8306 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008307 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008308}
8309
John McCall342fec42010-02-01 18:53:26 +00008310/// Diagnose a failed template-argument deduction.
8311void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008312 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008313 FunctionDecl *Fn = Cand->Function; // pattern
8314
Douglas Gregora9333192010-05-08 17:41:32 +00008315 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008316 NamedDecl *ParamD;
8317 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8318 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8319 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008320 switch (Cand->DeductionFailure.Result) {
8321 case Sema::TDK_Success:
8322 llvm_unreachable("TDK_success while diagnosing bad deduction");
8323
8324 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008325 assert(ParamD && "no parameter found for incomplete deduction result");
8326 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8327 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008328 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008329 return;
8330 }
8331
John McCall57e97782010-08-05 09:05:08 +00008332 case Sema::TDK_Underqualified: {
8333 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8334 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8335
8336 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8337
8338 // Param will have been canonicalized, but it should just be a
8339 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008340 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008341 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008342 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008343 assert(S.Context.hasSameType(Param, NonCanonParam));
8344
8345 // Arg has also been canonicalized, but there's nothing we can do
8346 // about that. It also doesn't matter as much, because it won't
8347 // have any template parameters in it (because deduction isn't
8348 // done on dependent types).
8349 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8350
8351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8352 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008353 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008354 return;
8355 }
8356
8357 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008358 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008359 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008360 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008361 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008362 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008363 which = 1;
8364 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008365 which = 2;
8366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008367
Douglas Gregora9333192010-05-08 17:41:32 +00008368 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008369 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008370 << *Cand->DeductionFailure.getFirstArg()
8371 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008372 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008373 return;
8374 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008375
Douglas Gregorf1a84452010-05-08 19:15:54 +00008376 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008377 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008378 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008379 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008380 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8381 << ParamD->getDeclName();
8382 else {
8383 int index = 0;
8384 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8385 index = TTP->getIndex();
8386 else if (NonTypeTemplateParmDecl *NTTP
8387 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8388 index = NTTP->getIndex();
8389 else
8390 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008391 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008392 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8393 << (index + 1);
8394 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008395 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008396 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008397
Douglas Gregora18592e2010-05-08 18:13:28 +00008398 case Sema::TDK_TooManyArguments:
8399 case Sema::TDK_TooFewArguments:
8400 DiagnoseArityMismatch(S, Cand, NumArgs);
8401 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008402
8403 case Sema::TDK_InstantiationDepth:
8404 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008405 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008406 return;
8407
8408 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008409 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008410 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008411 if (TemplateArgumentList *Args =
8412 Cand->DeductionFailure.getTemplateArgumentList()) {
8413 TemplateArgString = " ";
8414 TemplateArgString += S.getTemplateArgumentBindingsText(
8415 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8416 }
8417
Richard Smith4493c0a2012-05-09 05:17:00 +00008418 // If this candidate was disabled by enable_if, say so.
8419 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8420 if (PDiag && PDiag->second.getDiagID() ==
8421 diag::err_typename_nested_not_found_enable_if) {
8422 // FIXME: Use the source range of the condition, and the fully-qualified
8423 // name of the enable_if template. These are both present in PDiag.
8424 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8425 << "'enable_if'" << TemplateArgString;
8426 return;
8427 }
8428
Richard Smithb8590f32012-05-07 09:03:25 +00008429 // Format the SFINAE diagnostic into the argument string.
8430 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8431 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008432 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008433 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008434 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008435 SFINAEArgString = ": ";
8436 R = SourceRange(PDiag->first, PDiag->first);
8437 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8438 }
8439
Douglas Gregorec20f462010-05-08 20:07:26 +00008440 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008441 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008442 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008443 return;
8444 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008445
John McCall342fec42010-02-01 18:53:26 +00008446 // TODO: diagnose these individually, then kill off
8447 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008448 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008449 case Sema::TDK_FailedOverloadResolution:
8450 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008451 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008452 return;
8453 }
8454}
8455
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008456/// CUDA: diagnose an invalid call across targets.
8457void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8458 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8459 FunctionDecl *Callee = Cand->Function;
8460
8461 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8462 CalleeTarget = S.IdentifyCUDATarget(Callee);
8463
8464 std::string FnDesc;
8465 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8466
8467 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8468 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8469}
8470
John McCall342fec42010-02-01 18:53:26 +00008471/// Generates a 'note' diagnostic for an overload candidate. We've
8472/// already generated a primary error at the call site.
8473///
8474/// It really does need to be a single diagnostic with its caret
8475/// pointed at the candidate declaration. Yes, this creates some
8476/// major challenges of technical writing. Yes, this makes pointing
8477/// out problems with specific arguments quite awkward. It's still
8478/// better than generating twenty screens of text for every failed
8479/// overload.
8480///
8481/// It would be great to be able to express per-candidate problems
8482/// more richly for those diagnostic clients that cared, but we'd
8483/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008484void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008485 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008486 FunctionDecl *Fn = Cand->Function;
8487
John McCall81201622010-01-08 04:41:39 +00008488 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008489 if (Cand->Viable && (Fn->isDeleted() ||
8490 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008491 std::string FnDesc;
8492 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008493
8494 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008495 << FnKind << FnDesc
8496 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008497 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008498 return;
John McCall81201622010-01-08 04:41:39 +00008499 }
8500
John McCall220ccbf2010-01-13 00:25:19 +00008501 // We don't really have anything else to say about viable candidates.
8502 if (Cand->Viable) {
8503 S.NoteOverloadCandidate(Fn);
8504 return;
8505 }
John McCall1d318332010-01-12 00:44:57 +00008506
John McCalladbb8f82010-01-13 09:16:55 +00008507 switch (Cand->FailureKind) {
8508 case ovl_fail_too_many_arguments:
8509 case ovl_fail_too_few_arguments:
8510 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008511
John McCalladbb8f82010-01-13 09:16:55 +00008512 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008513 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008514
John McCall717e8912010-01-23 05:17:32 +00008515 case ovl_fail_trivial_conversion:
8516 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008517 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008518 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008519
John McCallb1bdc622010-02-25 01:37:24 +00008520 case ovl_fail_bad_conversion: {
8521 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008522 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008523 if (Cand->Conversions[I].isBad())
8524 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008525
John McCalladbb8f82010-01-13 09:16:55 +00008526 // FIXME: this currently happens when we're called from SemaInit
8527 // when user-conversion overload fails. Figure out how to handle
8528 // those conditions and diagnose them well.
8529 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008530 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008531
8532 case ovl_fail_bad_target:
8533 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008534 }
John McCalla1d7d622010-01-08 00:58:21 +00008535}
8536
8537void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8538 // Desugar the type of the surrogate down to a function type,
8539 // retaining as many typedefs as possible while still showing
8540 // the function type (and, therefore, its parameter types).
8541 QualType FnType = Cand->Surrogate->getConversionType();
8542 bool isLValueReference = false;
8543 bool isRValueReference = false;
8544 bool isPointer = false;
8545 if (const LValueReferenceType *FnTypeRef =
8546 FnType->getAs<LValueReferenceType>()) {
8547 FnType = FnTypeRef->getPointeeType();
8548 isLValueReference = true;
8549 } else if (const RValueReferenceType *FnTypeRef =
8550 FnType->getAs<RValueReferenceType>()) {
8551 FnType = FnTypeRef->getPointeeType();
8552 isRValueReference = true;
8553 }
8554 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8555 FnType = FnTypePtr->getPointeeType();
8556 isPointer = true;
8557 }
8558 // Desugar down to a function type.
8559 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8560 // Reconstruct the pointer/reference as appropriate.
8561 if (isPointer) FnType = S.Context.getPointerType(FnType);
8562 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8563 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8564
8565 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8566 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008567 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008568}
8569
8570void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008571 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008572 SourceLocation OpLoc,
8573 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008574 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008575 std::string TypeStr("operator");
8576 TypeStr += Opc;
8577 TypeStr += "(";
8578 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008579 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008580 TypeStr += ")";
8581 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8582 } else {
8583 TypeStr += ", ";
8584 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8585 TypeStr += ")";
8586 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8587 }
8588}
8589
8590void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8591 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008592 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008593 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8594 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008595 if (ICS.isBad()) break; // all meaningless after first invalid
8596 if (!ICS.isAmbiguous()) continue;
8597
John McCall120d63c2010-08-24 20:38:10 +00008598 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008599 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008600 }
8601}
8602
John McCall1b77e732010-01-15 23:32:50 +00008603SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8604 if (Cand->Function)
8605 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008606 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008607 return Cand->Surrogate->getLocation();
8608 return SourceLocation();
8609}
8610
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008611static unsigned
8612RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008613 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008614 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008615 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008616
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008617 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008618 case Sema::TDK_Incomplete:
8619 return 1;
8620
8621 case Sema::TDK_Underqualified:
8622 case Sema::TDK_Inconsistent:
8623 return 2;
8624
8625 case Sema::TDK_SubstitutionFailure:
8626 case Sema::TDK_NonDeducedMismatch:
8627 return 3;
8628
8629 case Sema::TDK_InstantiationDepth:
8630 case Sema::TDK_FailedOverloadResolution:
8631 return 4;
8632
8633 case Sema::TDK_InvalidExplicitArguments:
8634 return 5;
8635
8636 case Sema::TDK_TooManyArguments:
8637 case Sema::TDK_TooFewArguments:
8638 return 6;
8639 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008640 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008641}
8642
John McCallbf65c0b2010-01-12 00:48:53 +00008643struct CompareOverloadCandidatesForDisplay {
8644 Sema &S;
8645 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008646
8647 bool operator()(const OverloadCandidate *L,
8648 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008649 // Fast-path this check.
8650 if (L == R) return false;
8651
John McCall81201622010-01-08 04:41:39 +00008652 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008653 if (L->Viable) {
8654 if (!R->Viable) return true;
8655
8656 // TODO: introduce a tri-valued comparison for overload
8657 // candidates. Would be more worthwhile if we had a sort
8658 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008659 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8660 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008661 } else if (R->Viable)
8662 return false;
John McCall81201622010-01-08 04:41:39 +00008663
John McCall1b77e732010-01-15 23:32:50 +00008664 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008665
John McCall1b77e732010-01-15 23:32:50 +00008666 // Criteria by which we can sort non-viable candidates:
8667 if (!L->Viable) {
8668 // 1. Arity mismatches come after other candidates.
8669 if (L->FailureKind == ovl_fail_too_many_arguments ||
8670 L->FailureKind == ovl_fail_too_few_arguments)
8671 return false;
8672 if (R->FailureKind == ovl_fail_too_many_arguments ||
8673 R->FailureKind == ovl_fail_too_few_arguments)
8674 return true;
John McCall81201622010-01-08 04:41:39 +00008675
John McCall717e8912010-01-23 05:17:32 +00008676 // 2. Bad conversions come first and are ordered by the number
8677 // of bad conversions and quality of good conversions.
8678 if (L->FailureKind == ovl_fail_bad_conversion) {
8679 if (R->FailureKind != ovl_fail_bad_conversion)
8680 return true;
8681
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008682 // The conversion that can be fixed with a smaller number of changes,
8683 // comes first.
8684 unsigned numLFixes = L->Fix.NumConversionsFixed;
8685 unsigned numRFixes = R->Fix.NumConversionsFixed;
8686 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8687 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008688 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008689 if (numLFixes < numRFixes)
8690 return true;
8691 else
8692 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008693 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008694
John McCall717e8912010-01-23 05:17:32 +00008695 // If there's any ordering between the defined conversions...
8696 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008697 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008698
8699 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008700 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008701 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008702 switch (CompareImplicitConversionSequences(S,
8703 L->Conversions[I],
8704 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008705 case ImplicitConversionSequence::Better:
8706 leftBetter++;
8707 break;
8708
8709 case ImplicitConversionSequence::Worse:
8710 leftBetter--;
8711 break;
8712
8713 case ImplicitConversionSequence::Indistinguishable:
8714 break;
8715 }
8716 }
8717 if (leftBetter > 0) return true;
8718 if (leftBetter < 0) return false;
8719
8720 } else if (R->FailureKind == ovl_fail_bad_conversion)
8721 return false;
8722
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008723 if (L->FailureKind == ovl_fail_bad_deduction) {
8724 if (R->FailureKind != ovl_fail_bad_deduction)
8725 return true;
8726
8727 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8728 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008729 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008730 } else if (R->FailureKind == ovl_fail_bad_deduction)
8731 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008732
John McCall1b77e732010-01-15 23:32:50 +00008733 // TODO: others?
8734 }
8735
8736 // Sort everything else by location.
8737 SourceLocation LLoc = GetLocationForCandidate(L);
8738 SourceLocation RLoc = GetLocationForCandidate(R);
8739
8740 // Put candidates without locations (e.g. builtins) at the end.
8741 if (LLoc.isInvalid()) return false;
8742 if (RLoc.isInvalid()) return true;
8743
8744 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008745 }
8746};
8747
John McCall717e8912010-01-23 05:17:32 +00008748/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008749/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008750void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008751 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008752 assert(!Cand->Viable);
8753
8754 // Don't do anything on failures other than bad conversion.
8755 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8756
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008757 // We only want the FixIts if all the arguments can be corrected.
8758 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008759 // Use a implicit copy initialization to check conversion fixes.
8760 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008761
John McCall717e8912010-01-23 05:17:32 +00008762 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008763 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008764 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008765 while (true) {
8766 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8767 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008768 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008769 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008770 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008771 }
John McCall717e8912010-01-23 05:17:32 +00008772 }
8773
8774 if (ConvIdx == ConvCount)
8775 return;
8776
John McCallb1bdc622010-02-25 01:37:24 +00008777 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8778 "remaining conversion is initialized?");
8779
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008780 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008781 // operation somehow.
8782 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008783
8784 const FunctionProtoType* Proto;
8785 unsigned ArgIdx = ConvIdx;
8786
8787 if (Cand->IsSurrogate) {
8788 QualType ConvType
8789 = Cand->Surrogate->getConversionType().getNonReferenceType();
8790 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8791 ConvType = ConvPtrType->getPointeeType();
8792 Proto = ConvType->getAs<FunctionProtoType>();
8793 ArgIdx--;
8794 } else if (Cand->Function) {
8795 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8796 if (isa<CXXMethodDecl>(Cand->Function) &&
8797 !isa<CXXConstructorDecl>(Cand->Function))
8798 ArgIdx--;
8799 } else {
8800 // Builtin binary operator with a bad first conversion.
8801 assert(ConvCount <= 3);
8802 for (; ConvIdx != ConvCount; ++ConvIdx)
8803 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008804 = TryCopyInitialization(S, Args[ConvIdx],
8805 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008806 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008807 /*InOverloadResolution*/ true,
8808 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008809 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008810 return;
8811 }
8812
8813 // Fill in the rest of the conversions.
8814 unsigned NumArgsInProto = Proto->getNumArgs();
8815 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008816 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008817 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008818 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008819 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008820 /*InOverloadResolution=*/true,
8821 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008822 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008823 // Store the FixIt in the candidate if it exists.
8824 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008825 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008826 }
John McCall717e8912010-01-23 05:17:32 +00008827 else
8828 Cand->Conversions[ConvIdx].setEllipsis();
8829 }
8830}
8831
John McCalla1d7d622010-01-08 00:58:21 +00008832} // end anonymous namespace
8833
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008834/// PrintOverloadCandidates - When overload resolution fails, prints
8835/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008836/// set.
John McCall120d63c2010-08-24 20:38:10 +00008837void OverloadCandidateSet::NoteCandidates(Sema &S,
8838 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008839 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008840 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008841 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008842 // Sort the candidates by viability and position. Sorting directly would
8843 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008844 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008845 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8846 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008847 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008848 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008849 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008850 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008851 if (Cand->Function || Cand->IsSurrogate)
8852 Cands.push_back(Cand);
8853 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8854 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008855 }
8856 }
8857
John McCallbf65c0b2010-01-12 00:48:53 +00008858 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008859 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008860
John McCall1d318332010-01-12 00:44:57 +00008861 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008862
Chris Lattner5f9e2722011-07-23 10:55:15 +00008863 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008864 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008865 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008866 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8867 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008868
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008869 // Set an arbitrary limit on the number of candidate functions we'll spam
8870 // the user with. FIXME: This limit should depend on details of the
8871 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008872 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008873 break;
8874 }
8875 ++CandsShown;
8876
John McCalla1d7d622010-01-08 00:58:21 +00008877 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008878 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008879 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008880 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008881 else {
8882 assert(Cand->Viable &&
8883 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008884 // Generally we only see ambiguities including viable builtin
8885 // operators if overload resolution got screwed up by an
8886 // ambiguous user-defined conversion.
8887 //
8888 // FIXME: It's quite possible for different conversions to see
8889 // different ambiguities, though.
8890 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008891 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008892 ReportedAmbiguousConversions = true;
8893 }
John McCalla1d7d622010-01-08 00:58:21 +00008894
John McCall1d318332010-01-12 00:44:57 +00008895 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008896 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008897 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008898 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008899
8900 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008901 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008902}
8903
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008904// [PossiblyAFunctionType] --> [Return]
8905// NonFunctionType --> NonFunctionType
8906// R (A) --> R(A)
8907// R (*)(A) --> R (A)
8908// R (&)(A) --> R (A)
8909// R (S::*)(A) --> R (A)
8910QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8911 QualType Ret = PossiblyAFunctionType;
8912 if (const PointerType *ToTypePtr =
8913 PossiblyAFunctionType->getAs<PointerType>())
8914 Ret = ToTypePtr->getPointeeType();
8915 else if (const ReferenceType *ToTypeRef =
8916 PossiblyAFunctionType->getAs<ReferenceType>())
8917 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008918 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008919 PossiblyAFunctionType->getAs<MemberPointerType>())
8920 Ret = MemTypePtr->getPointeeType();
8921 Ret =
8922 Context.getCanonicalType(Ret).getUnqualifiedType();
8923 return Ret;
8924}
Douglas Gregor904eed32008-11-10 20:40:00 +00008925
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008926// A helper class to help with address of function resolution
8927// - allows us to avoid passing around all those ugly parameters
8928class AddressOfFunctionResolver
8929{
8930 Sema& S;
8931 Expr* SourceExpr;
8932 const QualType& TargetType;
8933 QualType TargetFunctionType; // Extracted function type from target type
8934
8935 bool Complain;
8936 //DeclAccessPair& ResultFunctionAccessPair;
8937 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008938
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008939 bool TargetTypeIsNonStaticMemberFunction;
8940 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008941
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008942 OverloadExpr::FindResult OvlExprInfo;
8943 OverloadExpr *OvlExpr;
8944 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008945 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008946
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008947public:
8948 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8949 const QualType& TargetType, bool Complain)
8950 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8951 Complain(Complain), Context(S.getASTContext()),
8952 TargetTypeIsNonStaticMemberFunction(
8953 !!TargetType->getAs<MemberPointerType>()),
8954 FoundNonTemplateFunction(false),
8955 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8956 OvlExpr(OvlExprInfo.Expression)
8957 {
8958 ExtractUnqualifiedFunctionTypeFromTargetType();
8959
8960 if (!TargetFunctionType->isFunctionType()) {
8961 if (OvlExpr->hasExplicitTemplateArgs()) {
8962 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008963 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008964 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008965
8966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8967 if (!Method->isStatic()) {
8968 // If the target type is a non-function type and the function
8969 // found is a non-static member function, pretend as if that was
8970 // the target, it's the only possible type to end up with.
8971 TargetTypeIsNonStaticMemberFunction = true;
8972
8973 // And skip adding the function if its not in the proper form.
8974 // We'll diagnose this due to an empty set of functions.
8975 if (!OvlExprInfo.HasFormOfMemberPointer)
8976 return;
8977 }
8978 }
8979
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008980 Matches.push_back(std::make_pair(dap,Fn));
8981 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008982 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008983 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008984 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008985
8986 if (OvlExpr->hasExplicitTemplateArgs())
8987 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008988
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008989 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8990 // C++ [over.over]p4:
8991 // If more than one function is selected, [...]
8992 if (Matches.size() > 1) {
8993 if (FoundNonTemplateFunction)
8994 EliminateAllTemplateMatches();
8995 else
8996 EliminateAllExceptMostSpecializedTemplate();
8997 }
8998 }
8999 }
9000
9001private:
9002 bool isTargetTypeAFunction() const {
9003 return TargetFunctionType->isFunctionType();
9004 }
9005
9006 // [ToType] [Return]
9007
9008 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9009 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9010 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9011 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9012 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9013 }
9014
9015 // return true if any matching specializations were found
9016 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9017 const DeclAccessPair& CurAccessFunPair) {
9018 if (CXXMethodDecl *Method
9019 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9020 // Skip non-static function templates when converting to pointer, and
9021 // static when converting to member pointer.
9022 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9023 return false;
9024 }
9025 else if (TargetTypeIsNonStaticMemberFunction)
9026 return false;
9027
9028 // C++ [over.over]p2:
9029 // If the name is a function template, template argument deduction is
9030 // done (14.8.2.2), and if the argument deduction succeeds, the
9031 // resulting template argument list is used to generate a single
9032 // function template specialization, which is added to the set of
9033 // overloaded functions considered.
9034 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009035 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009036 if (Sema::TemplateDeductionResult Result
9037 = S.DeduceTemplateArguments(FunctionTemplate,
9038 &OvlExplicitTemplateArgs,
9039 TargetFunctionType, Specialization,
9040 Info)) {
9041 // FIXME: make a note of the failed deduction for diagnostics.
9042 (void)Result;
9043 return false;
9044 }
9045
9046 // Template argument deduction ensures that we have an exact match.
9047 // This function template specicalization works.
9048 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9049 assert(TargetFunctionType
9050 == Context.getCanonicalType(Specialization->getType()));
9051 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9052 return true;
9053 }
9054
9055 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9056 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009058 // Skip non-static functions when converting to pointer, and static
9059 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009060 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9061 return false;
9062 }
9063 else if (TargetTypeIsNonStaticMemberFunction)
9064 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009065
Chandler Carruthbd647292009-12-29 06:17:27 +00009066 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009067 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009068 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9069 if (S.CheckCUDATarget(Caller, FunDecl))
9070 return false;
9071
Douglas Gregor43c79c22009-12-09 00:47:37 +00009072 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009073 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9074 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009075 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9076 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009077 Matches.push_back(std::make_pair(CurAccessFunPair,
9078 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009079 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009080 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009081 }
Mike Stump1eb44332009-09-09 15:08:12 +00009082 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009083
9084 return false;
9085 }
9086
9087 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9088 bool Ret = false;
9089
9090 // If the overload expression doesn't have the form of a pointer to
9091 // member, don't try to convert it to a pointer-to-member type.
9092 if (IsInvalidFormOfPointerToMemberFunction())
9093 return false;
9094
9095 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9096 E = OvlExpr->decls_end();
9097 I != E; ++I) {
9098 // Look through any using declarations to find the underlying function.
9099 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9100
9101 // C++ [over.over]p3:
9102 // Non-member functions and static member functions match
9103 // targets of type "pointer-to-function" or "reference-to-function."
9104 // Nonstatic member functions match targets of
9105 // type "pointer-to-member-function."
9106 // Note that according to DR 247, the containing class does not matter.
9107 if (FunctionTemplateDecl *FunctionTemplate
9108 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9109 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9110 Ret = true;
9111 }
9112 // If we have explicit template arguments supplied, skip non-templates.
9113 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9114 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9115 Ret = true;
9116 }
9117 assert(Ret || Matches.empty());
9118 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009119 }
9120
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009121 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009122 // [...] and any given function template specialization F1 is
9123 // eliminated if the set contains a second function template
9124 // specialization whose function template is more specialized
9125 // than the function template of F1 according to the partial
9126 // ordering rules of 14.5.5.2.
9127
9128 // The algorithm specified above is quadratic. We instead use a
9129 // two-pass algorithm (similar to the one used to identify the
9130 // best viable function in an overload set) that identifies the
9131 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009132
9133 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9134 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9135 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009136
John McCallc373d482010-01-27 01:50:18 +00009137 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009138 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9139 TPOC_Other, 0, SourceExpr->getLocStart(),
9140 S.PDiag(),
9141 S.PDiag(diag::err_addr_ovl_ambiguous)
9142 << Matches[0].second->getDeclName(),
9143 S.PDiag(diag::note_ovl_candidate)
9144 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009145 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009146
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009147 if (Result != MatchesCopy.end()) {
9148 // Make it the first and only element
9149 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9150 Matches[0].second = cast<FunctionDecl>(*Result);
9151 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009152 }
9153 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009154
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009155 void EliminateAllTemplateMatches() {
9156 // [...] any function template specializations in the set are
9157 // eliminated if the set also contains a non-template function, [...]
9158 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9159 if (Matches[I].second->getPrimaryTemplate() == 0)
9160 ++I;
9161 else {
9162 Matches[I] = Matches[--N];
9163 Matches.set_size(N);
9164 }
9165 }
9166 }
9167
9168public:
9169 void ComplainNoMatchesFound() const {
9170 assert(Matches.empty());
9171 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9172 << OvlExpr->getName() << TargetFunctionType
9173 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009174 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009175 }
9176
9177 bool IsInvalidFormOfPointerToMemberFunction() const {
9178 return TargetTypeIsNonStaticMemberFunction &&
9179 !OvlExprInfo.HasFormOfMemberPointer;
9180 }
9181
9182 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9183 // TODO: Should we condition this on whether any functions might
9184 // have matched, or is it more appropriate to do that in callers?
9185 // TODO: a fixit wouldn't hurt.
9186 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9187 << TargetType << OvlExpr->getSourceRange();
9188 }
9189
9190 void ComplainOfInvalidConversion() const {
9191 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9192 << OvlExpr->getName() << TargetType;
9193 }
9194
9195 void ComplainMultipleMatchesFound() const {
9196 assert(Matches.size() > 1);
9197 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9198 << OvlExpr->getName()
9199 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009200 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009201 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009202
9203 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9204
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009205 int getNumMatches() const { return Matches.size(); }
9206
9207 FunctionDecl* getMatchingFunctionDecl() const {
9208 if (Matches.size() != 1) return 0;
9209 return Matches[0].second;
9210 }
9211
9212 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9213 if (Matches.size() != 1) return 0;
9214 return &Matches[0].first;
9215 }
9216};
9217
9218/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9219/// an overloaded function (C++ [over.over]), where @p From is an
9220/// expression with overloaded function type and @p ToType is the type
9221/// we're trying to resolve to. For example:
9222///
9223/// @code
9224/// int f(double);
9225/// int f(int);
9226///
9227/// int (*pfd)(double) = f; // selects f(double)
9228/// @endcode
9229///
9230/// This routine returns the resulting FunctionDecl if it could be
9231/// resolved, and NULL otherwise. When @p Complain is true, this
9232/// routine will emit diagnostics if there is an error.
9233FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009234Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9235 QualType TargetType,
9236 bool Complain,
9237 DeclAccessPair &FoundResult,
9238 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009239 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009240
9241 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9242 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009243 int NumMatches = Resolver.getNumMatches();
9244 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009245 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009246 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9247 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9248 else
9249 Resolver.ComplainNoMatchesFound();
9250 }
9251 else if (NumMatches > 1 && Complain)
9252 Resolver.ComplainMultipleMatchesFound();
9253 else if (NumMatches == 1) {
9254 Fn = Resolver.getMatchingFunctionDecl();
9255 assert(Fn);
9256 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009257 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009258 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009259 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009260
9261 if (pHadMultipleCandidates)
9262 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009263 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009264}
9265
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009266/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009267/// resolve that overloaded function expression down to a single function.
9268///
9269/// This routine can only resolve template-ids that refer to a single function
9270/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009271/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009272/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009273FunctionDecl *
9274Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9275 bool Complain,
9276 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009277 // C++ [over.over]p1:
9278 // [...] [Note: any redundant set of parentheses surrounding the
9279 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009280 // C++ [over.over]p1:
9281 // [...] The overloaded function name can be preceded by the &
9282 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009283
Douglas Gregor4b52e252009-12-21 23:17:24 +00009284 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009285 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009286 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009287
9288 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009289 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009290
Douglas Gregor4b52e252009-12-21 23:17:24 +00009291 // Look through all of the overloaded functions, searching for one
9292 // whose type matches exactly.
9293 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009294 for (UnresolvedSetIterator I = ovl->decls_begin(),
9295 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009296 // C++0x [temp.arg.explicit]p3:
9297 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009298 // where deduction is not done, if a template argument list is
9299 // specified and it, along with any default template arguments,
9300 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009301 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009302 FunctionTemplateDecl *FunctionTemplate
9303 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009304
Douglas Gregor4b52e252009-12-21 23:17:24 +00009305 // C++ [over.over]p2:
9306 // If the name is a function template, template argument deduction is
9307 // done (14.8.2.2), and if the argument deduction succeeds, the
9308 // resulting template argument list is used to generate a single
9309 // function template specialization, which is added to the set of
9310 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009311 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009312 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009313 if (TemplateDeductionResult Result
9314 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9315 Specialization, Info)) {
9316 // FIXME: make a note of the failed deduction for diagnostics.
9317 (void)Result;
9318 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009319 }
9320
John McCall864c0412011-04-26 20:42:42 +00009321 assert(Specialization && "no specialization and no error?");
9322
Douglas Gregor4b52e252009-12-21 23:17:24 +00009323 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009324 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009325 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009326 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9327 << ovl->getName();
9328 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009329 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009330 return 0;
John McCall864c0412011-04-26 20:42:42 +00009331 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009332
John McCall864c0412011-04-26 20:42:42 +00009333 Matched = Specialization;
9334 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009335 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009336
Douglas Gregor4b52e252009-12-21 23:17:24 +00009337 return Matched;
9338}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009339
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009340
9341
9342
John McCall6dbba4f2011-10-11 23:14:30 +00009343// Resolve and fix an overloaded expression that can be resolved
9344// because it identifies a single function template specialization.
9345//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009346// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009347//
9348// Return true if it was logically possible to so resolve the
9349// expression, regardless of whether or not it succeeded. Always
9350// returns true if 'complain' is set.
9351bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9352 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9353 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009354 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009355 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009356 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009357
John McCall6dbba4f2011-10-11 23:14:30 +00009358 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009359
John McCall864c0412011-04-26 20:42:42 +00009360 DeclAccessPair found;
9361 ExprResult SingleFunctionExpression;
9362 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9363 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009364 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009365 SrcExpr = ExprError();
9366 return true;
9367 }
John McCall864c0412011-04-26 20:42:42 +00009368
9369 // It is only correct to resolve to an instance method if we're
9370 // resolving a form that's permitted to be a pointer to member.
9371 // Otherwise we'll end up making a bound member expression, which
9372 // is illegal in all the contexts we resolve like this.
9373 if (!ovl.HasFormOfMemberPointer &&
9374 isa<CXXMethodDecl>(fn) &&
9375 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009376 if (!complain) return false;
9377
9378 Diag(ovl.Expression->getExprLoc(),
9379 diag::err_bound_member_function)
9380 << 0 << ovl.Expression->getSourceRange();
9381
9382 // TODO: I believe we only end up here if there's a mix of
9383 // static and non-static candidates (otherwise the expression
9384 // would have 'bound member' type, not 'overload' type).
9385 // Ideally we would note which candidate was chosen and why
9386 // the static candidates were rejected.
9387 SrcExpr = ExprError();
9388 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009389 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009390
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009391 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009392 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009393 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009394
9395 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009396 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009397 SingleFunctionExpression =
9398 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009399 if (SingleFunctionExpression.isInvalid()) {
9400 SrcExpr = ExprError();
9401 return true;
9402 }
9403 }
John McCall864c0412011-04-26 20:42:42 +00009404 }
9405
9406 if (!SingleFunctionExpression.isUsable()) {
9407 if (complain) {
9408 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9409 << ovl.Expression->getName()
9410 << DestTypeForComplaining
9411 << OpRangeForComplaining
9412 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009413 NoteAllOverloadCandidates(SrcExpr.get());
9414
9415 SrcExpr = ExprError();
9416 return true;
9417 }
9418
9419 return false;
John McCall864c0412011-04-26 20:42:42 +00009420 }
9421
John McCall6dbba4f2011-10-11 23:14:30 +00009422 SrcExpr = SingleFunctionExpression;
9423 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009424}
9425
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009426/// \brief Add a single candidate to the overload set.
9427static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009428 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009429 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009430 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009431 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009432 bool PartialOverloading,
9433 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009434 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009435 if (isa<UsingShadowDecl>(Callee))
9436 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9437
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009438 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009439 if (ExplicitTemplateArgs) {
9440 assert(!KnownValid && "Explicit template arguments?");
9441 return;
9442 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009443 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9444 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009445 return;
John McCallba135432009-11-21 08:51:07 +00009446 }
9447
9448 if (FunctionTemplateDecl *FuncTemplate
9449 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009450 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009451 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009452 return;
9453 }
9454
Richard Smith2ced0442011-06-26 22:19:54 +00009455 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009456}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009457
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009458/// \brief Add the overload candidates named by callee and/or found by argument
9459/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009460void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009461 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009462 OverloadCandidateSet &CandidateSet,
9463 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009464
9465#ifndef NDEBUG
9466 // Verify that ArgumentDependentLookup is consistent with the rules
9467 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009468 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009469 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9470 // and let Y be the lookup set produced by argument dependent
9471 // lookup (defined as follows). If X contains
9472 //
9473 // -- a declaration of a class member, or
9474 //
9475 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009476 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009477 //
9478 // -- a declaration that is neither a function or a function
9479 // template
9480 //
9481 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009482
John McCall3b4294e2009-12-16 12:17:52 +00009483 if (ULE->requiresADL()) {
9484 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9485 E = ULE->decls_end(); I != E; ++I) {
9486 assert(!(*I)->getDeclContext()->isRecord());
9487 assert(isa<UsingShadowDecl>(*I) ||
9488 !(*I)->getDeclContext()->isFunctionOrMethod());
9489 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009490 }
9491 }
9492#endif
9493
John McCall3b4294e2009-12-16 12:17:52 +00009494 // It would be nice to avoid this copy.
9495 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009496 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009497 if (ULE->hasExplicitTemplateArgs()) {
9498 ULE->copyTemplateArgumentsInto(TABuffer);
9499 ExplicitTemplateArgs = &TABuffer;
9500 }
9501
9502 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9503 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009504 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9505 CandidateSet, PartialOverloading,
9506 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009507
John McCall3b4294e2009-12-16 12:17:52 +00009508 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009509 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009510 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009511 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009512 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009513}
John McCall578b69b2009-12-16 08:11:27 +00009514
Richard Smithf50e88a2011-06-05 22:42:48 +00009515/// Attempt to recover from an ill-formed use of a non-dependent name in a
9516/// template, where the non-dependent name was declared after the template
9517/// was defined. This is common in code written for a compilers which do not
9518/// correctly implement two-stage name lookup.
9519///
9520/// Returns true if a viable candidate was found and a diagnostic was issued.
9521static bool
9522DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9523 const CXXScopeSpec &SS, LookupResult &R,
9524 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009525 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009526 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9527 return false;
9528
9529 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009530 if (DC->isTransparentContext())
9531 continue;
9532
Richard Smithf50e88a2011-06-05 22:42:48 +00009533 SemaRef.LookupQualifiedName(R, DC);
9534
9535 if (!R.empty()) {
9536 R.suppressDiagnostics();
9537
9538 if (isa<CXXRecordDecl>(DC)) {
9539 // Don't diagnose names we find in classes; we get much better
9540 // diagnostics for these from DiagnoseEmptyLookup.
9541 R.clear();
9542 return false;
9543 }
9544
9545 OverloadCandidateSet Candidates(FnLoc);
9546 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9547 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009548 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009549 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009550
9551 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009552 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009553 // No viable functions. Don't bother the user with notes for functions
9554 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009555 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009556 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009557 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009558
9559 // Find the namespaces where ADL would have looked, and suggest
9560 // declaring the function there instead.
9561 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9562 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009563 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009564 AssociatedNamespaces,
9565 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009566 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009567 DeclContext *Std = SemaRef.getStdNamespace();
9568 for (Sema::AssociatedNamespaceSet::iterator
9569 it = AssociatedNamespaces.begin(),
9570 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009571 // Never suggest declaring a function within namespace 'std'.
9572 if (Std && Std->Encloses(*it))
9573 continue;
9574
9575 // Never suggest declaring a function within a namespace with a reserved
9576 // name, like __gnu_cxx.
9577 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9578 if (NS &&
9579 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9580 continue;
9581
9582 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009583 }
9584
9585 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9586 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009587 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009588 SemaRef.Diag(Best->Function->getLocation(),
9589 diag::note_not_found_by_two_phase_lookup)
9590 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009591 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009592 SemaRef.Diag(Best->Function->getLocation(),
9593 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009594 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009595 } else {
9596 // FIXME: It would be useful to list the associated namespaces here,
9597 // but the diagnostics infrastructure doesn't provide a way to produce
9598 // a localized representation of a list of items.
9599 SemaRef.Diag(Best->Function->getLocation(),
9600 diag::note_not_found_by_two_phase_lookup)
9601 << R.getLookupName() << 2;
9602 }
9603
9604 // Try to recover by calling this function.
9605 return true;
9606 }
9607
9608 R.clear();
9609 }
9610
9611 return false;
9612}
9613
9614/// Attempt to recover from ill-formed use of a non-dependent operator in a
9615/// template, where the non-dependent operator was declared after the template
9616/// was defined.
9617///
9618/// Returns true if a viable candidate was found and a diagnostic was issued.
9619static bool
9620DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9621 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009622 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009623 DeclarationName OpName =
9624 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9625 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9626 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009627 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009628}
9629
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009630namespace {
9631// Callback to limit the allowed keywords and to only accept typo corrections
9632// that are keywords or whose decls refer to functions (or template functions)
9633// that accept the given number of arguments.
9634class RecoveryCallCCC : public CorrectionCandidateCallback {
9635 public:
9636 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9637 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009638 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009639 WantRemainingKeywords = false;
9640 }
9641
9642 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9643 if (!candidate.getCorrectionDecl())
9644 return candidate.isKeyword();
9645
9646 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9647 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9648 FunctionDecl *FD = 0;
9649 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9650 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9651 FD = FTD->getTemplatedDecl();
9652 if (!HasExplicitTemplateArgs && !FD) {
9653 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9654 // If the Decl is neither a function nor a template function,
9655 // determine if it is a pointer or reference to a function. If so,
9656 // check against the number of arguments expected for the pointee.
9657 QualType ValType = cast<ValueDecl>(ND)->getType();
9658 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9659 ValType = ValType->getPointeeType();
9660 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9661 if (FPT->getNumArgs() == NumArgs)
9662 return true;
9663 }
9664 }
9665 if (FD && FD->getNumParams() >= NumArgs &&
9666 FD->getMinRequiredArguments() <= NumArgs)
9667 return true;
9668 }
9669 return false;
9670 }
9671
9672 private:
9673 unsigned NumArgs;
9674 bool HasExplicitTemplateArgs;
9675};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009676
9677// Callback that effectively disabled typo correction
9678class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9679 public:
9680 NoTypoCorrectionCCC() {
9681 WantTypeSpecifiers = false;
9682 WantExpressionKeywords = false;
9683 WantCXXNamedCasts = false;
9684 WantRemainingKeywords = false;
9685 }
9686
9687 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9688 return false;
9689 }
9690};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009691
9692class BuildRecoveryCallExprRAII {
9693 Sema &SemaRef;
9694public:
9695 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9696 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9697 SemaRef.IsBuildingRecoveryCallExpr = true;
9698 }
9699
9700 ~BuildRecoveryCallExprRAII() {
9701 SemaRef.IsBuildingRecoveryCallExpr = false;
9702 }
9703};
9704
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009705}
9706
John McCall578b69b2009-12-16 08:11:27 +00009707/// Attempts to recover from a call where no functions were found.
9708///
9709/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009710static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009711BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009712 UnresolvedLookupExpr *ULE,
9713 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009714 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009715 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009716 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009717 // Do not try to recover if it is already building a recovery call.
9718 // This stops infinite loops for template instantiations like
9719 //
9720 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9721 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9722 //
9723 if (SemaRef.IsBuildingRecoveryCallExpr)
9724 return ExprError();
9725 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009726
9727 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009728 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009729 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009730
John McCall3b4294e2009-12-16 12:17:52 +00009731 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009732 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009733 if (ULE->hasExplicitTemplateArgs()) {
9734 ULE->copyTemplateArgumentsInto(TABuffer);
9735 ExplicitTemplateArgs = &TABuffer;
9736 }
9737
John McCall578b69b2009-12-16 08:11:27 +00009738 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9739 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009740 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009741 NoTypoCorrectionCCC RejectAll;
9742 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9743 (CorrectionCandidateCallback*)&Validator :
9744 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009745 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009746 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009747 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009748 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009749 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009750 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009751
John McCall3b4294e2009-12-16 12:17:52 +00009752 assert(!R.empty() && "lookup results empty despite recovery");
9753
9754 // Build an implicit member call if appropriate. Just drop the
9755 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009756 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009757 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009758 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9759 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009760 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009761 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009762 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009763 else
9764 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9765
9766 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009767 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009768
9769 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009770 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009771 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009772 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009773 MultiExprArg(Args.data(), Args.size()),
9774 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009775}
Douglas Gregord7a95972010-06-08 17:35:15 +00009776
Sam Panzere1715b62012-08-21 00:52:01 +00009777/// \brief Constructs and populates an OverloadedCandidateSet from
9778/// the given function.
9779/// \returns true when an the ExprResult output parameter has been set.
9780bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9781 UnresolvedLookupExpr *ULE,
9782 Expr **Args, unsigned NumArgs,
9783 SourceLocation RParenLoc,
9784 OverloadCandidateSet *CandidateSet,
9785 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009786#ifndef NDEBUG
9787 if (ULE->requiresADL()) {
9788 // To do ADL, we must have found an unqualified name.
9789 assert(!ULE->getQualifier() && "qualified name with ADL");
9790
9791 // We don't perform ADL for implicit declarations of builtins.
9792 // Verify that this was correctly set up.
9793 FunctionDecl *F;
9794 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9795 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9796 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009797 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009798
John McCall3b4294e2009-12-16 12:17:52 +00009799 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009800 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009801 }
John McCall3b4294e2009-12-16 12:17:52 +00009802#endif
9803
John McCall5acb0c92011-10-17 18:40:02 +00009804 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009805 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9806 *Result = ExprError();
9807 return true;
9808 }
Douglas Gregor17330012009-02-04 15:01:18 +00009809
John McCall3b4294e2009-12-16 12:17:52 +00009810 // Add the functions denoted by the callee to the set of candidate
9811 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009812 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009813 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009814
9815 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009816 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9817 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009818 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009819 // In Microsoft mode, if we are inside a template class member function then
9820 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009821 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009822 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009823 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009824 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009825 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9826 llvm::makeArrayRef(Args, NumArgs),
9827 Context.DependentTy, VK_RValue,
9828 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009829 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009830 *Result = Owned(CE);
9831 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009832 }
Sam Panzere1715b62012-08-21 00:52:01 +00009833 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009834 }
John McCall578b69b2009-12-16 08:11:27 +00009835
John McCall5acb0c92011-10-17 18:40:02 +00009836 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009837 return false;
9838}
John McCall5acb0c92011-10-17 18:40:02 +00009839
Sam Panzere1715b62012-08-21 00:52:01 +00009840/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9841/// the completed call expression. If overload resolution fails, emits
9842/// diagnostics and returns ExprError()
9843static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9844 UnresolvedLookupExpr *ULE,
9845 SourceLocation LParenLoc,
9846 Expr **Args, unsigned NumArgs,
9847 SourceLocation RParenLoc,
9848 Expr *ExecConfig,
9849 OverloadCandidateSet *CandidateSet,
9850 OverloadCandidateSet::iterator *Best,
9851 OverloadingResult OverloadResult,
9852 bool AllowTypoCorrection) {
9853 if (CandidateSet->empty())
9854 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9855 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9856 RParenLoc, /*EmptyLookup=*/true,
9857 AllowTypoCorrection);
9858
9859 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009860 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009861 FunctionDecl *FDecl = (*Best)->Function;
9862 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9863 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9864 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9865 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9866 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9867 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009868 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009869
Richard Smithf50e88a2011-06-05 22:42:48 +00009870 case OR_No_Viable_Function: {
9871 // Try to recover by looking for viable functions which the user might
9872 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009873 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009874 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9875 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009876 /*EmptyLookup=*/false,
9877 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009878 if (!Recovery.isInvalid())
9879 return Recovery;
9880
Sam Panzere1715b62012-08-21 00:52:01 +00009881 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009882 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009883 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009884 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9885 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009886 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009887 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009888
9889 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009890 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009891 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009892 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9893 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009894 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009895
Sam Panzere1715b62012-08-21 00:52:01 +00009896 case OR_Deleted: {
9897 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9898 << (*Best)->Function->isDeleted()
9899 << ULE->getName()
9900 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9901 << Fn->getSourceRange();
9902 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9903 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009904
Sam Panzere1715b62012-08-21 00:52:01 +00009905 // We emitted an error for the unvailable/deleted function call but keep
9906 // the call in the AST.
9907 FunctionDecl *FDecl = (*Best)->Function;
9908 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9909 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9910 RParenLoc, ExecConfig);
9911 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009912 }
9913
Douglas Gregorff331c12010-07-25 18:17:45 +00009914 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009915 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009916}
9917
Sam Panzere1715b62012-08-21 00:52:01 +00009918/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9919/// (which eventually refers to the declaration Func) and the call
9920/// arguments Args/NumArgs, attempt to resolve the function call down
9921/// to a specific function. If overload resolution succeeds, returns
9922/// the call expression produced by overload resolution.
9923/// Otherwise, emits diagnostics and returns ExprError.
9924ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9925 UnresolvedLookupExpr *ULE,
9926 SourceLocation LParenLoc,
9927 Expr **Args, unsigned NumArgs,
9928 SourceLocation RParenLoc,
9929 Expr *ExecConfig,
9930 bool AllowTypoCorrection) {
9931 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9932 ExprResult result;
9933
9934 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9935 &CandidateSet, &result))
9936 return result;
9937
9938 OverloadCandidateSet::iterator Best;
9939 OverloadingResult OverloadResult =
9940 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9941
9942 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9943 RParenLoc, ExecConfig, &CandidateSet,
9944 &Best, OverloadResult,
9945 AllowTypoCorrection);
9946}
9947
John McCall6e266892010-01-26 03:27:55 +00009948static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009949 return Functions.size() > 1 ||
9950 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9951}
9952
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009953/// \brief Create a unary operation that may resolve to an overloaded
9954/// operator.
9955///
9956/// \param OpLoc The location of the operator itself (e.g., '*').
9957///
9958/// \param OpcIn The UnaryOperator::Opcode that describes this
9959/// operator.
9960///
James Dennett40ae6662012-06-22 08:52:37 +00009961/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009962/// considered by overload resolution. The caller needs to build this
9963/// set based on the context using, e.g.,
9964/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9965/// set should not contain any member functions; those will be added
9966/// by CreateOverloadedUnaryOp().
9967///
James Dennett8da16872012-06-22 10:32:46 +00009968/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009969ExprResult
John McCall6e266892010-01-26 03:27:55 +00009970Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9971 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009972 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009973 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009974
9975 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9976 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9977 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009978 // TODO: provide better source location info.
9979 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009980
John McCall5acb0c92011-10-17 18:40:02 +00009981 if (checkPlaceholderForOverload(*this, Input))
9982 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009983
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009984 Expr *Args[2] = { Input, 0 };
9985 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009986
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009987 // For post-increment and post-decrement, add the implicit '0' as
9988 // the second argument, so that we know this is a post-increment or
9989 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009990 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009991 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009992 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9993 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009994 NumArgs = 2;
9995 }
9996
9997 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009998 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009999 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010000 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010001 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010002 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010003 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010004
John McCallc373d482010-01-27 01:50:18 +000010005 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010006 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010007 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010008 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010009 /*ADL*/ true, IsOverloaded(Fns),
10010 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010011 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010012 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010013 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010014 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010015 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010016 }
10017
10018 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010019 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010020
10021 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010022 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10023 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010024
10025 // Add operator candidates that are member functions.
10026 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10027
John McCall6e266892010-01-26 03:27:55 +000010028 // Add candidates from ADL.
10029 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010030 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010031 /*ExplicitTemplateArgs*/ 0,
10032 CandidateSet);
10033
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010034 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010035 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010036
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010037 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10038
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010039 // Perform overload resolution.
10040 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010041 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010042 case OR_Success: {
10043 // We found a built-in operator or an overloaded operator.
10044 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010045
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010046 if (FnDecl) {
10047 // We matched an overloaded operator. Build a call to that
10048 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010049
Eli Friedman5f2987c2012-02-02 03:46:19 +000010050 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010051
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010052 // Convert the arguments.
10053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010054 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010055
John Wiegley429bb272011-04-08 18:41:53 +000010056 ExprResult InputRes =
10057 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10058 Best->FoundDecl, Method);
10059 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010060 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010061 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010062 } else {
10063 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010064 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010065 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010066 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010067 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010068 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010069 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010070 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010071 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010072 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010073 }
10074
John McCallb697e082010-05-06 18:15:07 +000010075 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10076
John McCallf89e55a2010-11-18 06:31:45 +000010077 // Determine the result type.
10078 QualType ResultTy = FnDecl->getResultType();
10079 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10080 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010081
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010082 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010083 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010084 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010085 if (FnExpr.isInvalid())
10086 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010087
Eli Friedman4c3b8962009-11-18 03:58:17 +000010088 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010089 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010090 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010091 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010092 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010093
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010094 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010095 FnDecl))
10096 return ExprError();
10097
John McCall9ae2f072010-08-23 23:25:46 +000010098 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010099 } else {
10100 // We matched a built-in operator. Convert the arguments, then
10101 // break out so that we will build the appropriate built-in
10102 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010103 ExprResult InputRes =
10104 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10105 Best->Conversions[0], AA_Passing);
10106 if (InputRes.isInvalid())
10107 return ExprError();
10108 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010109 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010110 }
John Wiegley429bb272011-04-08 18:41:53 +000010111 }
10112
10113 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010114 // This is an erroneous use of an operator which can be overloaded by
10115 // a non-member function. Check for non-member operators which were
10116 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010117 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10118 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010119 // FIXME: Recover by calling the found function.
10120 return ExprError();
10121
John Wiegley429bb272011-04-08 18:41:53 +000010122 // No viable function; fall through to handling this as a
10123 // built-in operator, which will produce an error message for us.
10124 break;
10125
10126 case OR_Ambiguous:
10127 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10128 << UnaryOperator::getOpcodeStr(Opc)
10129 << Input->getType()
10130 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010131 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10132 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010133 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10134 return ExprError();
10135
10136 case OR_Deleted:
10137 Diag(OpLoc, diag::err_ovl_deleted_oper)
10138 << Best->Function->isDeleted()
10139 << UnaryOperator::getOpcodeStr(Opc)
10140 << getDeletedOrUnavailableSuffix(Best->Function)
10141 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010142 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10143 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010144 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010145 return ExprError();
10146 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010147
10148 // Either we found no viable overloaded operator or we matched a
10149 // built-in operator. In either case, fall through to trying to
10150 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010151 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010152}
10153
Douglas Gregor063daf62009-03-13 18:40:31 +000010154/// \brief Create a binary operation that may resolve to an overloaded
10155/// operator.
10156///
10157/// \param OpLoc The location of the operator itself (e.g., '+').
10158///
10159/// \param OpcIn The BinaryOperator::Opcode that describes this
10160/// operator.
10161///
James Dennett40ae6662012-06-22 08:52:37 +000010162/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010163/// considered by overload resolution. The caller needs to build this
10164/// set based on the context using, e.g.,
10165/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10166/// set should not contain any member functions; those will be added
10167/// by CreateOverloadedBinOp().
10168///
10169/// \param LHS Left-hand argument.
10170/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010171ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010172Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010173 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010174 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010175 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010176 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010177 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010178
10179 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10180 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10181 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10182
10183 // If either side is type-dependent, create an appropriate dependent
10184 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010185 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010186 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010187 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010188 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010189 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010190 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010191 Context.DependentTy,
10192 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010193 OpLoc,
10194 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010195
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010196 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10197 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010198 VK_LValue,
10199 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010200 Context.DependentTy,
10201 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010202 OpLoc,
10203 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010204 }
John McCall6e266892010-01-26 03:27:55 +000010205
10206 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010207 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010208 // TODO: provide better source location info in DNLoc component.
10209 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010210 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010211 = UnresolvedLookupExpr::Create(Context, NamingClass,
10212 NestedNameSpecifierLoc(), OpNameInfo,
10213 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010214 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010215 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10216 Context.DependentTy, VK_RValue,
10217 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010218 }
10219
John McCall5acb0c92011-10-17 18:40:02 +000010220 // Always do placeholder-like conversions on the RHS.
10221 if (checkPlaceholderForOverload(*this, Args[1]))
10222 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010223
John McCall3c3b7f92011-10-25 17:37:35 +000010224 // Do placeholder-like conversion on the LHS; note that we should
10225 // not get here with a PseudoObject LHS.
10226 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010227 if (checkPlaceholderForOverload(*this, Args[0]))
10228 return ExprError();
10229
Sebastian Redl275c2b42009-11-18 23:10:33 +000010230 // If this is the assignment operator, we only perform overload resolution
10231 // if the left-hand side is a class or enumeration type. This is actually
10232 // a hack. The standard requires that we do overload resolution between the
10233 // various built-in candidates, but as DR507 points out, this can lead to
10234 // problems. So we do it this way, which pretty much follows what GCC does.
10235 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010236 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010237 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010238
John McCall0e800c92010-12-04 08:14:53 +000010239 // If this is the .* operator, which is not overloadable, just
10240 // create a built-in binary operator.
10241 if (Opc == BO_PtrMemD)
10242 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10243
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010244 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010245 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010246
10247 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010248 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010249
10250 // Add operator candidates that are member functions.
10251 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10252
John McCall6e266892010-01-26 03:27:55 +000010253 // Add candidates from ADL.
10254 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010255 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010256 /*ExplicitTemplateArgs*/ 0,
10257 CandidateSet);
10258
Douglas Gregor063daf62009-03-13 18:40:31 +000010259 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010260 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010261
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010262 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10263
Douglas Gregor063daf62009-03-13 18:40:31 +000010264 // Perform overload resolution.
10265 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010266 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010267 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010268 // We found a built-in operator or an overloaded operator.
10269 FunctionDecl *FnDecl = Best->Function;
10270
10271 if (FnDecl) {
10272 // We matched an overloaded operator. Build a call to that
10273 // operator.
10274
Eli Friedman5f2987c2012-02-02 03:46:19 +000010275 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010276
Douglas Gregor063daf62009-03-13 18:40:31 +000010277 // Convert the arguments.
10278 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010279 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010280 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010281
Chandler Carruth6df868e2010-12-12 08:17:55 +000010282 ExprResult Arg1 =
10283 PerformCopyInitialization(
10284 InitializedEntity::InitializeParameter(Context,
10285 FnDecl->getParamDecl(0)),
10286 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010287 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010288 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010289
John Wiegley429bb272011-04-08 18:41:53 +000010290 ExprResult Arg0 =
10291 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10292 Best->FoundDecl, Method);
10293 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010294 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010295 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010296 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010297 } else {
10298 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010299 ExprResult Arg0 = PerformCopyInitialization(
10300 InitializedEntity::InitializeParameter(Context,
10301 FnDecl->getParamDecl(0)),
10302 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010303 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010304 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010305
Chandler Carruth6df868e2010-12-12 08:17:55 +000010306 ExprResult Arg1 =
10307 PerformCopyInitialization(
10308 InitializedEntity::InitializeParameter(Context,
10309 FnDecl->getParamDecl(1)),
10310 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010311 if (Arg1.isInvalid())
10312 return ExprError();
10313 Args[0] = LHS = Arg0.takeAs<Expr>();
10314 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010315 }
10316
John McCallb697e082010-05-06 18:15:07 +000010317 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10318
John McCallf89e55a2010-11-18 06:31:45 +000010319 // Determine the result type.
10320 QualType ResultTy = FnDecl->getResultType();
10321 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10322 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010323
10324 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010325 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10326 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010327 if (FnExpr.isInvalid())
10328 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010329
John McCall9ae2f072010-08-23 23:25:46 +000010330 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010331 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010332 Args, ResultTy, VK, OpLoc,
10333 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010334
10335 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010336 FnDecl))
10337 return ExprError();
10338
John McCall9ae2f072010-08-23 23:25:46 +000010339 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010340 } else {
10341 // We matched a built-in operator. Convert the arguments, then
10342 // break out so that we will build the appropriate built-in
10343 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010344 ExprResult ArgsRes0 =
10345 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10346 Best->Conversions[0], AA_Passing);
10347 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010348 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010349 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010350
John Wiegley429bb272011-04-08 18:41:53 +000010351 ExprResult ArgsRes1 =
10352 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10353 Best->Conversions[1], AA_Passing);
10354 if (ArgsRes1.isInvalid())
10355 return ExprError();
10356 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010357 break;
10358 }
10359 }
10360
Douglas Gregor33074752009-09-30 21:46:01 +000010361 case OR_No_Viable_Function: {
10362 // C++ [over.match.oper]p9:
10363 // If the operator is the operator , [...] and there are no
10364 // viable functions, then the operator is assumed to be the
10365 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010366 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010367 break;
10368
Chandler Carruth6df868e2010-12-12 08:17:55 +000010369 // For class as left operand for assignment or compound assigment
10370 // operator do not fall through to handling in built-in, but report that
10371 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010372 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010373 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010374 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010375 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10376 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010377 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010378 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010379 // This is an erroneous use of an operator which can be overloaded by
10380 // a non-member function. Check for non-member operators which were
10381 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010382 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010383 // FIXME: Recover by calling the found function.
10384 return ExprError();
10385
Douglas Gregor33074752009-09-30 21:46:01 +000010386 // No viable function; try to create a built-in operation, which will
10387 // produce an error. Then, show the non-viable candidates.
10388 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010389 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010390 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010391 "C++ binary operator overloading is missing candidates!");
10392 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010393 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010394 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010395 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010396 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010397
10398 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010399 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010400 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010401 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010402 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010403 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010404 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010405 return ExprError();
10406
10407 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010408 if (isImplicitlyDeleted(Best->Function)) {
10409 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10410 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010411 << Context.getRecordType(Method->getParent())
10412 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010413
Richard Smith0f46e642012-12-28 12:23:24 +000010414 // The user probably meant to call this special member. Just
10415 // explain why it's deleted.
10416 NoteDeletedFunction(Method);
10417 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010418 } else {
10419 Diag(OpLoc, diag::err_ovl_deleted_oper)
10420 << Best->Function->isDeleted()
10421 << BinaryOperator::getOpcodeStr(Opc)
10422 << getDeletedOrUnavailableSuffix(Best->Function)
10423 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10424 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010425 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010426 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010427 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010428 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010429
Douglas Gregor33074752009-09-30 21:46:01 +000010430 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010431 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010432}
10433
John McCall60d7b3a2010-08-24 06:29:42 +000010434ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010435Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10436 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010437 Expr *Base, Expr *Idx) {
10438 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010439 DeclarationName OpName =
10440 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10441
10442 // If either side is type-dependent, create an appropriate dependent
10443 // expression.
10444 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10445
John McCallc373d482010-01-27 01:50:18 +000010446 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010447 // CHECKME: no 'operator' keyword?
10448 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10449 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010450 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010451 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010452 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010453 /*ADL*/ true, /*Overloaded*/ false,
10454 UnresolvedSetIterator(),
10455 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010456 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010457
Sebastian Redlf322ed62009-10-29 20:17:01 +000010458 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010459 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010460 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010461 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010462 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010463 }
10464
John McCall5acb0c92011-10-17 18:40:02 +000010465 // Handle placeholders on both operands.
10466 if (checkPlaceholderForOverload(*this, Args[0]))
10467 return ExprError();
10468 if (checkPlaceholderForOverload(*this, Args[1]))
10469 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010470
Sebastian Redlf322ed62009-10-29 20:17:01 +000010471 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010472 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010473
10474 // Subscript can only be overloaded as a member function.
10475
10476 // Add operator candidates that are member functions.
10477 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10478
10479 // Add builtin operator candidates.
10480 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10481
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010482 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10483
Sebastian Redlf322ed62009-10-29 20:17:01 +000010484 // Perform overload resolution.
10485 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010486 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010487 case OR_Success: {
10488 // We found a built-in operator or an overloaded operator.
10489 FunctionDecl *FnDecl = Best->Function;
10490
10491 if (FnDecl) {
10492 // We matched an overloaded operator. Build a call to that
10493 // operator.
10494
Eli Friedman5f2987c2012-02-02 03:46:19 +000010495 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010496
John McCall9aa472c2010-03-19 07:35:19 +000010497 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010498 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010499
Sebastian Redlf322ed62009-10-29 20:17:01 +000010500 // Convert the arguments.
10501 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010502 ExprResult Arg0 =
10503 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10504 Best->FoundDecl, Method);
10505 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010506 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010507 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010508
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010509 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010510 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010511 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010512 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010513 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010514 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010515 Owned(Args[1]));
10516 if (InputInit.isInvalid())
10517 return ExprError();
10518
10519 Args[1] = InputInit.takeAs<Expr>();
10520
Sebastian Redlf322ed62009-10-29 20:17:01 +000010521 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010522 QualType ResultTy = FnDecl->getResultType();
10523 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10524 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010525
10526 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010527 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10528 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010529 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10530 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010531 OpLocInfo.getLoc(),
10532 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010533 if (FnExpr.isInvalid())
10534 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010535
John McCall9ae2f072010-08-23 23:25:46 +000010536 CXXOperatorCallExpr *TheCall =
10537 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010538 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010539 ResultTy, VK, RLoc,
10540 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010541
John McCall9ae2f072010-08-23 23:25:46 +000010542 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010543 FnDecl))
10544 return ExprError();
10545
John McCall9ae2f072010-08-23 23:25:46 +000010546 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010547 } else {
10548 // We matched a built-in operator. Convert the arguments, then
10549 // break out so that we will build the appropriate built-in
10550 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010551 ExprResult ArgsRes0 =
10552 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10553 Best->Conversions[0], AA_Passing);
10554 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010555 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010556 Args[0] = ArgsRes0.take();
10557
10558 ExprResult ArgsRes1 =
10559 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10560 Best->Conversions[1], AA_Passing);
10561 if (ArgsRes1.isInvalid())
10562 return ExprError();
10563 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010564
10565 break;
10566 }
10567 }
10568
10569 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010570 if (CandidateSet.empty())
10571 Diag(LLoc, diag::err_ovl_no_oper)
10572 << Args[0]->getType() << /*subscript*/ 0
10573 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10574 else
10575 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10576 << Args[0]->getType()
10577 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010579 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010580 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010581 }
10582
10583 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010584 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010585 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010586 << Args[0]->getType() << Args[1]->getType()
10587 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010588 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010589 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010590 return ExprError();
10591
10592 case OR_Deleted:
10593 Diag(LLoc, diag::err_ovl_deleted_oper)
10594 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010595 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010596 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010597 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010598 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010599 return ExprError();
10600 }
10601
10602 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010603 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010604}
10605
Douglas Gregor88a35142008-12-22 05:46:06 +000010606/// BuildCallToMemberFunction - Build a call to a member
10607/// function. MemExpr is the expression that refers to the member
10608/// function (and includes the object parameter), Args/NumArgs are the
10609/// arguments to the function call (not including the object
10610/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010611/// expression refers to a non-static member function or an overloaded
10612/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010613ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010614Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10615 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010616 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010617 assert(MemExprE->getType() == Context.BoundMemberTy ||
10618 MemExprE->getType() == Context.OverloadTy);
10619
Douglas Gregor88a35142008-12-22 05:46:06 +000010620 // Dig out the member expression. This holds both the object
10621 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010622 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010623
John McCall864c0412011-04-26 20:42:42 +000010624 // Determine whether this is a call to a pointer-to-member function.
10625 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10626 assert(op->getType() == Context.BoundMemberTy);
10627 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10628
10629 QualType fnType =
10630 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10631
10632 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10633 QualType resultType = proto->getCallResultType(Context);
10634 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10635
10636 // Check that the object type isn't more qualified than the
10637 // member function we're calling.
10638 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10639
10640 QualType objectType = op->getLHS()->getType();
10641 if (op->getOpcode() == BO_PtrMemI)
10642 objectType = objectType->castAs<PointerType>()->getPointeeType();
10643 Qualifiers objectQuals = objectType.getQualifiers();
10644
10645 Qualifiers difference = objectQuals - funcQuals;
10646 difference.removeObjCGCAttr();
10647 difference.removeAddressSpace();
10648 if (difference) {
10649 std::string qualsString = difference.getAsString();
10650 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10651 << fnType.getUnqualifiedType()
10652 << qualsString
10653 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10654 }
10655
10656 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010657 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10658 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010659 resultType, valueKind, RParenLoc);
10660
10661 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010662 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010663 call, 0))
10664 return ExprError();
10665
10666 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10667 return ExprError();
10668
10669 return MaybeBindToTemporary(call);
10670 }
10671
John McCall5acb0c92011-10-17 18:40:02 +000010672 UnbridgedCastsSet UnbridgedCasts;
10673 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10674 return ExprError();
10675
John McCall129e2df2009-11-30 22:42:35 +000010676 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010677 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010678 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010679 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010680 if (isa<MemberExpr>(NakedMemExpr)) {
10681 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010682 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010683 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010684 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010685 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010686 } else {
10687 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010688 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010689
John McCall701c89e2009-12-03 04:06:58 +000010690 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010691 Expr::Classification ObjectClassification
10692 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10693 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010694
Douglas Gregor88a35142008-12-22 05:46:06 +000010695 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010696 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010697
John McCallaa81e162009-12-01 22:10:20 +000010698 // FIXME: avoid copy.
10699 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10700 if (UnresExpr->hasExplicitTemplateArgs()) {
10701 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10702 TemplateArgs = &TemplateArgsBuffer;
10703 }
10704
John McCall129e2df2009-11-30 22:42:35 +000010705 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10706 E = UnresExpr->decls_end(); I != E; ++I) {
10707
John McCall701c89e2009-12-03 04:06:58 +000010708 NamedDecl *Func = *I;
10709 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10710 if (isa<UsingShadowDecl>(Func))
10711 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10712
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010713
Francois Pichetdbee3412011-01-18 05:04:39 +000010714 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010715 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010716 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10717 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010718 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010719 // If explicit template arguments were provided, we can't call a
10720 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010721 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010722 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010723
John McCall9aa472c2010-03-19 07:35:19 +000010724 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010725 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010726 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010727 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010728 } else {
John McCall129e2df2009-11-30 22:42:35 +000010729 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010730 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010731 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010732 llvm::makeArrayRef(Args, NumArgs),
10733 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010734 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010735 }
Douglas Gregordec06662009-08-21 18:42:58 +000010736 }
Mike Stump1eb44332009-09-09 15:08:12 +000010737
John McCall129e2df2009-11-30 22:42:35 +000010738 DeclarationName DeclName = UnresExpr->getMemberName();
10739
John McCall5acb0c92011-10-17 18:40:02 +000010740 UnbridgedCasts.restore();
10741
Douglas Gregor88a35142008-12-22 05:46:06 +000010742 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010743 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010744 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010745 case OR_Success:
10746 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010747 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010748 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010749 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010750 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010751 break;
10752
10753 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010754 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010755 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010756 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010757 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10758 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010759 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010760 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010761
10762 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010763 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010764 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010765 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10766 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010767 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010768 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010769
10770 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010771 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010772 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010773 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010774 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010775 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010776 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10777 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010778 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010779 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010780 }
10781
John McCall6bb80172010-03-30 21:47:33 +000010782 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010783
John McCallaa81e162009-12-01 22:10:20 +000010784 // If overload resolution picked a static member, build a
10785 // non-member call based on that function.
10786 if (Method->isStatic()) {
10787 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10788 Args, NumArgs, RParenLoc);
10789 }
10790
John McCall129e2df2009-11-30 22:42:35 +000010791 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010792 }
10793
John McCallf89e55a2010-11-18 06:31:45 +000010794 QualType ResultType = Method->getResultType();
10795 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10796 ResultType = ResultType.getNonLValueExprType(Context);
10797
Douglas Gregor88a35142008-12-22 05:46:06 +000010798 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010799 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010800 new (Context) CXXMemberCallExpr(Context, MemExprE,
10801 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010802 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010803
Anders Carlssoneed3e692009-10-10 00:06:20 +000010804 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010805 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010806 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010807 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010808
Douglas Gregor88a35142008-12-22 05:46:06 +000010809 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010810 // We only need to do this if there was actually an overload; otherwise
10811 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010812 if (!Method->isStatic()) {
10813 ExprResult ObjectArg =
10814 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10815 FoundDecl, Method);
10816 if (ObjectArg.isInvalid())
10817 return ExprError();
10818 MemExpr->setBase(ObjectArg.take());
10819 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010820
10821 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010822 const FunctionProtoType *Proto =
10823 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010824 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010825 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010826 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010827
Eli Friedmane61eb042012-02-18 04:48:30 +000010828 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10829
Richard Smith831421f2012-06-25 20:30:08 +000010830 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010831 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010832
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010833 if ((isa<CXXConstructorDecl>(CurContext) ||
10834 isa<CXXDestructorDecl>(CurContext)) &&
10835 TheCall->getMethodDecl()->isPure()) {
10836 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10837
Chandler Carruthae198062011-06-27 08:31:58 +000010838 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010839 Diag(MemExpr->getLocStart(),
10840 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10841 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10842 << MD->getParent()->getDeclName();
10843
10844 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010845 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010846 }
John McCall9ae2f072010-08-23 23:25:46 +000010847 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010848}
10849
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010850/// BuildCallToObjectOfClassType - Build a call to an object of class
10851/// type (C++ [over.call.object]), which can end up invoking an
10852/// overloaded function call operator (@c operator()) or performing a
10853/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010854ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010855Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010856 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010857 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010858 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010859 if (checkPlaceholderForOverload(*this, Obj))
10860 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010861 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010862
10863 UnbridgedCastsSet UnbridgedCasts;
10864 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10865 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010866
John Wiegley429bb272011-04-08 18:41:53 +000010867 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10868 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010869
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010870 // C++ [over.call.object]p1:
10871 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010872 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010873 // candidate functions includes at least the function call
10874 // operators of T. The function call operators of T are obtained by
10875 // ordinary lookup of the name operator() in the context of
10876 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010877 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010878 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010879
John Wiegley429bb272011-04-08 18:41:53 +000010880 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010881 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010882 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010883
John McCalla24dc2e2009-11-17 02:14:36 +000010884 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10885 LookupQualifiedName(R, Record->getDecl());
10886 R.suppressDiagnostics();
10887
Douglas Gregor593564b2009-11-15 07:48:03 +000010888 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010889 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010890 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10891 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010892 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010893 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010894
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010895 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010896 // In addition, for each (non-explicit in C++0x) conversion function
10897 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010898 //
10899 // operator conversion-type-id () cv-qualifier;
10900 //
10901 // where cv-qualifier is the same cv-qualification as, or a
10902 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010903 // denotes the type "pointer to function of (P1,...,Pn) returning
10904 // R", or the type "reference to pointer to function of
10905 // (P1,...,Pn) returning R", or the type "reference to function
10906 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010907 // is also considered as a candidate function. Similarly,
10908 // surrogate call functions are added to the set of candidate
10909 // functions for each conversion function declared in an
10910 // accessible base class provided the function is not hidden
10911 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010912 std::pair<CXXRecordDecl::conversion_iterator,
10913 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010914 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010915 for (CXXRecordDecl::conversion_iterator
10916 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010917 NamedDecl *D = *I;
10918 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10919 if (isa<UsingShadowDecl>(D))
10920 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010921
Douglas Gregor4a27d702009-10-21 06:18:39 +000010922 // Skip over templated conversion functions; they aren't
10923 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010924 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010925 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010926
John McCall701c89e2009-12-03 04:06:58 +000010927 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010928 if (!Conv->isExplicit()) {
10929 // Strip the reference type (if any) and then the pointer type (if
10930 // any) to get down to what might be a function type.
10931 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10932 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10933 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010934
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010935 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10936 {
10937 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010938 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10939 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010940 }
10941 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010942 }
Mike Stump1eb44332009-09-09 15:08:12 +000010943
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010944 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10945
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010946 // Perform overload resolution.
10947 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010948 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010949 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010950 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010951 // Overload resolution succeeded; we'll build the appropriate call
10952 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010953 break;
10954
10955 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010956 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010957 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010958 << Object.get()->getType() << /*call*/ 1
10959 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010960 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010961 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010962 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010963 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010964 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10965 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010966 break;
10967
10968 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010969 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010970 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010971 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010972 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10973 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010974 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010975
10976 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010977 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010978 diag::err_ovl_deleted_object_call)
10979 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010980 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010981 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010982 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010983 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10984 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010985 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010986 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010987
Douglas Gregorff331c12010-07-25 18:17:45 +000010988 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010989 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010990
John McCall5acb0c92011-10-17 18:40:02 +000010991 UnbridgedCasts.restore();
10992
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010993 if (Best->Function == 0) {
10994 // Since there is no function declaration, this is one of the
10995 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010996 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010997 = cast<CXXConversionDecl>(
10998 Best->Conversions[0].UserDefined.ConversionFunction);
10999
John Wiegley429bb272011-04-08 18:41:53 +000011000 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011001 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011002
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011003 // We selected one of the surrogate functions that converts the
11004 // object parameter to a function pointer. Perform the conversion
11005 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011006
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011007 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011008 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011009 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11010 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011011 if (Call.isInvalid())
11012 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011013 // Record usage of conversion in an implicit cast.
11014 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11015 CK_UserDefinedConversion,
11016 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011017
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011018 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011019 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011020 }
11021
Eli Friedman5f2987c2012-02-02 03:46:19 +000011022 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011023 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011024 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011025
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011026 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11027 // that calls this method, using Object for the implicit object
11028 // parameter and passing along the remaining arguments.
11029 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011030
11031 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011032 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011033 return ExprError();
11034
Chandler Carruth6df868e2010-12-12 08:17:55 +000011035 const FunctionProtoType *Proto =
11036 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011037
11038 unsigned NumArgsInProto = Proto->getNumArgs();
11039 unsigned NumArgsToCheck = NumArgs;
11040
11041 // Build the full argument list for the method call (the
11042 // implicit object parameter is placed at the beginning of the
11043 // list).
11044 Expr **MethodArgs;
11045 if (NumArgs < NumArgsInProto) {
11046 NumArgsToCheck = NumArgsInProto;
11047 MethodArgs = new Expr*[NumArgsInProto + 1];
11048 } else {
11049 MethodArgs = new Expr*[NumArgs + 1];
11050 }
John Wiegley429bb272011-04-08 18:41:53 +000011051 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011052 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11053 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011054
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011055 DeclarationNameInfo OpLocInfo(
11056 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11057 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011058 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011059 HadMultipleCandidates,
11060 OpLocInfo.getLoc(),
11061 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011062 if (NewFn.isInvalid())
11063 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011064
11065 // Once we've built TheCall, all of the expressions are properly
11066 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011067 QualType ResultTy = Method->getResultType();
11068 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11069 ResultTy = ResultTy.getNonLValueExprType(Context);
11070
John McCall9ae2f072010-08-23 23:25:46 +000011071 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011072 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011073 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011074 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011075 delete [] MethodArgs;
11076
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011077 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011078 Method))
11079 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011080
Douglas Gregor518fda12009-01-13 05:10:00 +000011081 // We may have default arguments. If so, we need to allocate more
11082 // slots in the call for them.
11083 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011084 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011085 else if (NumArgs > NumArgsInProto)
11086 NumArgsToCheck = NumArgsInProto;
11087
Chris Lattner312531a2009-04-12 08:11:20 +000011088 bool IsError = false;
11089
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011090 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011091 ExprResult ObjRes =
11092 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11093 Best->FoundDecl, Method);
11094 if (ObjRes.isInvalid())
11095 IsError = true;
11096 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011097 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011098 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011099
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011100 // Check the argument types.
11101 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011102 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011103 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011104 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011105
Douglas Gregor518fda12009-01-13 05:10:00 +000011106 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011107
John McCall60d7b3a2010-08-24 06:29:42 +000011108 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011109 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011110 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011111 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011112 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011113
Anders Carlsson3faa4862010-01-29 18:43:53 +000011114 IsError |= InputInit.isInvalid();
11115 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011116 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011117 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011118 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11119 if (DefArg.isInvalid()) {
11120 IsError = true;
11121 break;
11122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011123
Douglas Gregord47c47d2009-11-09 19:27:57 +000011124 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011125 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011126
11127 TheCall->setArg(i + 1, Arg);
11128 }
11129
11130 // If this is a variadic call, handle args passed through "...".
11131 if (Proto->isVariadic()) {
11132 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011133 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011134 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11135 IsError |= Arg.isInvalid();
11136 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011137 }
11138 }
11139
Chris Lattner312531a2009-04-12 08:11:20 +000011140 if (IsError) return true;
11141
Eli Friedmane61eb042012-02-18 04:48:30 +000011142 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11143
Richard Smith831421f2012-06-25 20:30:08 +000011144 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011145 return true;
11146
John McCall182f7092010-08-24 06:09:16 +000011147 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011148}
11149
Douglas Gregor8ba10742008-11-20 16:27:02 +000011150/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011151/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011152/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011153ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011154Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011155 assert(Base->getType()->isRecordType() &&
11156 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011157
John McCall5acb0c92011-10-17 18:40:02 +000011158 if (checkPlaceholderForOverload(*this, Base))
11159 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011160
John McCall5769d612010-02-08 23:07:23 +000011161 SourceLocation Loc = Base->getExprLoc();
11162
Douglas Gregor8ba10742008-11-20 16:27:02 +000011163 // C++ [over.ref]p1:
11164 //
11165 // [...] An expression x->m is interpreted as (x.operator->())->m
11166 // for a class object x of type T if T::operator->() exists and if
11167 // the operator is selected as the best match function by the
11168 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011169 DeclarationName OpName =
11170 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011171 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011172 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011173
John McCall5769d612010-02-08 23:07:23 +000011174 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011175 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011176 return ExprError();
11177
John McCalla24dc2e2009-11-17 02:14:36 +000011178 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11179 LookupQualifiedName(R, BaseRecord->getDecl());
11180 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011181
11182 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011183 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011184 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11185 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011186 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011187
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011188 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11189
Douglas Gregor8ba10742008-11-20 16:27:02 +000011190 // Perform overload resolution.
11191 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011192 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011193 case OR_Success:
11194 // Overload resolution succeeded; we'll build the call below.
11195 break;
11196
11197 case OR_No_Viable_Function:
11198 if (CandidateSet.empty())
11199 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011200 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011201 else
11202 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011203 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011204 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011205 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011206
11207 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011208 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11209 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011210 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011211 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011212
11213 case OR_Deleted:
11214 Diag(OpLoc, diag::err_ovl_deleted_oper)
11215 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011216 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011217 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011218 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011219 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011220 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011221 }
11222
Eli Friedman5f2987c2012-02-02 03:46:19 +000011223 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011224 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011225 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011226
Douglas Gregor8ba10742008-11-20 16:27:02 +000011227 // Convert the object parameter.
11228 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011229 ExprResult BaseResult =
11230 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11231 Best->FoundDecl, Method);
11232 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011233 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011234 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011235
Douglas Gregor8ba10742008-11-20 16:27:02 +000011236 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011237 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011238 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011239 if (FnExpr.isInvalid())
11240 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011241
John McCallf89e55a2010-11-18 06:31:45 +000011242 QualType ResultTy = Method->getResultType();
11243 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11244 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011245 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011246 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011247 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011248
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011249 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011250 Method))
11251 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011252
11253 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011254}
11255
Richard Smith36f5cfe2012-03-09 08:00:36 +000011256/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11257/// a literal operator described by the provided lookup results.
11258ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11259 DeclarationNameInfo &SuffixInfo,
11260 ArrayRef<Expr*> Args,
11261 SourceLocation LitEndLoc,
11262 TemplateArgumentListInfo *TemplateArgs) {
11263 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011264
Richard Smith36f5cfe2012-03-09 08:00:36 +000011265 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11266 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11267 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011268
Richard Smith36f5cfe2012-03-09 08:00:36 +000011269 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11270
Richard Smith36f5cfe2012-03-09 08:00:36 +000011271 // Perform overload resolution. This will usually be trivial, but might need
11272 // to perform substitutions for a literal operator template.
11273 OverloadCandidateSet::iterator Best;
11274 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11275 case OR_Success:
11276 case OR_Deleted:
11277 break;
11278
11279 case OR_No_Viable_Function:
11280 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11281 << R.getLookupName();
11282 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11283 return ExprError();
11284
11285 case OR_Ambiguous:
11286 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11287 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11288 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011289 }
11290
Richard Smith36f5cfe2012-03-09 08:00:36 +000011291 FunctionDecl *FD = Best->Function;
11292 MarkFunctionReferenced(UDSuffixLoc, FD);
11293 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011294
Richard Smith36f5cfe2012-03-09 08:00:36 +000011295 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11296 SuffixInfo.getLoc(),
11297 SuffixInfo.getInfo());
11298 if (Fn.isInvalid())
11299 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011300
11301 // Check the argument types. This should almost always be a no-op, except
11302 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011303 Expr *ConvArgs[2];
11304 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11305 ExprResult InputInit = PerformCopyInitialization(
11306 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11307 SourceLocation(), Args[ArgIdx]);
11308 if (InputInit.isInvalid())
11309 return true;
11310 ConvArgs[ArgIdx] = InputInit.take();
11311 }
11312
Richard Smith9fcce652012-03-07 08:35:16 +000011313 QualType ResultTy = FD->getResultType();
11314 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11315 ResultTy = ResultTy.getNonLValueExprType(Context);
11316
Richard Smith9fcce652012-03-07 08:35:16 +000011317 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011318 new (Context) UserDefinedLiteral(Context, Fn.take(),
11319 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011320 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11321
11322 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11323 return ExprError();
11324
Richard Smith831421f2012-06-25 20:30:08 +000011325 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011326 return ExprError();
11327
11328 return MaybeBindToTemporary(UDL);
11329}
11330
Sam Panzere1715b62012-08-21 00:52:01 +000011331/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11332/// given LookupResult is non-empty, it is assumed to describe a member which
11333/// will be invoked. Otherwise, the function will be found via argument
11334/// dependent lookup.
11335/// CallExpr is set to a valid expression and FRS_Success returned on success,
11336/// otherwise CallExpr is set to ExprError() and some non-success value
11337/// is returned.
11338Sema::ForRangeStatus
11339Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11340 SourceLocation RangeLoc, VarDecl *Decl,
11341 BeginEndFunction BEF,
11342 const DeclarationNameInfo &NameInfo,
11343 LookupResult &MemberLookup,
11344 OverloadCandidateSet *CandidateSet,
11345 Expr *Range, ExprResult *CallExpr) {
11346 CandidateSet->clear();
11347 if (!MemberLookup.empty()) {
11348 ExprResult MemberRef =
11349 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11350 /*IsPtr=*/false, CXXScopeSpec(),
11351 /*TemplateKWLoc=*/SourceLocation(),
11352 /*FirstQualifierInScope=*/0,
11353 MemberLookup,
11354 /*TemplateArgs=*/0);
11355 if (MemberRef.isInvalid()) {
11356 *CallExpr = ExprError();
11357 Diag(Range->getLocStart(), diag::note_in_for_range)
11358 << RangeLoc << BEF << Range->getType();
11359 return FRS_DiagnosticIssued;
11360 }
11361 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11362 if (CallExpr->isInvalid()) {
11363 *CallExpr = ExprError();
11364 Diag(Range->getLocStart(), diag::note_in_for_range)
11365 << RangeLoc << BEF << Range->getType();
11366 return FRS_DiagnosticIssued;
11367 }
11368 } else {
11369 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011370 UnresolvedLookupExpr *Fn =
11371 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11372 NestedNameSpecifierLoc(), NameInfo,
11373 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011374 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011375
11376 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11377 CandidateSet, CallExpr);
11378 if (CandidateSet->empty() || CandidateSetError) {
11379 *CallExpr = ExprError();
11380 return FRS_NoViableFunction;
11381 }
11382 OverloadCandidateSet::iterator Best;
11383 OverloadingResult OverloadResult =
11384 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11385
11386 if (OverloadResult == OR_No_Viable_Function) {
11387 *CallExpr = ExprError();
11388 return FRS_NoViableFunction;
11389 }
11390 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11391 Loc, 0, CandidateSet, &Best,
11392 OverloadResult,
11393 /*AllowTypoCorrection=*/false);
11394 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11395 *CallExpr = ExprError();
11396 Diag(Range->getLocStart(), diag::note_in_for_range)
11397 << RangeLoc << BEF << Range->getType();
11398 return FRS_DiagnosticIssued;
11399 }
11400 }
11401 return FRS_Success;
11402}
11403
11404
Douglas Gregor904eed32008-11-10 20:40:00 +000011405/// FixOverloadedFunctionReference - E is an expression that refers to
11406/// a C++ overloaded function (possibly with some parentheses and
11407/// perhaps a '&' around it). We have resolved the overloaded function
11408/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011409/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011410Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011411 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011412 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011413 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11414 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011415 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011416 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011417
Douglas Gregor699ee522009-11-20 19:42:02 +000011418 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011419 }
11420
Douglas Gregor699ee522009-11-20 19:42:02 +000011421 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011422 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11423 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011424 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011425 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011426 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011427 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011428 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011429 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011430
11431 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011432 ICE->getCastKind(),
11433 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011434 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011435 }
11436
Douglas Gregor699ee522009-11-20 19:42:02 +000011437 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011438 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011439 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11441 if (Method->isStatic()) {
11442 // Do nothing: static member functions aren't any different
11443 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011444 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011445 // Fix the sub expression, which really has to be an
11446 // UnresolvedLookupExpr holding an overloaded member function
11447 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011448 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11449 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011450 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011451 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011452
John McCallba135432009-11-21 08:51:07 +000011453 assert(isa<DeclRefExpr>(SubExpr)
11454 && "fixed to something other than a decl ref");
11455 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11456 && "fixed to a member ref with no nested name qualifier");
11457
11458 // We have taken the address of a pointer to member
11459 // function. Perform the computation here so that we get the
11460 // appropriate pointer to member type.
11461 QualType ClassType
11462 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11463 QualType MemPtrType
11464 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11465
John McCallf89e55a2010-11-18 06:31:45 +000011466 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11467 VK_RValue, OK_Ordinary,
11468 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011469 }
11470 }
John McCall6bb80172010-03-30 21:47:33 +000011471 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11472 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011473 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011474 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011475
John McCall2de56d12010-08-25 11:45:40 +000011476 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011477 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011478 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011479 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011480 }
John McCallba135432009-11-21 08:51:07 +000011481
11482 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011483 // FIXME: avoid copy.
11484 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011485 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011486 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11487 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011488 }
11489
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011490 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11491 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011492 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011493 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011494 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011495 ULE->getNameLoc(),
11496 Fn->getType(),
11497 VK_LValue,
11498 Found.getDecl(),
11499 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011500 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011501 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11502 return DRE;
John McCallba135432009-11-21 08:51:07 +000011503 }
11504
John McCall129e2df2009-11-30 22:42:35 +000011505 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011506 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011507 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11508 if (MemExpr->hasExplicitTemplateArgs()) {
11509 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11510 TemplateArgs = &TemplateArgsBuffer;
11511 }
John McCalld5532b62009-11-23 01:53:49 +000011512
John McCallaa81e162009-12-01 22:10:20 +000011513 Expr *Base;
11514
John McCallf89e55a2010-11-18 06:31:45 +000011515 // If we're filling in a static method where we used to have an
11516 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011517 if (MemExpr->isImplicitAccess()) {
11518 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011519 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11520 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011521 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011522 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011523 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011524 MemExpr->getMemberLoc(),
11525 Fn->getType(),
11526 VK_LValue,
11527 Found.getDecl(),
11528 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011529 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011530 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11531 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011532 } else {
11533 SourceLocation Loc = MemExpr->getMemberLoc();
11534 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011535 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011536 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011537 Base = new (Context) CXXThisExpr(Loc,
11538 MemExpr->getBaseType(),
11539 /*isImplicit=*/true);
11540 }
John McCallaa81e162009-12-01 22:10:20 +000011541 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011542 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011543
John McCallf5307512011-04-27 00:36:17 +000011544 ExprValueKind valueKind;
11545 QualType type;
11546 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11547 valueKind = VK_LValue;
11548 type = Fn->getType();
11549 } else {
11550 valueKind = VK_RValue;
11551 type = Context.BoundMemberTy;
11552 }
11553
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011554 MemberExpr *ME = MemberExpr::Create(Context, Base,
11555 MemExpr->isArrow(),
11556 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011557 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011558 Fn,
11559 Found,
11560 MemExpr->getMemberNameInfo(),
11561 TemplateArgs,
11562 type, valueKind, OK_Ordinary);
11563 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011564 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011565 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011567
John McCall3fa5cae2010-10-26 07:05:15 +000011568 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011569}
11570
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011571ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011572 DeclAccessPair Found,
11573 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011574 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011575}
11576
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011577} // end namespace clang