blob: 5d931cfcafb29af6a0bcd2942d2723577a35b39f [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
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000039/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 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);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000049
50 S.MarkDeclRefReferenced(DRE);
51 S.DiagnoseUseOfDecl(FoundDecl, Loc);
52
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000053 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000054 E = S.DefaultFunctionArrayConversion(E.take());
55 if (E.isInvalid())
56 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000057 return E;
John McCallf89e55a2010-11-18 06:31:45 +000058}
59
John McCall120d63c2010-08-24 20:38:10 +000060static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
61 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000062 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000063 bool CStyle,
64 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000065
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000066static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
67 QualType &ToType,
68 bool InOverloadResolution,
69 StandardConversionSequence &SCS,
70 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000071static OverloadingResult
72IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
73 UserDefinedConversionSequence& User,
74 OverloadCandidateSet& Conversions,
75 bool AllowExplicit);
76
77
78static ImplicitConversionSequence::CompareKind
79CompareStandardConversionSequences(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareQualificationConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88static ImplicitConversionSequence::CompareKind
89CompareDerivedToBaseConversions(Sema &S,
90 const StandardConversionSequence& SCS1,
91 const StandardConversionSequence& SCS2);
92
93
94
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000095/// GetConversionCategory - Retrieve the implicit conversion
96/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000097ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098GetConversionCategory(ImplicitConversionKind Kind) {
99 static const ImplicitConversionCategory
100 Category[(int)ICK_Num_Conversion_Kinds] = {
101 ICC_Identity,
102 ICC_Lvalue_Transformation,
103 ICC_Lvalue_Transformation,
104 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000105 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Qualification_Adjustment,
107 ICC_Promotion,
108 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000109 ICC_Promotion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000112 ICC_Conversion,
113 ICC_Conversion,
114 ICC_Conversion,
115 ICC_Conversion,
116 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000117 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000118 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000119 ICC_Conversion,
120 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000121 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000122 ICC_Conversion
123 };
124 return Category[(int)Kind];
125}
126
127/// GetConversionRank - Retrieve the implicit conversion rank
128/// corresponding to the given implicit conversion kind.
129ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
130 static const ImplicitConversionRank
131 Rank[(int)ICK_Num_Conversion_Kinds] = {
132 ICR_Exact_Match,
133 ICR_Exact_Match,
134 ICR_Exact_Match,
135 ICR_Exact_Match,
136 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000137 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138 ICR_Promotion,
139 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000140 ICR_Promotion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000148 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000149 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000150 ICR_Conversion,
151 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000152 ICR_Complex_Real_Conversion,
153 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000154 ICR_Conversion,
155 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000156 };
157 return Rank[(int)Kind];
158}
159
160/// GetImplicitConversionName - Return the name of this kind of
161/// implicit conversion.
162const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000163 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 "No conversion",
165 "Lvalue-to-rvalue",
166 "Array-to-pointer",
167 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000168 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 "Qualification",
170 "Integral promotion",
171 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000172 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 "Integral conversion",
174 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000175 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000176 "Floating-integral conversion",
177 "Pointer conversion",
178 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000179 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000180 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000181 "Derived-to-base conversion",
182 "Vector conversion",
183 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000184 "Complex-real conversion",
185 "Block Pointer conversion",
186 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000187 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000188 };
189 return Name[Kind];
190}
191
Douglas Gregor60d62c22008-10-31 16:23:19 +0000192/// StandardConversionSequence - Set the standard conversion
193/// sequence to the identity conversion.
194void StandardConversionSequence::setAsIdentityConversion() {
195 First = ICK_Identity;
196 Second = ICK_Identity;
197 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000198 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000199 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000200 ReferenceBinding = false;
201 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000202 IsLvalueReference = true;
203 BindsToFunctionLvalue = false;
204 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000205 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000206 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000207 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000208}
209
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210/// getRank - Retrieve the rank of this standard conversion sequence
211/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
212/// implicit conversions.
213ImplicitConversionRank StandardConversionSequence::getRank() const {
214 ImplicitConversionRank Rank = ICR_Exact_Match;
215 if (GetConversionRank(First) > Rank)
216 Rank = GetConversionRank(First);
217 if (GetConversionRank(Second) > Rank)
218 Rank = GetConversionRank(Second);
219 if (GetConversionRank(Third) > Rank)
220 Rank = GetConversionRank(Third);
221 return Rank;
222}
223
224/// isPointerConversionToBool - Determines whether this conversion is
225/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000226/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000228bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 // Note that FromType has not necessarily been transformed by the
230 // array-to-pointer or function-to-pointer implicit conversions, so
231 // check for their presence as well as checking whether FromType is
232 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000233 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000234 (getFromType()->isPointerType() ||
235 getFromType()->isObjCObjectPointerType() ||
236 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000237 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
239 return true;
240
241 return false;
242}
243
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000244/// isPointerConversionToVoidPointer - Determines whether this
245/// conversion is a conversion of a pointer to a void pointer. This is
246/// used as part of the ranking of standard conversion sequences (C++
247/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000248bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000249StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000250isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000251 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000252 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253
254 // Note that FromType has not necessarily been transformed by the
255 // array-to-pointer implicit conversion, so check for its presence
256 // and redo the conversion to get a pointer.
257 if (First == ICK_Array_To_Pointer)
258 FromType = Context.getArrayDecayedType(FromType);
259
Douglas Gregorf9af5242011-04-15 20:45:44 +0000260 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000261 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000262 return ToPtrType->getPointeeType()->isVoidType();
263
264 return false;
265}
266
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000267/// Skip any implicit casts which could be either part of a narrowing conversion
268/// or after one in an implicit conversion.
269static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
270 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
271 switch (ICE->getCastKind()) {
272 case CK_NoOp:
273 case CK_IntegralCast:
274 case CK_IntegralToBoolean:
275 case CK_IntegralToFloating:
276 case CK_FloatingToIntegral:
277 case CK_FloatingToBoolean:
278 case CK_FloatingCast:
279 Converted = ICE->getSubExpr();
280 continue;
281
282 default:
283 return Converted;
284 }
285 }
286
287 return Converted;
288}
289
290/// Check if this standard conversion sequence represents a narrowing
291/// conversion, according to C++11 [dcl.init.list]p7.
292///
293/// \param Ctx The AST context.
294/// \param Converted The result of applying this standard conversion sequence.
295/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
296/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000297/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
298/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000299NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000300StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
301 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000302 APValue &ConstantValue,
303 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000304 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000305
306 // C++11 [dcl.init.list]p7:
307 // A narrowing conversion is an implicit conversion ...
308 QualType FromType = getToType(0);
309 QualType ToType = getToType(1);
310 switch (Second) {
311 // -- from a floating-point type to an integer type, or
312 //
313 // -- from an integer type or unscoped enumeration type to a floating-point
314 // type, except where the source is a constant expression and the actual
315 // value after conversion will fit into the target type and will produce
316 // the original value when converted back to the original type, or
317 case ICK_Floating_Integral:
318 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
319 return NK_Type_Narrowing;
320 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
321 llvm::APSInt IntConstantValue;
322 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
323 if (Initializer &&
324 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
325 // Convert the integer to the floating type.
326 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
327 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
328 llvm::APFloat::rmNearestTiesToEven);
329 // And back.
330 llvm::APSInt ConvertedValue = IntConstantValue;
331 bool ignored;
332 Result.convertToInteger(ConvertedValue,
333 llvm::APFloat::rmTowardZero, &ignored);
334 // If the resulting value is different, this was a narrowing conversion.
335 if (IntConstantValue != ConvertedValue) {
336 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000337 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000338 return NK_Constant_Narrowing;
339 }
340 } else {
341 // Variables are always narrowings.
342 return NK_Variable_Narrowing;
343 }
344 }
345 return NK_Not_Narrowing;
346
347 // -- from long double to double or float, or from double to float, except
348 // where the source is a constant expression and the actual value after
349 // conversion is within the range of values that can be represented (even
350 // if it cannot be represented exactly), or
351 case ICK_Floating_Conversion:
352 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
353 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
354 // FromType is larger than ToType.
355 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
356 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
357 // Constant!
358 assert(ConstantValue.isFloat());
359 llvm::APFloat FloatVal = ConstantValue.getFloat();
360 // Convert the source value into the target type.
361 bool ignored;
362 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
363 Ctx.getFloatTypeSemantics(ToType),
364 llvm::APFloat::rmNearestTiesToEven, &ignored);
365 // If there was no overflow, the source value is within the range of
366 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000367 if (ConvertStatus & llvm::APFloat::opOverflow) {
368 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000369 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000370 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000371 } else {
372 return NK_Variable_Narrowing;
373 }
374 }
375 return NK_Not_Narrowing;
376
377 // -- from an integer type or unscoped enumeration type to an integer type
378 // that cannot represent all the values of the original type, except where
379 // the source is a constant expression and the actual value after
380 // conversion will fit into the target type and will produce the original
381 // value when converted back to the original type.
382 case ICK_Boolean_Conversion: // Bools are integers too.
383 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
384 // Boolean conversions can be from pointers and pointers to members
385 // [conv.bool], and those aren't considered narrowing conversions.
386 return NK_Not_Narrowing;
387 } // Otherwise, fall through to the integral case.
388 case ICK_Integral_Conversion: {
389 assert(FromType->isIntegralOrUnscopedEnumerationType());
390 assert(ToType->isIntegralOrUnscopedEnumerationType());
391 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
392 const unsigned FromWidth = Ctx.getIntWidth(FromType);
393 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
394 const unsigned ToWidth = Ctx.getIntWidth(ToType);
395
396 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000397 (FromWidth == ToWidth && FromSigned != ToSigned) ||
398 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000399 // Not all values of FromType can be represented in ToType.
400 llvm::APSInt InitializerValue;
401 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000402 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
403 // Such conversions on variables are always narrowing.
404 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000405 }
406 bool Narrowing = false;
407 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000408 // Negative -> unsigned is narrowing. Otherwise, more bits is never
409 // narrowing.
410 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000411 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000412 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000413 // Add a bit to the InitializerValue so we don't have to worry about
414 // signed vs. unsigned comparisons.
415 InitializerValue = InitializerValue.extend(
416 InitializerValue.getBitWidth() + 1);
417 // Convert the initializer to and from the target width and signed-ness.
418 llvm::APSInt ConvertedValue = InitializerValue;
419 ConvertedValue = ConvertedValue.trunc(ToWidth);
420 ConvertedValue.setIsSigned(ToSigned);
421 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
422 ConvertedValue.setIsSigned(InitializerValue.isSigned());
423 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000424 if (ConvertedValue != InitializerValue)
425 Narrowing = true;
426 }
427 if (Narrowing) {
428 ConstantType = Initializer->getType();
429 ConstantValue = APValue(InitializerValue);
430 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000431 }
432 }
433 return NK_Not_Narrowing;
434 }
435
436 default:
437 // Other kinds of conversions are not narrowings.
438 return NK_Not_Narrowing;
439 }
440}
441
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442/// DebugPrint - Print this standard conversion sequence to standard
443/// error. Useful for debugging overloading issues.
444void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000445 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000446 bool PrintedSomething = false;
447 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000448 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Second != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000457
458 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000459 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000460 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000461 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000462 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000464 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 PrintedSomething = true;
466 }
467
468 if (Third != ICK_Identity) {
469 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 PrintedSomething = true;
474 }
475
476 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000477 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478 }
479}
480
481/// DebugPrint - Print this user-defined conversion sequence to standard
482/// error. Useful for debugging overloading issues.
483void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000485 if (Before.First || Before.Second || Before.Third) {
486 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000487 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000489 if (ConversionFunction)
490 OS << '\'' << *ConversionFunction << '\'';
491 else
492 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000494 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 After.DebugPrint();
496 }
497}
498
499/// DebugPrint - Print this implicit conversion sequence to standard
500/// error. Useful for debugging overloading issues.
501void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000502 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 switch (ConversionKind) {
504 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 Standard.DebugPrint();
507 break;
508 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 UserDefined.DebugPrint();
511 break;
512 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000513 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 break;
John McCall1d318332010-01-12 00:44:57 +0000515 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000516 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000517 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000519 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520 break;
521 }
522
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000523 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524}
525
John McCall1d318332010-01-12 00:44:57 +0000526void AmbiguousConversionSequence::construct() {
527 new (&conversions()) ConversionSet();
528}
529
530void AmbiguousConversionSequence::destruct() {
531 conversions().~ConversionSet();
532}
533
534void
535AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
536 FromTypePtr = O.FromTypePtr;
537 ToTypePtr = O.ToTypePtr;
538 new (&conversions()) ConversionSet(O.conversions());
539}
540
Douglas Gregora9333192010-05-08 17:41:32 +0000541namespace {
542 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000543 // template argument information.
544 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000545 TemplateArgument FirstArg;
546 TemplateArgument SecondArg;
547 };
Richard Smith29805ca2013-01-31 05:19:49 +0000548 // Structure used by OverloadCandidate::DeductionFailureInfo to store
549 // template parameter and template argument information.
550 struct DFIParamWithArguments : DFIArguments {
551 TemplateParameter Param;
552 };
Douglas Gregora9333192010-05-08 17:41:32 +0000553}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554
Douglas Gregora9333192010-05-08 17:41:32 +0000555/// \brief Convert from Sema's representation of template deduction information
556/// to the form used in overload-candidate information.
557OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000558static MakeDeductionFailureInfo(ASTContext &Context,
559 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000560 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000561 OverloadCandidate::DeductionFailureInfo Result;
562 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000563 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000564 Result.Data = 0;
565 switch (TDK) {
566 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000567 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000568 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000569 case Sema::TDK_TooManyArguments:
570 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000571 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
Douglas Gregora9333192010-05-08 17:41:32 +0000573 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000574 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000575 Result.Data = Info.Param.getOpaqueValue();
576 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000577
Richard Smith29805ca2013-01-31 05:19:49 +0000578 case Sema::TDK_NonDeducedMismatch: {
579 // FIXME: Should allocate from normal heap so that we can free this later.
580 DFIArguments *Saved = new (Context) DFIArguments;
581 Saved->FirstArg = Info.FirstArg;
582 Saved->SecondArg = Info.SecondArg;
583 Result.Data = Saved;
584 break;
585 }
586
Douglas Gregora9333192010-05-08 17:41:32 +0000587 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000588 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000589 // FIXME: Should allocate from normal heap so that we can free this later.
590 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000591 Saved->Param = Info.Param;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Result.Data = Saved;
595 break;
596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
Douglas Gregora9333192010-05-08 17:41:32 +0000598 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000599 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000600 if (Info.hasSFINAEDiagnostic()) {
601 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
602 SourceLocation(), PartialDiagnostic::NullDiagnostic());
603 Info.takeSFINAEDiagnostic(*Diag);
604 Result.HasDiagnostic = true;
605 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000606 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
Douglas Gregora9333192010-05-08 17:41:32 +0000608 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000609 Result.Data = Info.Expression;
610 break;
611
Richard Smith29805ca2013-01-31 05:19:49 +0000612 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000613 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000614 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return Result;
617}
John McCall1d318332010-01-12 00:44:57 +0000618
Douglas Gregora9333192010-05-08 17:41:32 +0000619void OverloadCandidate::DeductionFailureInfo::Destroy() {
620 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
621 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000622 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000623 case Sema::TDK_InstantiationDepth:
624 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000625 case Sema::TDK_TooManyArguments:
626 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000627 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000628 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000630
Douglas Gregora9333192010-05-08 17:41:32 +0000631 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000632 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000633 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000634 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000635 Data = 0;
636 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000637
638 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000639 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000640 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000641 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
642 Diag->~PartialDiagnosticAt();
643 HasDiagnostic = false;
644 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000645 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000647 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000648 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000649 break;
650 }
651}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652
Richard Smithb8590f32012-05-07 09:03:25 +0000653PartialDiagnosticAt *
654OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
655 if (HasDiagnostic)
656 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
657 return 0;
658}
659
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000660TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000661OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000664 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000665 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000666 case Sema::TDK_TooManyArguments:
667 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000668 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000669 case Sema::TDK_NonDeducedMismatch:
670 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000671 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
Douglas Gregora9333192010-05-08 17:41:32 +0000673 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000674 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000675 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000676
677 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000679 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000680
Douglas Gregora9333192010-05-08 17:41:32 +0000681 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000682 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000683 break;
684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685
Douglas Gregora9333192010-05-08 17:41:32 +0000686 return TemplateParameter();
687}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688
Douglas Gregorec20f462010-05-08 20:07:26 +0000689TemplateArgumentList *
690OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000692 case Sema::TDK_Success:
693 case Sema::TDK_Invalid:
694 case Sema::TDK_InstantiationDepth:
695 case Sema::TDK_TooManyArguments:
696 case Sema::TDK_TooFewArguments:
697 case Sema::TDK_Incomplete:
698 case Sema::TDK_InvalidExplicitArguments:
699 case Sema::TDK_Inconsistent:
700 case Sema::TDK_Underqualified:
701 case Sema::TDK_NonDeducedMismatch:
702 case Sema::TDK_FailedOverloadResolution:
703 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000704
Richard Smith29805ca2013-01-31 05:19:49 +0000705 case Sema::TDK_SubstitutionFailure:
706 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707
Richard Smith29805ca2013-01-31 05:19:49 +0000708 // Unhandled
709 case Sema::TDK_MiscellaneousDeductionFailure:
710 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000711 }
712
713 return 0;
714}
715
Douglas Gregora9333192010-05-08 17:41:32 +0000716const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
718 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000719 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000720 case Sema::TDK_InstantiationDepth:
721 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000722 case Sema::TDK_TooManyArguments:
723 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000724 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000725 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000726 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000727 return 0;
728
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000730 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000731 case Sema::TDK_NonDeducedMismatch:
732 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000733
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000734 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 break;
737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000738
Douglas Gregora9333192010-05-08 17:41:32 +0000739 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000740}
Douglas Gregora9333192010-05-08 17:41:32 +0000741
742const TemplateArgument *
743OverloadCandidate::DeductionFailureInfo::getSecondArg() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000746 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000749 case Sema::TDK_TooManyArguments:
750 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000751 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000752 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000753 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000754 return 0;
755
Douglas Gregora9333192010-05-08 17:41:32 +0000756 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000757 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000758 case Sema::TDK_NonDeducedMismatch:
759 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000760
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000761 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000762 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000763 break;
764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765
Douglas Gregora9333192010-05-08 17:41:32 +0000766 return 0;
767}
768
Richard Smith0efa62f2013-01-31 04:03:12 +0000769Expr *
770OverloadCandidate::DeductionFailureInfo::getExpr() {
771 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
772 Sema::TDK_FailedOverloadResolution)
773 return static_cast<Expr*>(Data);
774
775 return 0;
776}
777
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000778void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000779 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000780 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
781 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000782 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
783 i->DeductionFailure.Destroy();
784 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000785}
786
787void OverloadCandidateSet::clear() {
788 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000789 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000790 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000791 Functions.clear();
792}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000793
John McCall5acb0c92011-10-17 18:40:02 +0000794namespace {
795 class UnbridgedCastsSet {
796 struct Entry {
797 Expr **Addr;
798 Expr *Saved;
799 };
800 SmallVector<Entry, 2> Entries;
801
802 public:
803 void save(Sema &S, Expr *&E) {
804 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
805 Entry entry = { &E, E };
806 Entries.push_back(entry);
807 E = S.stripARCUnbridgedCast(E);
808 }
809
810 void restore() {
811 for (SmallVectorImpl<Entry>::iterator
812 i = Entries.begin(), e = Entries.end(); i != e; ++i)
813 *i->Addr = i->Saved;
814 }
815 };
816}
817
818/// checkPlaceholderForOverload - Do any interesting placeholder-like
819/// preprocessing on the given expression.
820///
821/// \param unbridgedCasts a collection to which to add unbridged casts;
822/// without this, they will be immediately diagnosed as errors
823///
824/// Return true on unrecoverable error.
825static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
826 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000827 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
828 // We can't handle overloaded expressions here because overload
829 // resolution might reasonably tweak them.
830 if (placeholder->getKind() == BuiltinType::Overload) return false;
831
832 // If the context potentially accepts unbridged ARC casts, strip
833 // the unbridged cast and add it to the collection for later restoration.
834 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
835 unbridgedCasts) {
836 unbridgedCasts->save(S, E);
837 return false;
838 }
839
840 // Go ahead and check everything else.
841 ExprResult result = S.CheckPlaceholderExpr(E);
842 if (result.isInvalid())
843 return true;
844
845 E = result.take();
846 return false;
847 }
848
849 // Nothing to do.
850 return false;
851}
852
853/// checkArgPlaceholdersForOverload - Check a set of call operands for
854/// placeholders.
855static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
856 unsigned numArgs,
857 UnbridgedCastsSet &unbridged) {
858 for (unsigned i = 0; i != numArgs; ++i)
859 if (checkPlaceholderForOverload(S, args[i], &unbridged))
860 return true;
861
862 return false;
863}
864
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000866// overload of the declarations in Old. This routine returns false if
867// New and Old cannot be overloaded, e.g., if New has the same
868// signature as some function in Old (C++ 1.3.10) or if the Old
869// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000870// it does return false, MatchedDecl will point to the decl that New
871// cannot be overloaded with. This decl may be a UsingShadowDecl on
872// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000873//
874// Example: Given the following input:
875//
876// void f(int, float); // #1
877// void f(int, int); // #2
878// int f(int, int); // #3
879//
880// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000881// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000882//
John McCall51fa86f2009-12-02 08:47:38 +0000883// When we process #2, Old contains only the FunctionDecl for #1. By
884// comparing the parameter types, we see that #1 and #2 are overloaded
885// (since they have different signatures), so this routine returns
886// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000887//
John McCall51fa86f2009-12-02 08:47:38 +0000888// When we process #3, Old is an overload set containing #1 and #2. We
889// compare the signatures of #3 to #1 (they're overloaded, so we do
890// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
891// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000892// signature), IsOverload returns false and MatchedDecl will be set to
893// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000894//
895// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
896// into a class by a using declaration. The rules for whether to hide
897// shadow declarations ignore some properties which otherwise figure
898// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000899Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000900Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
901 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000902 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000903 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000904 NamedDecl *OldD = *I;
905
906 bool OldIsUsingDecl = false;
907 if (isa<UsingShadowDecl>(OldD)) {
908 OldIsUsingDecl = true;
909
910 // We can always introduce two using declarations into the same
911 // context, even if they have identical signatures.
912 if (NewIsUsingDecl) continue;
913
914 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
915 }
916
917 // If either declaration was introduced by a using declaration,
918 // we'll need to use slightly different rules for matching.
919 // Essentially, these rules are the normal rules, except that
920 // function templates hide function templates with different
921 // return types or template parameter lists.
922 bool UseMemberUsingDeclRules =
923 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
924
John McCall51fa86f2009-12-02 08:47:38 +0000925 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000926 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
927 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
928 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
929 continue;
930 }
931
John McCall871b2e72009-12-09 03:35:25 +0000932 Match = *I;
933 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000934 }
John McCall51fa86f2009-12-02 08:47:38 +0000935 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
John McCall871b2e72009-12-09 03:35:25 +0000942 Match = *I;
943 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000944 }
John McCalld7945c62010-11-10 03:01:53 +0000945 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000946 // We can overload with these, which can show up when doing
947 // redeclaration checks for UsingDecls.
948 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000949 } else if (isa<TagDecl>(OldD)) {
950 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000951 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
952 // Optimistically assume that an unresolved using decl will
953 // overload; if it doesn't, we'll have to diagnose during
954 // template instantiation.
955 } else {
John McCall68263142009-11-18 22:49:29 +0000956 // (C++ 13p1):
957 // Only function declarations can be overloaded; object and type
958 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000959 Match = *I;
960 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000961 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000962 }
John McCall68263142009-11-18 22:49:29 +0000963
John McCall871b2e72009-12-09 03:35:25 +0000964 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000965}
966
Rafael Espindola78eeba82012-12-28 14:21:58 +0000967static bool canBeOverloaded(const FunctionDecl &D) {
968 if (D.getAttr<OverloadableAttr>())
969 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000970 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000971 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000972
973 // Main cannot be overloaded (basic.start.main).
974 if (D.isMain())
975 return false;
976
Rafael Espindola78eeba82012-12-28 14:21:58 +0000977 return true;
978}
979
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000980static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
981 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000982 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
983 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
984
985 // C++ [temp.fct]p2:
986 // A function template can be overloaded with other function templates
987 // and with normal (non-template) functions.
988 if ((OldTemplate == 0) != (NewTemplate == 0))
989 return true;
990
991 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000992 QualType OldQType = S.Context.getCanonicalType(Old->getType());
993 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000994
995 // Compare the signatures (C++ 1.3.10) of the two functions to
996 // determine whether they are overloads. If we find any mismatch
997 // in the signature, they are overloads.
998
999 // If either of these functions is a K&R-style function (no
1000 // prototype), then we consider them to have matching signatures.
1001 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1002 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1003 return false;
1004
John McCallf4c73712011-01-19 06:33:43 +00001005 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1006 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001007
1008 // The signature of a function includes the types of its
1009 // parameters (C++ 1.3.10), which includes the presence or absence
1010 // of the ellipsis; see C++ DR 357).
1011 if (OldQType != NewQType &&
1012 (OldType->getNumArgs() != NewType->getNumArgs() ||
1013 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001014 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001015 return true;
1016
1017 // C++ [temp.over.link]p4:
1018 // The signature of a function template consists of its function
1019 // signature, its return type and its template parameter list. The names
1020 // of the template parameters are significant only for establishing the
1021 // relationship between the template parameters and the rest of the
1022 // signature.
1023 //
1024 // We check the return type and template parameter lists for function
1025 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001026 //
1027 // However, we don't consider either of these when deciding whether
1028 // a member introduced by a shadow declaration is hidden.
1029 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001030 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1031 OldTemplate->getTemplateParameters(),
1032 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001033 OldType->getResultType() != NewType->getResultType()))
1034 return true;
1035
1036 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001037 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001038 //
1039 // As part of this, also check whether one of the member functions
1040 // is static, in which case they are not overloads (C++
1041 // 13.1p2). While not part of the definition of the signature,
1042 // this check is important to determine whether these functions
1043 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001044 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1045 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001046 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001047 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1048 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1049 if (!UseUsingDeclRules &&
1050 (OldMethod->getRefQualifier() == RQ_None ||
1051 NewMethod->getRefQualifier() == RQ_None)) {
1052 // C++0x [over.load]p2:
1053 // - Member function declarations with the same name and the same
1054 // parameter-type-list as well as member function template
1055 // declarations with the same name, the same parameter-type-list, and
1056 // the same template parameter lists cannot be overloaded if any of
1057 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001058 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001059 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001060 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001061 }
1062 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001063 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001064
Richard Smith21c8fa82013-01-14 05:37:29 +00001065 // We may not have applied the implicit const for a constexpr member
1066 // function yet (because we haven't yet resolved whether this is a static
1067 // or non-static member function). Add it now, on the assumption that this
1068 // is a redeclaration of OldMethod.
1069 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001070 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001071 NewQuals |= Qualifiers::Const;
1072 if (OldMethod->getTypeQualifiers() != NewQuals)
1073 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001074 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001075
John McCall68263142009-11-18 22:49:29 +00001076 // The signatures match; this is not an overload.
1077 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001078}
1079
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001080bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1081 bool UseUsingDeclRules) {
1082 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1083 return false;
1084
1085 // If both of the functions are extern "C", then they are not
1086 // overloads.
1087 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1088 return false;
1089
1090 return true;
1091}
1092
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001093/// \brief Checks availability of the function depending on the current
1094/// function context. Inside an unavailable function, unavailability is ignored.
1095///
1096/// \returns true if \arg FD is unavailable and current context is inside
1097/// an available function, false otherwise.
1098bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1099 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1100}
1101
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001102/// \brief Tries a user-defined conversion from From to ToType.
1103///
1104/// Produces an implicit conversion sequence for when a standard conversion
1105/// is not an option. See TryImplicitConversion for more information.
1106static ImplicitConversionSequence
1107TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1108 bool SuppressUserConversions,
1109 bool AllowExplicit,
1110 bool InOverloadResolution,
1111 bool CStyle,
1112 bool AllowObjCWritebackConversion) {
1113 ImplicitConversionSequence ICS;
1114
1115 if (SuppressUserConversions) {
1116 // We're not in the case above, so there is no conversion that
1117 // we can perform.
1118 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1119 return ICS;
1120 }
1121
1122 // Attempt user-defined conversion.
1123 OverloadCandidateSet Conversions(From->getExprLoc());
1124 OverloadingResult UserDefResult
1125 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1126 AllowExplicit);
1127
1128 if (UserDefResult == OR_Success) {
1129 ICS.setUserDefined();
1130 // C++ [over.ics.user]p4:
1131 // A conversion of an expression of class type to the same class
1132 // type is given Exact Match rank, and a conversion of an
1133 // expression of class type to a base class of that type is
1134 // given Conversion rank, in spite of the fact that a copy
1135 // constructor (i.e., a user-defined conversion function) is
1136 // called for those cases.
1137 if (CXXConstructorDecl *Constructor
1138 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1139 QualType FromCanon
1140 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1141 QualType ToCanon
1142 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1143 if (Constructor->isCopyConstructor() &&
1144 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1145 // Turn this into a "standard" conversion sequence, so that it
1146 // gets ranked with standard conversion sequences.
1147 ICS.setStandard();
1148 ICS.Standard.setAsIdentityConversion();
1149 ICS.Standard.setFromType(From->getType());
1150 ICS.Standard.setAllToTypes(ToType);
1151 ICS.Standard.CopyConstructor = Constructor;
1152 if (ToCanon != FromCanon)
1153 ICS.Standard.Second = ICK_Derived_To_Base;
1154 }
1155 }
1156
1157 // C++ [over.best.ics]p4:
1158 // However, when considering the argument of a user-defined
1159 // conversion function that is a candidate by 13.3.1.3 when
1160 // invoked for the copying of the temporary in the second step
1161 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1162 // 13.3.1.6 in all cases, only standard conversion sequences and
1163 // ellipsis conversion sequences are allowed.
1164 if (SuppressUserConversions && ICS.isUserDefined()) {
1165 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1166 }
1167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168 ICS.setAmbiguous();
1169 ICS.Ambiguous.setFromType(From->getType());
1170 ICS.Ambiguous.setToType(ToType);
1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172 Cand != Conversions.end(); ++Cand)
1173 if (Cand->Viable)
1174 ICS.Ambiguous.addConversion(Cand->Function);
1175 } else {
1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177 }
1178
1179 return ICS;
1180}
1181
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001182/// TryImplicitConversion - Attempt to perform an implicit conversion
1183/// from the given expression (Expr) to the given type (ToType). This
1184/// function returns an implicit conversion sequence that can be used
1185/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001186///
1187/// void f(float f);
1188/// void g(int i) { f(i); }
1189///
1190/// this routine would produce an implicit conversion sequence to
1191/// describe the initialization of f from i, which will be a standard
1192/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1194//
1195/// Note that this routine only determines how the conversion can be
1196/// performed; it does not actually perform the conversion. As such,
1197/// it will not produce any diagnostics if no conversion is available,
1198/// but will instead return an implicit conversion sequence of kind
1199/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001200///
1201/// If @p SuppressUserConversions, then user-defined conversions are
1202/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001203/// If @p AllowExplicit, then explicit user-defined conversions are
1204/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001205///
1206/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207/// writeback conversion, which allows __autoreleasing id* parameters to
1208/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001209static ImplicitConversionSequence
1210TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001212 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001213 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001214 bool CStyle,
1215 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001216 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001217 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001218 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001219 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001220 return ICS;
1221 }
1222
David Blaikie4e4d0842012-03-11 07:00:24 +00001223 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001224 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001225 return ICS;
1226 }
1227
Douglas Gregor604eb652010-08-11 02:15:33 +00001228 // C++ [over.ics.user]p4:
1229 // A conversion of an expression of class type to the same class
1230 // type is given Exact Match rank, and a conversion of an
1231 // expression of class type to a base class of that type is
1232 // given Conversion rank, in spite of the fact that a copy/move
1233 // constructor (i.e., a user-defined conversion function) is
1234 // called for those cases.
1235 QualType FromType = From->getType();
1236 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001237 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1238 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001239 ICS.setStandard();
1240 ICS.Standard.setAsIdentityConversion();
1241 ICS.Standard.setFromType(FromType);
1242 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001244 // We don't actually check at this point whether there is a valid
1245 // copy/move constructor, since overloading just assumes that it
1246 // exists. When we actually perform initialization, we'll find the
1247 // appropriate constructor to copy the returned object, if needed.
1248 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001249
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001250 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001251 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001252 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253
Douglas Gregor604eb652010-08-11 02:15:33 +00001254 return ICS;
1255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001256
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001257 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1258 AllowExplicit, InOverloadResolution, CStyle,
1259 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001260}
1261
John McCallf85e1932011-06-15 23:02:42 +00001262ImplicitConversionSequence
1263Sema::TryImplicitConversion(Expr *From, QualType ToType,
1264 bool SuppressUserConversions,
1265 bool AllowExplicit,
1266 bool InOverloadResolution,
1267 bool CStyle,
1268 bool AllowObjCWritebackConversion) {
1269 return clang::TryImplicitConversion(*this, From, ToType,
1270 SuppressUserConversions, AllowExplicit,
1271 InOverloadResolution, CStyle,
1272 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001273}
1274
Douglas Gregor575c63a2010-04-16 22:27:05 +00001275/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001276/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001277/// converted expression. Flavor is the kind of conversion we're
1278/// performing, used in the error message. If @p AllowExplicit,
1279/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001280ExprResult
1281Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001282 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001283 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001284 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001285}
1286
John Wiegley429bb272011-04-08 18:41:53 +00001287ExprResult
1288Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001289 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001290 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001291 if (checkPlaceholderForOverload(*this, From))
1292 return ExprError();
1293
John McCallf85e1932011-06-15 23:02:42 +00001294 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1295 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001296 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001297 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001298
John McCall120d63c2010-08-24 20:38:10 +00001299 ICS = clang::TryImplicitConversion(*this, From, ToType,
1300 /*SuppressUserConversions=*/false,
1301 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001302 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001303 /*CStyle=*/false,
1304 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001305 return PerformImplicitConversion(From, ToType, ICS, Action);
1306}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001307
1308/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001309/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001310bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1311 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001312 if (Context.hasSameUnqualifiedType(FromType, ToType))
1313 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001314
John McCall00ccbef2010-12-21 00:44:39 +00001315 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1316 // where F adds one of the following at most once:
1317 // - a pointer
1318 // - a member pointer
1319 // - a block pointer
1320 CanQualType CanTo = Context.getCanonicalType(ToType);
1321 CanQualType CanFrom = Context.getCanonicalType(FromType);
1322 Type::TypeClass TyClass = CanTo->getTypeClass();
1323 if (TyClass != CanFrom->getTypeClass()) return false;
1324 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1325 if (TyClass == Type::Pointer) {
1326 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1327 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1328 } else if (TyClass == Type::BlockPointer) {
1329 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1330 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1331 } else if (TyClass == Type::MemberPointer) {
1332 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1333 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1334 } else {
1335 return false;
1336 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001337
John McCall00ccbef2010-12-21 00:44:39 +00001338 TyClass = CanTo->getTypeClass();
1339 if (TyClass != CanFrom->getTypeClass()) return false;
1340 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1341 return false;
1342 }
1343
1344 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1345 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1346 if (!EInfo.getNoReturn()) return false;
1347
1348 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1349 assert(QualType(FromFn, 0).isCanonical());
1350 if (QualType(FromFn, 0) != CanTo) return false;
1351
1352 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001353 return true;
1354}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001355
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001356/// \brief Determine whether the conversion from FromType to ToType is a valid
1357/// vector conversion.
1358///
1359/// \param ICK Will be set to the vector conversion kind, if this is a vector
1360/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001361static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1362 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001363 // We need at least one of these types to be a vector type to have a vector
1364 // conversion.
1365 if (!ToType->isVectorType() && !FromType->isVectorType())
1366 return false;
1367
1368 // Identical types require no conversions.
1369 if (Context.hasSameUnqualifiedType(FromType, ToType))
1370 return false;
1371
1372 // There are no conversions between extended vector types, only identity.
1373 if (ToType->isExtVectorType()) {
1374 // There are no conversions between extended vector types other than the
1375 // identity conversion.
1376 if (FromType->isExtVectorType())
1377 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001378
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001379 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001380 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001381 ICK = ICK_Vector_Splat;
1382 return true;
1383 }
1384 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001385
1386 // We can perform the conversion between vector types in the following cases:
1387 // 1)vector types are equivalent AltiVec and GCC vector types
1388 // 2)lax vector conversions are permitted and the vector types are of the
1389 // same size
1390 if (ToType->isVectorType() && FromType->isVectorType()) {
1391 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001392 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001393 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001394 ICK = ICK_Vector_Conversion;
1395 return true;
1396 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001397 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001398
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001399 return false;
1400}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401
Douglas Gregor7d000652012-04-12 20:48:09 +00001402static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1403 bool InOverloadResolution,
1404 StandardConversionSequence &SCS,
1405 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001406
Douglas Gregor60d62c22008-10-31 16:23:19 +00001407/// IsStandardConversion - Determines whether there is a standard
1408/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1409/// expression From to the type ToType. Standard conversion sequences
1410/// only consider non-class types; for conversions that involve class
1411/// types, use TryImplicitConversion. If a conversion exists, SCS will
1412/// contain the standard conversion sequence required to perform this
1413/// conversion and this routine will return true. Otherwise, this
1414/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001415static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1416 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001417 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001418 bool CStyle,
1419 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001421
Douglas Gregor60d62c22008-10-31 16:23:19 +00001422 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001423 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001424 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001425 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001426 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001427 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001428
Douglas Gregorf9201e02009-02-11 23:02:49 +00001429 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001430 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001431 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001432 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001433 return false;
1434
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001436 }
1437
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001438 // The first conversion can be an lvalue-to-rvalue conversion,
1439 // array-to-pointer conversion, or function-to-pointer conversion
1440 // (C++ 4p1).
1441
John McCall120d63c2010-08-24 20:38:10 +00001442 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001443 DeclAccessPair AccessPair;
1444 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001445 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001446 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001447 // We were able to resolve the address of the overloaded function,
1448 // so we can convert to the type of that function.
1449 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001450
1451 // we can sometimes resolve &foo<int> regardless of ToType, so check
1452 // if the type matches (identity) or we are converting to bool
1453 if (!S.Context.hasSameUnqualifiedType(
1454 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1455 QualType resultTy;
1456 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001457 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001458 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1459 // otherwise, only a boolean conversion is standard
1460 if (!ToType->isBooleanType())
1461 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001462 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463
Chandler Carruth90434232011-03-29 08:08:18 +00001464 // Check if the "from" expression is taking the address of an overloaded
1465 // function and recompute the FromType accordingly. Take advantage of the
1466 // fact that non-static member functions *must* have such an address-of
1467 // expression.
1468 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1469 if (Method && !Method->isStatic()) {
1470 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1471 "Non-unary operator on non-static member address");
1472 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1473 == UO_AddrOf &&
1474 "Non-address-of operator on non-static member address");
1475 const Type *ClassType
1476 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1477 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001478 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1479 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1480 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001481 "Non-address-of operator for overloaded function expression");
1482 FromType = S.Context.getPointerType(FromType);
1483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001484
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001485 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001486 assert(S.Context.hasSameType(
1487 FromType,
1488 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001489 } else {
1490 return false;
1491 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001492 }
John McCall21480112011-08-30 00:57:29 +00001493 // Lvalue-to-rvalue conversion (C++11 4.1):
1494 // A glvalue (3.10) of a non-function, non-array type T can
1495 // be converted to a prvalue.
1496 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001497 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001498 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001499 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001502 // C11 6.3.2.1p2:
1503 // ... if the lvalue has atomic type, the value has the non-atomic version
1504 // of the type of the lvalue ...
1505 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1506 FromType = Atomic->getValueType();
1507
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001508 // If T is a non-class type, the type of the rvalue is the
1509 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001510 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1511 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001512 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001513 } else if (FromType->isArrayType()) {
1514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001516
1517 // An lvalue or rvalue of type "array of N T" or "array of unknown
1518 // bound of T" can be converted to an rvalue of type "pointer to
1519 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001520 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001521
John McCall120d63c2010-08-24 20:38:10 +00001522 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001524 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001525
1526 // For the purpose of ranking in overload resolution
1527 // (13.3.3.1.1), this conversion is considered an
1528 // array-to-pointer conversion followed by a qualification
1529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001530 SCS.Second = ICK_Identity;
1531 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001532 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001533 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001536 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001537 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001538 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539
1540 // An lvalue of function type T can be converted to an rvalue of
1541 // type "pointer to T." The result is a pointer to the
1542 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001543 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001544 } else {
1545 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001546 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001547 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001548 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001549
1550 // The second conversion can be an integral promotion, floating
1551 // point promotion, integral conversion, floating point conversion,
1552 // floating-integral conversion, pointer conversion,
1553 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001554 // For overloading in C, this can also be a "compatible-type"
1555 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001556 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001557 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001558 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001559 // The unqualified versions of the types are the same: there's no
1560 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001561 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001562 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001563 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001564 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001565 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001566 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001567 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001568 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001569 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001570 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001571 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001572 SCS.Second = ICK_Complex_Promotion;
1573 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001574 } else if (ToType->isBooleanType() &&
1575 (FromType->isArithmeticType() ||
1576 FromType->isAnyPointerType() ||
1577 FromType->isBlockPointerType() ||
1578 FromType->isMemberPointerType() ||
1579 FromType->isNullPtrType())) {
1580 // Boolean conversions (C++ 4.12).
1581 SCS.Second = ICK_Boolean_Conversion;
1582 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001583 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001584 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001585 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001586 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001587 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001588 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001589 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001590 SCS.Second = ICK_Complex_Conversion;
1591 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001592 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1593 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001594 // Complex-real conversions (C99 6.3.1.7)
1595 SCS.Second = ICK_Complex_Real;
1596 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001597 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001598 // Floating point conversions (C++ 4.8).
1599 SCS.Second = ICK_Floating_Conversion;
1600 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001601 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001602 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001603 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001604 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001605 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001606 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001607 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001608 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001609 SCS.Second = ICK_Block_Pointer_Conversion;
1610 } else if (AllowObjCWritebackConversion &&
1611 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1612 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001613 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1614 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001615 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001616 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001617 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001618 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001619 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001620 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001621 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001622 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001623 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001624 SCS.Second = SecondICK;
1625 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001626 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001627 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001628 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001629 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001630 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001631 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001632 // Treat a conversion that strips "noreturn" as an identity conversion.
1633 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001634 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1635 InOverloadResolution,
1636 SCS, CStyle)) {
1637 SCS.Second = ICK_TransparentUnionConversion;
1638 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001639 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1640 CStyle)) {
1641 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001642 // appropriately.
1643 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001644 } else if (ToType->isEventT() &&
1645 From->isIntegerConstantExpr(S.getASTContext()) &&
1646 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1647 SCS.Second = ICK_Zero_Event_Conversion;
1648 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001649 } else {
1650 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001652 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001653 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001654
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001655 QualType CanonFrom;
1656 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001658 bool ObjCLifetimeConversion;
1659 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1660 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001661 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001662 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001663 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001664 CanonFrom = S.Context.getCanonicalType(FromType);
1665 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001666 } else {
1667 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001668 SCS.Third = ICK_Identity;
1669
Mike Stump1eb44332009-09-09 15:08:12 +00001670 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001671 // [...] Any difference in top-level cv-qualification is
1672 // subsumed by the initialization itself and does not constitute
1673 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001674 CanonFrom = S.Context.getCanonicalType(FromType);
1675 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001677 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001678 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001679 FromType = ToType;
1680 CanonFrom = CanonTo;
1681 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001682 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001683 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001684
1685 // If we have not converted the argument type to the parameter type,
1686 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001687 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001688 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001689
Douglas Gregor60d62c22008-10-31 16:23:19 +00001690 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001691}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001692
1693static bool
1694IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1695 QualType &ToType,
1696 bool InOverloadResolution,
1697 StandardConversionSequence &SCS,
1698 bool CStyle) {
1699
1700 const RecordType *UT = ToType->getAsUnionType();
1701 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1702 return false;
1703 // The field to initialize within the transparent union.
1704 RecordDecl *UD = UT->getDecl();
1705 // It's compatible if the expression matches any of the fields.
1706 for (RecordDecl::field_iterator it = UD->field_begin(),
1707 itend = UD->field_end();
1708 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001709 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1710 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001711 ToType = it->getType();
1712 return true;
1713 }
1714 }
1715 return false;
1716}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001717
1718/// IsIntegralPromotion - Determines whether the conversion from the
1719/// expression From (whose potentially-adjusted type is FromType) to
1720/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1721/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001722bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001723 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001724 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001725 if (!To) {
1726 return false;
1727 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728
1729 // An rvalue of type char, signed char, unsigned char, short int, or
1730 // unsigned short int can be converted to an rvalue of type int if
1731 // int can represent all the values of the source type; otherwise,
1732 // the source rvalue can be converted to an rvalue of type unsigned
1733 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001734 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1735 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001736 if (// We can promote any signed, promotable integer type to an int
1737 (FromType->isSignedIntegerType() ||
1738 // We can promote any unsigned integer type whose size is
1739 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001740 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001741 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001743 }
1744
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001745 return To->getKind() == BuiltinType::UInt;
1746 }
1747
Richard Smithe7ff9192012-09-13 21:18:54 +00001748 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749 // A prvalue of an unscoped enumeration type whose underlying type is not
1750 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1751 // following types that can represent all the values of the enumeration
1752 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1753 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001754 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001755 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001756 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001757 // with lowest integer conversion rank (4.13) greater than the rank of long
1758 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001759 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001760 // C++11 [conv.prom]p4:
1761 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1762 // can be converted to a prvalue of its underlying type. Moreover, if
1763 // integral promotion can be applied to its underlying type, a prvalue of an
1764 // unscoped enumeration type whose underlying type is fixed can also be
1765 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001766 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1767 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1768 // provided for a scoped enumeration.
1769 if (FromEnumType->getDecl()->isScoped())
1770 return false;
1771
Richard Smithe7ff9192012-09-13 21:18:54 +00001772 // We can perform an integral promotion to the underlying type of the enum,
1773 // even if that's not the promoted type.
1774 if (FromEnumType->getDecl()->isFixed()) {
1775 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1776 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1777 IsIntegralPromotion(From, Underlying, ToType);
1778 }
1779
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001780 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001782 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001783 return Context.hasSameUnqualifiedType(ToType,
1784 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001785 }
John McCall842aef82009-12-09 09:09:27 +00001786
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001787 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1789 // to an rvalue a prvalue of the first of the following types that can
1790 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001791 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001793 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001795 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001797 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001798 // Determine whether the type we're converting from is signed or
1799 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001800 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001801 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001803 // The types we'll try to promote to, in the appropriate
1804 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001805 QualType PromoteTypes[6] = {
1806 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001807 Context.LongTy, Context.UnsignedLongTy ,
1808 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001809 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001810 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001811 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1812 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001813 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001814 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1815 // We found the type that we can promote to. If this is the
1816 // type we wanted, we have a promotion. Otherwise, no
1817 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001818 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001819 }
1820 }
1821 }
1822
1823 // An rvalue for an integral bit-field (9.6) can be converted to an
1824 // rvalue of type int if int can represent all the values of the
1825 // bit-field; otherwise, it can be converted to unsigned int if
1826 // unsigned int can represent all the values of the bit-field. If
1827 // the bit-field is larger yet, no integral promotion applies to
1828 // it. If the bit-field has an enumerated type, it is treated as any
1829 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001830 // FIXME: We should delay checking of bit-fields until we actually perform the
1831 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001832 using llvm::APSInt;
1833 if (From)
1834 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001835 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001836 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001837 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1838 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1839 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Douglas Gregor86f19402008-12-20 23:49:58 +00001841 // Are we promoting to an int from a bitfield that fits in an int?
1842 if (BitWidth < ToSize ||
1843 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1844 return To->getKind() == BuiltinType::Int;
1845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregor86f19402008-12-20 23:49:58 +00001847 // Are we promoting to an unsigned int from an unsigned bitfield
1848 // that fits into an unsigned int?
1849 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1850 return To->getKind() == BuiltinType::UInt;
1851 }
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Douglas Gregor86f19402008-12-20 23:49:58 +00001853 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001854 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001857 // An rvalue of type bool can be converted to an rvalue of type int,
1858 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001859 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001860 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001861 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001862
1863 return false;
1864}
1865
1866/// IsFloatingPointPromotion - Determines whether the conversion from
1867/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1868/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001869bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001870 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1871 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001872 /// An rvalue of type float can be converted to an rvalue of type
1873 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001874 if (FromBuiltin->getKind() == BuiltinType::Float &&
1875 ToBuiltin->getKind() == BuiltinType::Double)
1876 return true;
1877
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001878 // C99 6.3.1.5p1:
1879 // When a float is promoted to double or long double, or a
1880 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001881 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001882 (FromBuiltin->getKind() == BuiltinType::Float ||
1883 FromBuiltin->getKind() == BuiltinType::Double) &&
1884 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1885 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001886
1887 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001888 if (!getLangOpts().NativeHalfType &&
1889 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001890 ToBuiltin->getKind() == BuiltinType::Float)
1891 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001892 }
1893
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001894 return false;
1895}
1896
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001897/// \brief Determine if a conversion is a complex promotion.
1898///
1899/// A complex promotion is defined as a complex -> complex conversion
1900/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001901/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001902bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001903 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001904 if (!FromComplex)
1905 return false;
1906
John McCall183700f2009-09-21 23:43:11 +00001907 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001908 if (!ToComplex)
1909 return false;
1910
1911 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001912 ToComplex->getElementType()) ||
1913 IsIntegralPromotion(0, FromComplex->getElementType(),
1914 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001915}
1916
Douglas Gregorcb7de522008-11-26 23:31:11 +00001917/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1918/// the pointer type FromPtr to a pointer to type ToPointee, with the
1919/// same type qualifiers as FromPtr has on its pointee type. ToType,
1920/// if non-empty, will be a pointer to ToType that may or may not have
1921/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001922///
Mike Stump1eb44332009-09-09 15:08:12 +00001923static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001924BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001925 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001926 ASTContext &Context,
1927 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001928 assert((FromPtr->getTypeClass() == Type::Pointer ||
1929 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1930 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001931
John McCallf85e1932011-06-15 23:02:42 +00001932 /// Conversions to 'id' subsume cv-qualifier conversions.
1933 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001934 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001935
1936 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001937 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001938 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001939 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001940
John McCallf85e1932011-06-15 23:02:42 +00001941 if (StripObjCLifetime)
1942 Quals.removeObjCLifetime();
1943
Mike Stump1eb44332009-09-09 15:08:12 +00001944 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001945 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001946 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001947 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001948 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001949
1950 // Build a pointer to ToPointee. It has the right qualifiers
1951 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001952 if (isa<ObjCObjectPointerType>(ToType))
1953 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001954 return Context.getPointerType(ToPointee);
1955 }
1956
1957 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001958 QualType QualifiedCanonToPointee
1959 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001960
Douglas Gregorda80f742010-12-01 21:43:58 +00001961 if (isa<ObjCObjectPointerType>(ToType))
1962 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1963 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001964}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001965
Mike Stump1eb44332009-09-09 15:08:12 +00001966static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001967 bool InOverloadResolution,
1968 ASTContext &Context) {
1969 // Handle value-dependent integral null pointer constants correctly.
1970 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1971 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001972 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001973 return !InOverloadResolution;
1974
Douglas Gregorce940492009-09-25 04:25:58 +00001975 return Expr->isNullPointerConstant(Context,
1976 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1977 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001978}
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001980/// IsPointerConversion - Determines whether the conversion of the
1981/// expression From, which has the (possibly adjusted) type FromType,
1982/// can be converted to the type ToType via a pointer conversion (C++
1983/// 4.10). If so, returns true and places the converted type (that
1984/// might differ from ToType in its cv-qualifiers at some level) into
1985/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001986///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001987/// This routine also supports conversions to and from block pointers
1988/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1989/// pointers to interfaces. FIXME: Once we've determined the
1990/// appropriate overloading rules for Objective-C, we may want to
1991/// split the Objective-C checks into a different routine; however,
1992/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001993/// conversions, so for now they live here. IncompatibleObjC will be
1994/// set if the conversion is an allowed Objective-C conversion that
1995/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001996bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001997 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001998 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001999 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002000 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002001 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2002 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002003 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002004
Mike Stump1eb44332009-09-09 15:08:12 +00002005 // Conversion from a null pointer constant to any Objective-C pointer type.
2006 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002008 ConvertedType = ToType;
2009 return true;
2010 }
2011
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002012 // Blocks: Block pointers can be converted to void*.
2013 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002014 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002015 ConvertedType = ToType;
2016 return true;
2017 }
2018 // Blocks: A null pointer constant can be converted to a block
2019 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002020 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002022 ConvertedType = ToType;
2023 return true;
2024 }
2025
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002026 // If the left-hand-side is nullptr_t, the right side can be a null
2027 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002028 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002030 ConvertedType = ToType;
2031 return true;
2032 }
2033
Ted Kremenek6217b802009-07-29 21:53:49 +00002034 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002035 if (!ToTypePtr)
2036 return false;
2037
2038 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002039 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002040 ConvertedType = ToType;
2041 return true;
2042 }
Sebastian Redl07779722008-10-31 14:43:28 +00002043
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002044 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002045 // , including objective-c pointers.
2046 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002047 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002048 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002049 ConvertedType = BuildSimilarlyQualifiedPointerType(
2050 FromType->getAs<ObjCObjectPointerType>(),
2051 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002052 ToType, Context);
2053 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002054 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002055 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002056 if (!FromTypePtr)
2057 return false;
2058
2059 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002060
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002061 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002062 // pointer conversion, so don't do all of the work below.
2063 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2064 return false;
2065
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002066 // An rvalue of type "pointer to cv T," where T is an object type,
2067 // can be converted to an rvalue of type "pointer to cv void" (C++
2068 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002069 if (FromPointeeType->isIncompleteOrObjectType() &&
2070 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002071 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002072 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002073 ToType, Context,
2074 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002075 return true;
2076 }
2077
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002078 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002079 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002080 ToPointeeType->isVoidType()) {
2081 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2082 ToPointeeType,
2083 ToType, Context);
2084 return true;
2085 }
2086
Douglas Gregorf9201e02009-02-11 23:02:49 +00002087 // When we're overloading in C, we allow a special kind of pointer
2088 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002089 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002090 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002092 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002093 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002094 return true;
2095 }
2096
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002097 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002098 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002099 // An rvalue of type "pointer to cv D," where D is a class type,
2100 // can be converted to an rvalue of type "pointer to cv B," where
2101 // B is a base class (clause 10) of D. If B is an inaccessible
2102 // (clause 11) or ambiguous (10.2) base class of D, a program that
2103 // necessitates this conversion is ill-formed. The result of the
2104 // conversion is a pointer to the base class sub-object of the
2105 // derived class object. The null pointer value is converted to
2106 // the null pointer value of the destination type.
2107 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002108 // Note that we do not check for ambiguity or inaccessibility
2109 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002110 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002111 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002112 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002113 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002114 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002116 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002117 ToType, Context);
2118 return true;
2119 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002120
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002121 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2122 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2124 ToPointeeType,
2125 ToType, Context);
2126 return true;
2127 }
2128
Douglas Gregorc7887512008-12-19 19:13:09 +00002129 return false;
2130}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002131
2132/// \brief Adopt the given qualifiers for the given type.
2133static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2134 Qualifiers TQs = T.getQualifiers();
2135
2136 // Check whether qualifiers already match.
2137 if (TQs == Qs)
2138 return T;
2139
2140 if (Qs.compatiblyIncludes(TQs))
2141 return Context.getQualifiedType(T, Qs);
2142
2143 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2144}
Douglas Gregorc7887512008-12-19 19:13:09 +00002145
2146/// isObjCPointerConversion - Determines whether this is an
2147/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2148/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002149bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002150 QualType& ConvertedType,
2151 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002152 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002153 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002154
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002155 // The set of qualifiers on the type we're converting from.
2156 Qualifiers FromQualifiers = FromType.getQualifiers();
2157
Steve Naroff14108da2009-07-10 23:34:53 +00002158 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002159 const ObjCObjectPointerType* ToObjCPtr =
2160 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002161 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002162 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002163
Steve Naroff14108da2009-07-10 23:34:53 +00002164 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002165 // If the pointee types are the same (ignoring qualifications),
2166 // then this is not a pointer conversion.
2167 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2168 FromObjCPtr->getPointeeType()))
2169 return false;
2170
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002171 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002172 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002173 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002174 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002175 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002176 return true;
2177 }
2178 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002179 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002180 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002181 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002182 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002183 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002184 return true;
2185 }
2186 // Objective C++: We're able to convert from a pointer to an
2187 // interface to a pointer to a different interface.
2188 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002189 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2190 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002191 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002192 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2193 FromObjCPtr->getPointeeType()))
2194 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002196 ToObjCPtr->getPointeeType(),
2197 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002199 return true;
2200 }
2201
2202 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2203 // Okay: this is some kind of implicit downcast of Objective-C
2204 // interfaces, which is permitted. However, we're going to
2205 // complain about it.
2206 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002208 ToObjCPtr->getPointeeType(),
2209 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002211 return true;
2212 }
Mike Stump1eb44332009-09-09 15:08:12 +00002213 }
Steve Naroff14108da2009-07-10 23:34:53 +00002214 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002215 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002216 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002217 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002219 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002220 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002221 // to a block pointer type.
2222 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002224 return true;
2225 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002226 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002227 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002228 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002229 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002230 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002231 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002232 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002233 return true;
2234 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002235 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002236 return false;
2237
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002238 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002239 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002240 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002241 else if (const BlockPointerType *FromBlockPtr =
2242 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002243 FromPointeeType = FromBlockPtr->getPointeeType();
2244 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002245 return false;
2246
Douglas Gregorc7887512008-12-19 19:13:09 +00002247 // If we have pointers to pointers, recursively check whether this
2248 // is an Objective-C conversion.
2249 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2250 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2251 IncompatibleObjC)) {
2252 // We always complain about this conversion.
2253 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002254 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002256 return true;
2257 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002258 // Allow conversion of pointee being objective-c pointer to another one;
2259 // as in I* to id.
2260 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2261 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2263 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002264
Douglas Gregorda80f742010-12-01 21:43:58 +00002265 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002267 return true;
2268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002269
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002270 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002271 // differences in the argument and result types are in Objective-C
2272 // pointer conversions. If so, we permit the conversion (but
2273 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002274 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002275 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002276 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002277 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002278 if (FromFunctionType && ToFunctionType) {
2279 // If the function types are exactly the same, this isn't an
2280 // Objective-C pointer conversion.
2281 if (Context.getCanonicalType(FromPointeeType)
2282 == Context.getCanonicalType(ToPointeeType))
2283 return false;
2284
2285 // Perform the quick checks that will tell us whether these
2286 // function types are obviously different.
2287 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2288 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2289 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2290 return false;
2291
2292 bool HasObjCConversion = false;
2293 if (Context.getCanonicalType(FromFunctionType->getResultType())
2294 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2295 // Okay, the types match exactly. Nothing to do.
2296 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2297 ToFunctionType->getResultType(),
2298 ConvertedType, IncompatibleObjC)) {
2299 // Okay, we have an Objective-C pointer conversion.
2300 HasObjCConversion = true;
2301 } else {
2302 // Function types are too different. Abort.
2303 return false;
2304 }
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregorc7887512008-12-19 19:13:09 +00002306 // Check argument types.
2307 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2308 ArgIdx != NumArgs; ++ArgIdx) {
2309 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2310 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2311 if (Context.getCanonicalType(FromArgType)
2312 == Context.getCanonicalType(ToArgType)) {
2313 // Okay, the types match exactly. Nothing to do.
2314 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2315 ConvertedType, IncompatibleObjC)) {
2316 // Okay, we have an Objective-C pointer conversion.
2317 HasObjCConversion = true;
2318 } else {
2319 // Argument types are too different. Abort.
2320 return false;
2321 }
2322 }
2323
2324 if (HasObjCConversion) {
2325 // We had an Objective-C conversion. Allow this pointer
2326 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002327 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002328 IncompatibleObjC = true;
2329 return true;
2330 }
2331 }
2332
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002333 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002334}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335
John McCallf85e1932011-06-15 23:02:42 +00002336/// \brief Determine whether this is an Objective-C writeback conversion,
2337/// used for parameter passing when performing automatic reference counting.
2338///
2339/// \param FromType The type we're converting form.
2340///
2341/// \param ToType The type we're converting to.
2342///
2343/// \param ConvertedType The type that will be produced after applying
2344/// this conversion.
2345bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2346 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002347 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002348 Context.hasSameUnqualifiedType(FromType, ToType))
2349 return false;
2350
2351 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2352 QualType ToPointee;
2353 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2354 ToPointee = ToPointer->getPointeeType();
2355 else
2356 return false;
2357
2358 Qualifiers ToQuals = ToPointee.getQualifiers();
2359 if (!ToPointee->isObjCLifetimeType() ||
2360 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002361 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002362 return false;
2363
2364 // Argument must be a pointer to __strong to __weak.
2365 QualType FromPointee;
2366 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2367 FromPointee = FromPointer->getPointeeType();
2368 else
2369 return false;
2370
2371 Qualifiers FromQuals = FromPointee.getQualifiers();
2372 if (!FromPointee->isObjCLifetimeType() ||
2373 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2374 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2375 return false;
2376
2377 // Make sure that we have compatible qualifiers.
2378 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2379 if (!ToQuals.compatiblyIncludes(FromQuals))
2380 return false;
2381
2382 // Remove qualifiers from the pointee type we're converting from; they
2383 // aren't used in the compatibility check belong, and we'll be adding back
2384 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2385 FromPointee = FromPointee.getUnqualifiedType();
2386
2387 // The unqualified form of the pointee types must be compatible.
2388 ToPointee = ToPointee.getUnqualifiedType();
2389 bool IncompatibleObjC;
2390 if (Context.typesAreCompatible(FromPointee, ToPointee))
2391 FromPointee = ToPointee;
2392 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2393 IncompatibleObjC))
2394 return false;
2395
2396 /// \brief Construct the type we're converting to, which is a pointer to
2397 /// __autoreleasing pointee.
2398 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2399 ConvertedType = Context.getPointerType(FromPointee);
2400 return true;
2401}
2402
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002403bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2404 QualType& ConvertedType) {
2405 QualType ToPointeeType;
2406 if (const BlockPointerType *ToBlockPtr =
2407 ToType->getAs<BlockPointerType>())
2408 ToPointeeType = ToBlockPtr->getPointeeType();
2409 else
2410 return false;
2411
2412 QualType FromPointeeType;
2413 if (const BlockPointerType *FromBlockPtr =
2414 FromType->getAs<BlockPointerType>())
2415 FromPointeeType = FromBlockPtr->getPointeeType();
2416 else
2417 return false;
2418 // We have pointer to blocks, check whether the only
2419 // differences in the argument and result types are in Objective-C
2420 // pointer conversions. If so, we permit the conversion.
2421
2422 const FunctionProtoType *FromFunctionType
2423 = FromPointeeType->getAs<FunctionProtoType>();
2424 const FunctionProtoType *ToFunctionType
2425 = ToPointeeType->getAs<FunctionProtoType>();
2426
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002427 if (!FromFunctionType || !ToFunctionType)
2428 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002429
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002430 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002431 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002432
2433 // Perform the quick checks that will tell us whether these
2434 // function types are obviously different.
2435 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2436 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2437 return false;
2438
2439 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2440 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2441 if (FromEInfo != ToEInfo)
2442 return false;
2443
2444 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002445 if (Context.hasSameType(FromFunctionType->getResultType(),
2446 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002447 // Okay, the types match exactly. Nothing to do.
2448 } else {
2449 QualType RHS = FromFunctionType->getResultType();
2450 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002451 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002452 !RHS.hasQualifiers() && LHS.hasQualifiers())
2453 LHS = LHS.getUnqualifiedType();
2454
2455 if (Context.hasSameType(RHS,LHS)) {
2456 // OK exact match.
2457 } else if (isObjCPointerConversion(RHS, LHS,
2458 ConvertedType, IncompatibleObjC)) {
2459 if (IncompatibleObjC)
2460 return false;
2461 // Okay, we have an Objective-C pointer conversion.
2462 }
2463 else
2464 return false;
2465 }
2466
2467 // Check argument types.
2468 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2469 ArgIdx != NumArgs; ++ArgIdx) {
2470 IncompatibleObjC = false;
2471 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2472 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2473 if (Context.hasSameType(FromArgType, ToArgType)) {
2474 // Okay, the types match exactly. Nothing to do.
2475 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2476 ConvertedType, IncompatibleObjC)) {
2477 if (IncompatibleObjC)
2478 return false;
2479 // Okay, we have an Objective-C pointer conversion.
2480 } else
2481 // Argument types are too different. Abort.
2482 return false;
2483 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002484 if (LangOpts.ObjCAutoRefCount &&
2485 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2486 ToFunctionType))
2487 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002488
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002489 ConvertedType = ToType;
2490 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002491}
2492
Richard Trieu6efd4c52011-11-23 22:32:32 +00002493enum {
2494 ft_default,
2495 ft_different_class,
2496 ft_parameter_arity,
2497 ft_parameter_mismatch,
2498 ft_return_type,
2499 ft_qualifer_mismatch
2500};
2501
2502/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2503/// function types. Catches different number of parameter, mismatch in
2504/// parameter types, and different return types.
2505void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2506 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002507 // If either type is not valid, include no extra info.
2508 if (FromType.isNull() || ToType.isNull()) {
2509 PDiag << ft_default;
2510 return;
2511 }
2512
Richard Trieu6efd4c52011-11-23 22:32:32 +00002513 // Get the function type from the pointers.
2514 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2515 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2516 *ToMember = ToType->getAs<MemberPointerType>();
2517 if (FromMember->getClass() != ToMember->getClass()) {
2518 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2519 << QualType(FromMember->getClass(), 0);
2520 return;
2521 }
2522 FromType = FromMember->getPointeeType();
2523 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002524 }
2525
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002526 if (FromType->isPointerType())
2527 FromType = FromType->getPointeeType();
2528 if (ToType->isPointerType())
2529 ToType = ToType->getPointeeType();
2530
2531 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002532 FromType = FromType.getNonReferenceType();
2533 ToType = ToType.getNonReferenceType();
2534
Richard Trieu6efd4c52011-11-23 22:32:32 +00002535 // Don't print extra info for non-specialized template functions.
2536 if (FromType->isInstantiationDependentType() &&
2537 !FromType->getAs<TemplateSpecializationType>()) {
2538 PDiag << ft_default;
2539 return;
2540 }
2541
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002542 // No extra info for same types.
2543 if (Context.hasSameType(FromType, ToType)) {
2544 PDiag << ft_default;
2545 return;
2546 }
2547
Richard Trieu6efd4c52011-11-23 22:32:32 +00002548 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2549 *ToFunction = ToType->getAs<FunctionProtoType>();
2550
2551 // Both types need to be function types.
2552 if (!FromFunction || !ToFunction) {
2553 PDiag << ft_default;
2554 return;
2555 }
2556
2557 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2558 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2559 << FromFunction->getNumArgs();
2560 return;
2561 }
2562
2563 // Handle different parameter types.
2564 unsigned ArgPos;
2565 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2566 PDiag << ft_parameter_mismatch << ArgPos + 1
2567 << ToFunction->getArgType(ArgPos)
2568 << FromFunction->getArgType(ArgPos);
2569 return;
2570 }
2571
2572 // Handle different return type.
2573 if (!Context.hasSameType(FromFunction->getResultType(),
2574 ToFunction->getResultType())) {
2575 PDiag << ft_return_type << ToFunction->getResultType()
2576 << FromFunction->getResultType();
2577 return;
2578 }
2579
2580 unsigned FromQuals = FromFunction->getTypeQuals(),
2581 ToQuals = ToFunction->getTypeQuals();
2582 if (FromQuals != ToQuals) {
2583 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2584 return;
2585 }
2586
2587 // Unable to find a difference, so add no extra info.
2588 PDiag << ft_default;
2589}
2590
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002591/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002592/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002593/// they have same number of arguments. This routine assumes that Objective-C
2594/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002595/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002596/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002597bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002598 const FunctionProtoType *NewType,
2599 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002600 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002601 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2602 N = NewType->arg_type_begin(),
2603 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2604 if (!Context.hasSameType(*O, *N)) {
2605 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2606 return false;
2607 }
2608 }
2609 return true;
2610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002611
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002612 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2613 N = NewType->arg_type_begin(),
2614 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2615 QualType ToType = (*O);
2616 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002617 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002618 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2619 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002620 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2621 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2622 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2623 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002624 continue;
2625 }
John McCallc12c5bb2010-05-15 11:32:37 +00002626 else if (const ObjCObjectPointerType *PTTo =
2627 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002628 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002629 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002630 if (Context.hasSameUnqualifiedType(
2631 PTTo->getObjectType()->getBaseType(),
2632 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002633 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002634 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002635 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002636 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002637 }
2638 }
2639 return true;
2640}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002641
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002642/// CheckPointerConversion - Check the pointer conversion from the
2643/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002644/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002645/// conversions for which IsPointerConversion has already returned
2646/// true. It returns true and produces a diagnostic if there was an
2647/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002648bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002649 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002650 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002651 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002652 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002653 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002654
John McCalldaa8e4e2010-11-15 09:13:47 +00002655 Kind = CK_BitCast;
2656
David Blaikie50800fc2012-08-08 17:33:31 +00002657 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2658 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2659 Expr::NPCK_ZeroExpression) {
2660 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2661 DiagRuntimeBehavior(From->getExprLoc(), From,
2662 PDiag(diag::warn_impcast_bool_to_null_pointer)
2663 << ToType << From->getSourceRange());
2664 else if (!isUnevaluatedContext())
2665 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2666 << ToType << From->getSourceRange();
2667 }
John McCall1d9b3b22011-09-09 05:25:32 +00002668 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2669 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002670 QualType FromPointeeType = FromPtrType->getPointeeType(),
2671 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002672
Douglas Gregor5fccd362010-03-03 23:55:11 +00002673 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2674 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002675 // We must have a derived-to-base conversion. Check an
2676 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002677 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2678 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002679 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002680 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002681 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002682
Anders Carlsson61faec12009-09-12 04:46:44 +00002683 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002684 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002685 }
2686 }
John McCall1d9b3b22011-09-09 05:25:32 +00002687 } else if (const ObjCObjectPointerType *ToPtrType =
2688 ToType->getAs<ObjCObjectPointerType>()) {
2689 if (const ObjCObjectPointerType *FromPtrType =
2690 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002691 // Objective-C++ conversions are always okay.
2692 // FIXME: We should have a different class of conversions for the
2693 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002694 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002695 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002696 } else if (FromType->isBlockPointerType()) {
2697 Kind = CK_BlockPointerToObjCPointerCast;
2698 } else {
2699 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002700 }
John McCall1d9b3b22011-09-09 05:25:32 +00002701 } else if (ToType->isBlockPointerType()) {
2702 if (!FromType->isBlockPointerType())
2703 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002704 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002705
2706 // We shouldn't fall into this case unless it's valid for other
2707 // reasons.
2708 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2709 Kind = CK_NullToPointer;
2710
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002711 return false;
2712}
2713
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002714/// IsMemberPointerConversion - Determines whether the conversion of the
2715/// expression From, which has the (possibly adjusted) type FromType, can be
2716/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2717/// If so, returns true and places the converted type (that might differ from
2718/// ToType in its cv-qualifiers at some level) into ConvertedType.
2719bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002720 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002721 bool InOverloadResolution,
2722 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002723 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002724 if (!ToTypePtr)
2725 return false;
2726
2727 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002728 if (From->isNullPointerConstant(Context,
2729 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2730 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002731 ConvertedType = ToType;
2732 return true;
2733 }
2734
2735 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002736 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737 if (!FromTypePtr)
2738 return false;
2739
2740 // A pointer to member of B can be converted to a pointer to member of D,
2741 // where D is derived from B (C++ 4.11p2).
2742 QualType FromClass(FromTypePtr->getClass(), 0);
2743 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002744
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002745 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002746 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002747 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002748 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2749 ToClass.getTypePtr());
2750 return true;
2751 }
2752
2753 return false;
2754}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002755
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002756/// CheckMemberPointerConversion - Check the member pointer conversion from the
2757/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002758/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002759/// for which IsMemberPointerConversion has already returned true. It returns
2760/// true and produces a diagnostic if there was an error, or returns false
2761/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002762bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002763 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002764 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002765 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002766 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002767 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002768 if (!FromPtrType) {
2769 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002770 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002771 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002772 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002773 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002774 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002775 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002776
Ted Kremenek6217b802009-07-29 21:53:49 +00002777 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002778 assert(ToPtrType && "No member pointer cast has a target type "
2779 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002780
Sebastian Redl21593ac2009-01-28 18:33:18 +00002781 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2782 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002783
Sebastian Redl21593ac2009-01-28 18:33:18 +00002784 // FIXME: What about dependent types?
2785 assert(FromClass->isRecordType() && "Pointer into non-class.");
2786 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002787
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002788 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002789 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002790 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2791 assert(DerivationOkay &&
2792 "Should not have been called if derivation isn't OK.");
2793 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002794
Sebastian Redl21593ac2009-01-28 18:33:18 +00002795 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2796 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002797 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2798 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2799 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2800 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002801 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002802
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002803 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002804 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2805 << FromClass << ToClass << QualType(VBase, 0)
2806 << From->getSourceRange();
2807 return true;
2808 }
2809
John McCall6b2accb2010-02-10 09:31:12 +00002810 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002811 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2812 Paths.front(),
2813 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002814
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002815 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002816 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002817 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002818 return false;
2819}
2820
Douglas Gregor98cd5992008-10-21 23:43:52 +00002821/// IsQualificationConversion - Determines whether the conversion from
2822/// an rvalue of type FromType to ToType is a qualification conversion
2823/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002824///
2825/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2826/// when the qualification conversion involves a change in the Objective-C
2827/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002828bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002829Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002830 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002831 FromType = Context.getCanonicalType(FromType);
2832 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002833 ObjCLifetimeConversion = false;
2834
Douglas Gregor98cd5992008-10-21 23:43:52 +00002835 // If FromType and ToType are the same type, this is not a
2836 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002837 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002838 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002839
Douglas Gregor98cd5992008-10-21 23:43:52 +00002840 // (C++ 4.4p4):
2841 // A conversion can add cv-qualifiers at levels other than the first
2842 // in multi-level pointers, subject to the following rules: [...]
2843 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002844 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002845 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002846 // Within each iteration of the loop, we check the qualifiers to
2847 // determine if this still looks like a qualification
2848 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002849 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002850 // until there are no more pointers or pointers-to-members left to
2851 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002852 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002853
Douglas Gregor621c92a2011-04-25 18:40:17 +00002854 Qualifiers FromQuals = FromType.getQualifiers();
2855 Qualifiers ToQuals = ToType.getQualifiers();
2856
John McCallf85e1932011-06-15 23:02:42 +00002857 // Objective-C ARC:
2858 // Check Objective-C lifetime conversions.
2859 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2860 UnwrappedAnyPointer) {
2861 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2862 ObjCLifetimeConversion = true;
2863 FromQuals.removeObjCLifetime();
2864 ToQuals.removeObjCLifetime();
2865 } else {
2866 // Qualification conversions cannot cast between different
2867 // Objective-C lifetime qualifiers.
2868 return false;
2869 }
2870 }
2871
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002872 // Allow addition/removal of GC attributes but not changing GC attributes.
2873 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2874 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2875 FromQuals.removeObjCGCAttr();
2876 ToQuals.removeObjCGCAttr();
2877 }
2878
Douglas Gregor98cd5992008-10-21 23:43:52 +00002879 // -- for every j > 0, if const is in cv 1,j then const is in cv
2880 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002881 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002882 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002883
Douglas Gregor98cd5992008-10-21 23:43:52 +00002884 // -- if the cv 1,j and cv 2,j are different, then const is in
2885 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002886 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002887 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002888 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Douglas Gregor98cd5992008-10-21 23:43:52 +00002890 // Keep track of whether all prior cv-qualifiers in the "to" type
2891 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002892 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002893 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002894 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002895
2896 // We are left with FromType and ToType being the pointee types
2897 // after unwrapping the original FromType and ToType the same number
2898 // of types. If we unwrapped any pointers, and if FromType and
2899 // ToType have the same unqualified type (since we checked
2900 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002901 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002902}
2903
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002904/// \brief - Determine whether this is a conversion from a scalar type to an
2905/// atomic type.
2906///
2907/// If successful, updates \c SCS's second and third steps in the conversion
2908/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002909static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2910 bool InOverloadResolution,
2911 StandardConversionSequence &SCS,
2912 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002913 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2914 if (!ToAtomic)
2915 return false;
2916
2917 StandardConversionSequence InnerSCS;
2918 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2919 InOverloadResolution, InnerSCS,
2920 CStyle, /*AllowObjCWritebackConversion=*/false))
2921 return false;
2922
2923 SCS.Second = InnerSCS.Second;
2924 SCS.setToType(1, InnerSCS.getToType(1));
2925 SCS.Third = InnerSCS.Third;
2926 SCS.QualificationIncludesObjCLifetime
2927 = InnerSCS.QualificationIncludesObjCLifetime;
2928 SCS.setToType(2, InnerSCS.getToType(2));
2929 return true;
2930}
2931
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002932static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2933 CXXConstructorDecl *Constructor,
2934 QualType Type) {
2935 const FunctionProtoType *CtorType =
2936 Constructor->getType()->getAs<FunctionProtoType>();
2937 if (CtorType->getNumArgs() > 0) {
2938 QualType FirstArg = CtorType->getArgType(0);
2939 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2940 return true;
2941 }
2942 return false;
2943}
2944
Sebastian Redl56a04282012-02-11 23:51:08 +00002945static OverloadingResult
2946IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2947 CXXRecordDecl *To,
2948 UserDefinedConversionSequence &User,
2949 OverloadCandidateSet &CandidateSet,
2950 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002951 DeclContext::lookup_result R = S.LookupConstructors(To);
2952 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002953 Con != ConEnd; ++Con) {
2954 NamedDecl *D = *Con;
2955 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2956
2957 // Find the constructor (which may be a template).
2958 CXXConstructorDecl *Constructor = 0;
2959 FunctionTemplateDecl *ConstructorTmpl
2960 = dyn_cast<FunctionTemplateDecl>(D);
2961 if (ConstructorTmpl)
2962 Constructor
2963 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2964 else
2965 Constructor = cast<CXXConstructorDecl>(D);
2966
2967 bool Usable = !Constructor->isInvalidDecl() &&
2968 S.isInitListConstructor(Constructor) &&
2969 (AllowExplicit || !Constructor->isExplicit());
2970 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002971 // If the first argument is (a reference to) the target type,
2972 // suppress conversions.
2973 bool SuppressUserConversions =
2974 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002975 if (ConstructorTmpl)
2976 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2977 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002978 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002979 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002980 else
2981 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002982 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002983 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002984 }
2985 }
2986
2987 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2988
2989 OverloadCandidateSet::iterator Best;
2990 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2991 case OR_Success: {
2992 // Record the standard conversion we used and the conversion function.
2993 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002994 QualType ThisType = Constructor->getThisType(S.Context);
2995 // Initializer lists don't have conversions as such.
2996 User.Before.setAsIdentityConversion();
2997 User.HadMultipleCandidates = HadMultipleCandidates;
2998 User.ConversionFunction = Constructor;
2999 User.FoundConversionFunction = Best->FoundDecl;
3000 User.After.setAsIdentityConversion();
3001 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3002 User.After.setAllToTypes(ToType);
3003 return OR_Success;
3004 }
3005
3006 case OR_No_Viable_Function:
3007 return OR_No_Viable_Function;
3008 case OR_Deleted:
3009 return OR_Deleted;
3010 case OR_Ambiguous:
3011 return OR_Ambiguous;
3012 }
3013
3014 llvm_unreachable("Invalid OverloadResult!");
3015}
3016
Douglas Gregor734d9862009-01-30 23:27:23 +00003017/// Determines whether there is a user-defined conversion sequence
3018/// (C++ [over.ics.user]) that converts expression From to the type
3019/// ToType. If such a conversion exists, User will contain the
3020/// user-defined conversion sequence that performs such a conversion
3021/// and this routine will return true. Otherwise, this routine returns
3022/// false and User is unspecified.
3023///
Douglas Gregor734d9862009-01-30 23:27:23 +00003024/// \param AllowExplicit true if the conversion should consider C++0x
3025/// "explicit" conversion functions as well as non-explicit conversion
3026/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003027static OverloadingResult
3028IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003029 UserDefinedConversionSequence &User,
3030 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003031 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003032 // Whether we will only visit constructors.
3033 bool ConstructorsOnly = false;
3034
3035 // If the type we are conversion to is a class type, enumerate its
3036 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003037 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003038 // C++ [over.match.ctor]p1:
3039 // When objects of class type are direct-initialized (8.5), or
3040 // copy-initialized from an expression of the same or a
3041 // derived class type (8.5), overload resolution selects the
3042 // constructor. [...] For copy-initialization, the candidate
3043 // functions are all the converting constructors (12.3.1) of
3044 // that class. The argument list is the expression-list within
3045 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003046 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003047 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003048 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003049 ConstructorsOnly = true;
3050
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003051 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003052 // RequireCompleteType may have returned true due to some invalid decl
3053 // during template instantiation, but ToType may be complete enough now
3054 // to try to recover.
3055 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003056 // We're not going to find any constructors.
3057 } else if (CXXRecordDecl *ToRecordDecl
3058 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003059
3060 Expr **Args = &From;
3061 unsigned NumArgs = 1;
3062 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003063 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003064 // But first, see if there is an init-list-contructor that will work.
3065 OverloadingResult Result = IsInitializerListConstructorConversion(
3066 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3067 if (Result != OR_No_Viable_Function)
3068 return Result;
3069 // Never mind.
3070 CandidateSet.clear();
3071
3072 // If we're list-initializing, we pass the individual elements as
3073 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003074 Args = InitList->getInits();
3075 NumArgs = InitList->getNumInits();
3076 ListInitializing = true;
3077 }
3078
David Blaikie3bc93e32012-12-19 00:45:41 +00003079 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3080 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003081 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003082 NamedDecl *D = *Con;
3083 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3084
Douglas Gregordec06662009-08-21 18:42:58 +00003085 // Find the constructor (which may be a template).
3086 CXXConstructorDecl *Constructor = 0;
3087 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003088 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003089 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003090 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003091 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3092 else
John McCall9aa472c2010-03-19 07:35:19 +00003093 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003094
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003095 bool Usable = !Constructor->isInvalidDecl();
3096 if (ListInitializing)
3097 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3098 else
3099 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3100 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003101 bool SuppressUserConversions = !ConstructorsOnly;
3102 if (SuppressUserConversions && ListInitializing) {
3103 SuppressUserConversions = false;
3104 if (NumArgs == 1) {
3105 // If the first argument is (a reference to) the target type,
3106 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003107 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3108 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003109 }
3110 }
Douglas Gregordec06662009-08-21 18:42:58 +00003111 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003112 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3113 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003114 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003115 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003116 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003117 // Allow one user-defined conversion when user specifies a
3118 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003119 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003120 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003121 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003122 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003123 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003124 }
3125 }
3126
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003127 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003128 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003129 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003130 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003131 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003132 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003133 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003134 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3135 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003136 std::pair<CXXRecordDecl::conversion_iterator,
3137 CXXRecordDecl::conversion_iterator>
3138 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3139 for (CXXRecordDecl::conversion_iterator
3140 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003141 DeclAccessPair FoundDecl = I.getPair();
3142 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003143 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3144 if (isa<UsingShadowDecl>(D))
3145 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3146
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003147 CXXConversionDecl *Conv;
3148 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003149 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3150 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003151 else
John McCall32daa422010-03-31 01:36:47 +00003152 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003153
3154 if (AllowExplicit || !Conv->isExplicit()) {
3155 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003156 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3157 ActingContext, From, ToType,
3158 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003159 else
John McCall120d63c2010-08-24 20:38:10 +00003160 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3161 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003162 }
3163 }
3164 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003165 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003166
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003167 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3168
Douglas Gregor60d62c22008-10-31 16:23:19 +00003169 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003170 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003171 case OR_Success:
3172 // Record the standard conversion we used and the conversion function.
3173 if (CXXConstructorDecl *Constructor
3174 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3175 // C++ [over.ics.user]p1:
3176 // If the user-defined conversion is specified by a
3177 // constructor (12.3.1), the initial standard conversion
3178 // sequence converts the source type to the type required by
3179 // the argument of the constructor.
3180 //
3181 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003182 if (isa<InitListExpr>(From)) {
3183 // Initializer lists don't have conversions as such.
3184 User.Before.setAsIdentityConversion();
3185 } else {
3186 if (Best->Conversions[0].isEllipsis())
3187 User.EllipsisConversion = true;
3188 else {
3189 User.Before = Best->Conversions[0].Standard;
3190 User.EllipsisConversion = false;
3191 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003192 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003193 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003194 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003195 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003196 User.After.setAsIdentityConversion();
3197 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3198 User.After.setAllToTypes(ToType);
3199 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003200 }
3201 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003202 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3203 // C++ [over.ics.user]p1:
3204 //
3205 // [...] If the user-defined conversion is specified by a
3206 // conversion function (12.3.2), the initial standard
3207 // conversion sequence converts the source type to the
3208 // implicit object parameter of the conversion function.
3209 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003210 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003211 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003212 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003213 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003214
John McCall120d63c2010-08-24 20:38:10 +00003215 // C++ [over.ics.user]p2:
3216 // The second standard conversion sequence converts the
3217 // result of the user-defined conversion to the target type
3218 // for the sequence. Since an implicit conversion sequence
3219 // is an initialization, the special rules for
3220 // initialization by user-defined conversion apply when
3221 // selecting the best user-defined conversion for a
3222 // user-defined conversion sequence (see 13.3.3 and
3223 // 13.3.3.1).
3224 User.After = Best->FinalConversion;
3225 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003226 }
David Blaikie7530c032012-01-17 06:56:22 +00003227 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003228
John McCall120d63c2010-08-24 20:38:10 +00003229 case OR_No_Viable_Function:
3230 return OR_No_Viable_Function;
3231 case OR_Deleted:
3232 // No conversion here! We're done.
3233 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003234
John McCall120d63c2010-08-24 20:38:10 +00003235 case OR_Ambiguous:
3236 return OR_Ambiguous;
3237 }
3238
David Blaikie7530c032012-01-17 06:56:22 +00003239 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003240}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003242bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003243Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003244 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003245 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003247 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003248 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003249 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003250 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003251 diag::err_typecheck_ambiguous_condition)
3252 << From->getType() << ToType << From->getSourceRange();
3253 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003254 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003255 diag::err_typecheck_nonviable_condition)
3256 << From->getType() << ToType << From->getSourceRange();
3257 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003258 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003259 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003261}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003262
Douglas Gregorb734e242012-02-22 17:32:19 +00003263/// \brief Compare the user-defined conversion functions or constructors
3264/// of two user-defined conversion sequences to determine whether any ordering
3265/// is possible.
3266static ImplicitConversionSequence::CompareKind
3267compareConversionFunctions(Sema &S,
3268 FunctionDecl *Function1,
3269 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003270 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003271 return ImplicitConversionSequence::Indistinguishable;
3272
3273 // Objective-C++:
3274 // If both conversion functions are implicitly-declared conversions from
3275 // a lambda closure type to a function pointer and a block pointer,
3276 // respectively, always prefer the conversion to a function pointer,
3277 // because the function pointer is more lightweight and is more likely
3278 // to keep code working.
3279 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3280 if (!Conv1)
3281 return ImplicitConversionSequence::Indistinguishable;
3282
3283 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3284 if (!Conv2)
3285 return ImplicitConversionSequence::Indistinguishable;
3286
3287 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3288 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3289 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3290 if (Block1 != Block2)
3291 return Block1? ImplicitConversionSequence::Worse
3292 : ImplicitConversionSequence::Better;
3293 }
3294
3295 return ImplicitConversionSequence::Indistinguishable;
3296}
3297
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003298/// CompareImplicitConversionSequences - Compare two implicit
3299/// conversion sequences to determine whether one is better than the
3300/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003301static ImplicitConversionSequence::CompareKind
3302CompareImplicitConversionSequences(Sema &S,
3303 const ImplicitConversionSequence& ICS1,
3304 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003305{
3306 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3307 // conversion sequences (as defined in 13.3.3.1)
3308 // -- a standard conversion sequence (13.3.3.1.1) is a better
3309 // conversion sequence than a user-defined conversion sequence or
3310 // an ellipsis conversion sequence, and
3311 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3312 // conversion sequence than an ellipsis conversion sequence
3313 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003314 //
John McCall1d318332010-01-12 00:44:57 +00003315 // C++0x [over.best.ics]p10:
3316 // For the purpose of ranking implicit conversion sequences as
3317 // described in 13.3.3.2, the ambiguous conversion sequence is
3318 // treated as a user-defined sequence that is indistinguishable
3319 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003320 if (ICS1.getKindRank() < ICS2.getKindRank())
3321 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003322 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003323 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003324
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003325 // The following checks require both conversion sequences to be of
3326 // the same kind.
3327 if (ICS1.getKind() != ICS2.getKind())
3328 return ImplicitConversionSequence::Indistinguishable;
3329
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003330 ImplicitConversionSequence::CompareKind Result =
3331 ImplicitConversionSequence::Indistinguishable;
3332
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003333 // Two implicit conversion sequences of the same form are
3334 // indistinguishable conversion sequences unless one of the
3335 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003336 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003337 Result = CompareStandardConversionSequences(S,
3338 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003339 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003340 // User-defined conversion sequence U1 is a better conversion
3341 // sequence than another user-defined conversion sequence U2 if
3342 // they contain the same user-defined conversion function or
3343 // constructor and if the second standard conversion sequence of
3344 // U1 is better than the second standard conversion sequence of
3345 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003346 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003347 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003348 Result = CompareStandardConversionSequences(S,
3349 ICS1.UserDefined.After,
3350 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003351 else
3352 Result = compareConversionFunctions(S,
3353 ICS1.UserDefined.ConversionFunction,
3354 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003355 }
3356
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003357 // List-initialization sequence L1 is a better conversion sequence than
3358 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3359 // for some X and L2 does not.
3360 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003361 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003362 ICS1.isListInitializationSequence() &&
3363 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003364 if (ICS1.isStdInitializerListElement() &&
3365 !ICS2.isStdInitializerListElement())
3366 return ImplicitConversionSequence::Better;
3367 if (!ICS1.isStdInitializerListElement() &&
3368 ICS2.isStdInitializerListElement())
3369 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003370 }
3371
3372 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003373}
3374
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003375static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3376 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3377 Qualifiers Quals;
3378 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003381
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003382 return Context.hasSameUnqualifiedType(T1, T2);
3383}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003384
Douglas Gregorad323a82010-01-27 03:51:04 +00003385// Per 13.3.3.2p3, compare the given standard conversion sequences to
3386// determine if one is a proper subset of the other.
3387static ImplicitConversionSequence::CompareKind
3388compareStandardConversionSubsets(ASTContext &Context,
3389 const StandardConversionSequence& SCS1,
3390 const StandardConversionSequence& SCS2) {
3391 ImplicitConversionSequence::CompareKind Result
3392 = ImplicitConversionSequence::Indistinguishable;
3393
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003395 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003396 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3397 return ImplicitConversionSequence::Better;
3398 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3399 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400
Douglas Gregorad323a82010-01-27 03:51:04 +00003401 if (SCS1.Second != SCS2.Second) {
3402 if (SCS1.Second == ICK_Identity)
3403 Result = ImplicitConversionSequence::Better;
3404 else if (SCS2.Second == ICK_Identity)
3405 Result = ImplicitConversionSequence::Worse;
3406 else
3407 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003408 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003409 return ImplicitConversionSequence::Indistinguishable;
3410
3411 if (SCS1.Third == SCS2.Third) {
3412 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3413 : ImplicitConversionSequence::Indistinguishable;
3414 }
3415
3416 if (SCS1.Third == ICK_Identity)
3417 return Result == ImplicitConversionSequence::Worse
3418 ? ImplicitConversionSequence::Indistinguishable
3419 : ImplicitConversionSequence::Better;
3420
3421 if (SCS2.Third == ICK_Identity)
3422 return Result == ImplicitConversionSequence::Better
3423 ? ImplicitConversionSequence::Indistinguishable
3424 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003425
Douglas Gregorad323a82010-01-27 03:51:04 +00003426 return ImplicitConversionSequence::Indistinguishable;
3427}
3428
Douglas Gregor440a4832011-01-26 14:52:12 +00003429/// \brief Determine whether one of the given reference bindings is better
3430/// than the other based on what kind of bindings they are.
3431static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3432 const StandardConversionSequence &SCS2) {
3433 // C++0x [over.ics.rank]p3b4:
3434 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3435 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003436 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003437 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003439 // reference*.
3440 //
3441 // FIXME: Rvalue references. We're going rogue with the above edits,
3442 // because the semantics in the current C++0x working paper (N3225 at the
3443 // time of this writing) break the standard definition of std::forward
3444 // and std::reference_wrapper when dealing with references to functions.
3445 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003446 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3447 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3448 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003449
Douglas Gregor440a4832011-01-26 14:52:12 +00003450 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3451 SCS2.IsLvalueReference) ||
3452 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3453 !SCS2.IsLvalueReference);
3454}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003456/// CompareStandardConversionSequences - Compare two standard
3457/// conversion sequences to determine whether one is better than the
3458/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003459static ImplicitConversionSequence::CompareKind
3460CompareStandardConversionSequences(Sema &S,
3461 const StandardConversionSequence& SCS1,
3462 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003463{
3464 // Standard conversion sequence S1 is a better conversion sequence
3465 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3466
3467 // -- S1 is a proper subsequence of S2 (comparing the conversion
3468 // sequences in the canonical form defined by 13.3.3.1.1,
3469 // excluding any Lvalue Transformation; the identity conversion
3470 // sequence is considered to be a subsequence of any
3471 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003472 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003473 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003474 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003475
3476 // -- the rank of S1 is better than the rank of S2 (by the rules
3477 // defined below), or, if not that,
3478 ImplicitConversionRank Rank1 = SCS1.getRank();
3479 ImplicitConversionRank Rank2 = SCS2.getRank();
3480 if (Rank1 < Rank2)
3481 return ImplicitConversionSequence::Better;
3482 else if (Rank2 < Rank1)
3483 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003484
Douglas Gregor57373262008-10-22 14:17:15 +00003485 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3486 // are indistinguishable unless one of the following rules
3487 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Douglas Gregor57373262008-10-22 14:17:15 +00003489 // A conversion that is not a conversion of a pointer, or
3490 // pointer to member, to bool is better than another conversion
3491 // that is such a conversion.
3492 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3493 return SCS2.isPointerConversionToBool()
3494 ? ImplicitConversionSequence::Better
3495 : ImplicitConversionSequence::Worse;
3496
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003497 // C++ [over.ics.rank]p4b2:
3498 //
3499 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003500 // conversion of B* to A* is better than conversion of B* to
3501 // void*, and conversion of A* to void* is better than conversion
3502 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003503 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003504 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003505 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003506 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003507 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3508 // Exactly one of the conversion sequences is a conversion to
3509 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003510 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3511 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003512 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3513 // Neither conversion sequence converts to a void pointer; compare
3514 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003515 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003516 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003517 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003518 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3519 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003520 // Both conversion sequences are conversions to void
3521 // pointers. Compare the source types to determine if there's an
3522 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003523 QualType FromType1 = SCS1.getFromType();
3524 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003525
3526 // Adjust the types we're converting from via the array-to-pointer
3527 // conversion, if we need to.
3528 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003529 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003530 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003531 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003532
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003533 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3534 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003535
John McCall120d63c2010-08-24 20:38:10 +00003536 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003537 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003538 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003539 return ImplicitConversionSequence::Worse;
3540
3541 // Objective-C++: If one interface is more specific than the
3542 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003543 const ObjCObjectPointerType* FromObjCPtr1
3544 = FromType1->getAs<ObjCObjectPointerType>();
3545 const ObjCObjectPointerType* FromObjCPtr2
3546 = FromType2->getAs<ObjCObjectPointerType>();
3547 if (FromObjCPtr1 && FromObjCPtr2) {
3548 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3549 FromObjCPtr2);
3550 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3551 FromObjCPtr1);
3552 if (AssignLeft != AssignRight) {
3553 return AssignLeft? ImplicitConversionSequence::Better
3554 : ImplicitConversionSequence::Worse;
3555 }
Douglas Gregor01919692009-12-13 21:37:05 +00003556 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003557 }
Douglas Gregor57373262008-10-22 14:17:15 +00003558
3559 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3560 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003561 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003562 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003563 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003564
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003565 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003566 // Check for a better reference binding based on the kind of bindings.
3567 if (isBetterReferenceBindingKind(SCS1, SCS2))
3568 return ImplicitConversionSequence::Better;
3569 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3570 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003571
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003572 // C++ [over.ics.rank]p3b4:
3573 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3574 // which the references refer are the same type except for
3575 // top-level cv-qualifiers, and the type to which the reference
3576 // initialized by S2 refers is more cv-qualified than the type
3577 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003578 QualType T1 = SCS1.getToType(2);
3579 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003580 T1 = S.Context.getCanonicalType(T1);
3581 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003582 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003583 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3584 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003585 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003586 // Objective-C++ ARC: If the references refer to objects with different
3587 // lifetimes, prefer bindings that don't change lifetime.
3588 if (SCS1.ObjCLifetimeConversionBinding !=
3589 SCS2.ObjCLifetimeConversionBinding) {
3590 return SCS1.ObjCLifetimeConversionBinding
3591 ? ImplicitConversionSequence::Worse
3592 : ImplicitConversionSequence::Better;
3593 }
3594
Chandler Carruth6df868e2010-12-12 08:17:55 +00003595 // If the type is an array type, promote the element qualifiers to the
3596 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003597 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003598 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003599 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003600 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003601 if (T2.isMoreQualifiedThan(T1))
3602 return ImplicitConversionSequence::Better;
3603 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003604 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003605 }
3606 }
Douglas Gregor57373262008-10-22 14:17:15 +00003607
Francois Pichet1c98d622011-09-18 21:37:37 +00003608 // In Microsoft mode, prefer an integral conversion to a
3609 // floating-to-integral conversion if the integral conversion
3610 // is between types of the same size.
3611 // For example:
3612 // void f(float);
3613 // void f(int);
3614 // int main {
3615 // long a;
3616 // f(a);
3617 // }
3618 // Here, MSVC will call f(int) instead of generating a compile error
3619 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003620 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003621 SCS1.Second == ICK_Integral_Conversion &&
3622 SCS2.Second == ICK_Floating_Integral &&
3623 S.Context.getTypeSize(SCS1.getFromType()) ==
3624 S.Context.getTypeSize(SCS1.getToType(2)))
3625 return ImplicitConversionSequence::Better;
3626
Douglas Gregor57373262008-10-22 14:17:15 +00003627 return ImplicitConversionSequence::Indistinguishable;
3628}
3629
3630/// CompareQualificationConversions - Compares two standard conversion
3631/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003632/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3633ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003634CompareQualificationConversions(Sema &S,
3635 const StandardConversionSequence& SCS1,
3636 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003637 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003638 // -- S1 and S2 differ only in their qualification conversion and
3639 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3640 // cv-qualification signature of type T1 is a proper subset of
3641 // the cv-qualification signature of type T2, and S1 is not the
3642 // deprecated string literal array-to-pointer conversion (4.2).
3643 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3644 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3645 return ImplicitConversionSequence::Indistinguishable;
3646
3647 // FIXME: the example in the standard doesn't use a qualification
3648 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003649 QualType T1 = SCS1.getToType(2);
3650 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003651 T1 = S.Context.getCanonicalType(T1);
3652 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003653 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003654 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3655 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003656
3657 // If the types are the same, we won't learn anything by unwrapped
3658 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003659 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003660 return ImplicitConversionSequence::Indistinguishable;
3661
Chandler Carruth28e318c2009-12-29 07:16:59 +00003662 // If the type is an array type, promote the element qualifiers to the type
3663 // for comparison.
3664 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003665 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003666 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003667 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003668
Mike Stump1eb44332009-09-09 15:08:12 +00003669 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003670 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003671
3672 // Objective-C++ ARC:
3673 // Prefer qualification conversions not involving a change in lifetime
3674 // to qualification conversions that do not change lifetime.
3675 if (SCS1.QualificationIncludesObjCLifetime !=
3676 SCS2.QualificationIncludesObjCLifetime) {
3677 Result = SCS1.QualificationIncludesObjCLifetime
3678 ? ImplicitConversionSequence::Worse
3679 : ImplicitConversionSequence::Better;
3680 }
3681
John McCall120d63c2010-08-24 20:38:10 +00003682 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003683 // Within each iteration of the loop, we check the qualifiers to
3684 // determine if this still looks like a qualification
3685 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003686 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003687 // until there are no more pointers or pointers-to-members left
3688 // to unwrap. This essentially mimics what
3689 // IsQualificationConversion does, but here we're checking for a
3690 // strict subset of qualifiers.
3691 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3692 // The qualifiers are the same, so this doesn't tell us anything
3693 // about how the sequences rank.
3694 ;
3695 else if (T2.isMoreQualifiedThan(T1)) {
3696 // T1 has fewer qualifiers, so it could be the better sequence.
3697 if (Result == ImplicitConversionSequence::Worse)
3698 // Neither has qualifiers that are a subset of the other's
3699 // qualifiers.
3700 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Douglas Gregor57373262008-10-22 14:17:15 +00003702 Result = ImplicitConversionSequence::Better;
3703 } else if (T1.isMoreQualifiedThan(T2)) {
3704 // T2 has fewer qualifiers, so it could be the better sequence.
3705 if (Result == ImplicitConversionSequence::Better)
3706 // Neither has qualifiers that are a subset of the other's
3707 // qualifiers.
3708 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Douglas Gregor57373262008-10-22 14:17:15 +00003710 Result = ImplicitConversionSequence::Worse;
3711 } else {
3712 // Qualifiers are disjoint.
3713 return ImplicitConversionSequence::Indistinguishable;
3714 }
3715
3716 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003717 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003718 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003719 }
3720
Douglas Gregor57373262008-10-22 14:17:15 +00003721 // Check that the winning standard conversion sequence isn't using
3722 // the deprecated string literal array to pointer conversion.
3723 switch (Result) {
3724 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003725 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003726 Result = ImplicitConversionSequence::Indistinguishable;
3727 break;
3728
3729 case ImplicitConversionSequence::Indistinguishable:
3730 break;
3731
3732 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003733 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003734 Result = ImplicitConversionSequence::Indistinguishable;
3735 break;
3736 }
3737
3738 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003739}
3740
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003741/// CompareDerivedToBaseConversions - Compares two standard conversion
3742/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003743/// various kinds of derived-to-base conversions (C++
3744/// [over.ics.rank]p4b3). As part of these checks, we also look at
3745/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003746ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003747CompareDerivedToBaseConversions(Sema &S,
3748 const StandardConversionSequence& SCS1,
3749 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003750 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003751 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003752 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003753 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003754
3755 // Adjust the types we're converting from via the array-to-pointer
3756 // conversion, if we need to.
3757 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003758 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003759 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003760 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003761
3762 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003763 FromType1 = S.Context.getCanonicalType(FromType1);
3764 ToType1 = S.Context.getCanonicalType(ToType1);
3765 FromType2 = S.Context.getCanonicalType(FromType2);
3766 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003767
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003768 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003769 //
3770 // If class B is derived directly or indirectly from class A and
3771 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003772 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003773 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003774 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003775 SCS2.Second == ICK_Pointer_Conversion &&
3776 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3777 FromType1->isPointerType() && FromType2->isPointerType() &&
3778 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003779 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003780 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003781 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003782 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003783 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003784 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003785 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003787
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003788 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003789 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003790 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003791 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003792 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003793 return ImplicitConversionSequence::Worse;
3794 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003795
3796 // -- conversion of B* to A* is better than conversion of C* to A*,
3797 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003798 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003799 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003800 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003801 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003802 }
3803 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3804 SCS2.Second == ICK_Pointer_Conversion) {
3805 const ObjCObjectPointerType *FromPtr1
3806 = FromType1->getAs<ObjCObjectPointerType>();
3807 const ObjCObjectPointerType *FromPtr2
3808 = FromType2->getAs<ObjCObjectPointerType>();
3809 const ObjCObjectPointerType *ToPtr1
3810 = ToType1->getAs<ObjCObjectPointerType>();
3811 const ObjCObjectPointerType *ToPtr2
3812 = ToType2->getAs<ObjCObjectPointerType>();
3813
3814 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3815 // Apply the same conversion ranking rules for Objective-C pointer types
3816 // that we do for C++ pointers to class types. However, we employ the
3817 // Objective-C pseudo-subtyping relationship used for assignment of
3818 // Objective-C pointer types.
3819 bool FromAssignLeft
3820 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3821 bool FromAssignRight
3822 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3823 bool ToAssignLeft
3824 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3825 bool ToAssignRight
3826 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3827
3828 // A conversion to an a non-id object pointer type or qualified 'id'
3829 // type is better than a conversion to 'id'.
3830 if (ToPtr1->isObjCIdType() &&
3831 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3832 return ImplicitConversionSequence::Worse;
3833 if (ToPtr2->isObjCIdType() &&
3834 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3835 return ImplicitConversionSequence::Better;
3836
3837 // A conversion to a non-id object pointer type is better than a
3838 // conversion to a qualified 'id' type
3839 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3840 return ImplicitConversionSequence::Worse;
3841 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3842 return ImplicitConversionSequence::Better;
3843
3844 // A conversion to an a non-Class object pointer type or qualified 'Class'
3845 // type is better than a conversion to 'Class'.
3846 if (ToPtr1->isObjCClassType() &&
3847 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3848 return ImplicitConversionSequence::Worse;
3849 if (ToPtr2->isObjCClassType() &&
3850 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3851 return ImplicitConversionSequence::Better;
3852
3853 // A conversion to a non-Class object pointer type is better than a
3854 // conversion to a qualified 'Class' type.
3855 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3856 return ImplicitConversionSequence::Worse;
3857 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3858 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003859
Douglas Gregor395cc372011-01-31 18:51:41 +00003860 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3861 if (S.Context.hasSameType(FromType1, FromType2) &&
3862 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3863 (ToAssignLeft != ToAssignRight))
3864 return ToAssignLeft? ImplicitConversionSequence::Worse
3865 : ImplicitConversionSequence::Better;
3866
3867 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3868 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3869 (FromAssignLeft != FromAssignRight))
3870 return FromAssignLeft? ImplicitConversionSequence::Better
3871 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003872 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003873 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003874
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003875 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003876 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3877 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3878 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003879 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003880 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003881 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003882 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003883 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003884 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003886 ToType2->getAs<MemberPointerType>();
3887 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3888 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3889 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3890 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3891 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3892 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3893 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3894 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003895 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003897 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003898 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003899 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003900 return ImplicitConversionSequence::Better;
3901 }
3902 // conversion of B::* to C::* is better than conversion of A::* to C::*
3903 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003904 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003905 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003906 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003907 return ImplicitConversionSequence::Worse;
3908 }
3909 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003910
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003911 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003912 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003913 // -- binding of an expression of type C to a reference of type
3914 // B& is better than binding an expression of type C to a
3915 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003916 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3917 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3918 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003919 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003920 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003921 return ImplicitConversionSequence::Worse;
3922 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003923
Douglas Gregor225c41e2008-11-03 19:09:14 +00003924 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003925 // -- binding of an expression of type B to a reference of type
3926 // A& is better than binding an expression of type C to a
3927 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003928 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3929 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3930 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003931 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003932 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003933 return ImplicitConversionSequence::Worse;
3934 }
3935 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003936
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003937 return ImplicitConversionSequence::Indistinguishable;
3938}
3939
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003940/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3941/// C++ class.
3942static bool isTypeValid(QualType T) {
3943 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3944 return !Record->isInvalidDecl();
3945
3946 return true;
3947}
3948
Douglas Gregorabe183d2010-04-13 16:31:36 +00003949/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3950/// determine whether they are reference-related,
3951/// reference-compatible, reference-compatible with added
3952/// qualification, or incompatible, for use in C++ initialization by
3953/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3954/// type, and the first type (T1) is the pointee type of the reference
3955/// type being initialized.
3956Sema::ReferenceCompareResult
3957Sema::CompareReferenceRelationship(SourceLocation Loc,
3958 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003959 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003960 bool &ObjCConversion,
3961 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003962 assert(!OrigT1->isReferenceType() &&
3963 "T1 must be the pointee type of the reference type");
3964 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3965
3966 QualType T1 = Context.getCanonicalType(OrigT1);
3967 QualType T2 = Context.getCanonicalType(OrigT2);
3968 Qualifiers T1Quals, T2Quals;
3969 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3970 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3971
3972 // C++ [dcl.init.ref]p4:
3973 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3974 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3975 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003976 DerivedToBase = false;
3977 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003978 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003979 if (UnqualT1 == UnqualT2) {
3980 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003981 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003982 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3983 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003984 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003985 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3986 UnqualT2->isObjCObjectOrInterfaceType() &&
3987 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3988 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003989 else
3990 return Ref_Incompatible;
3991
3992 // At this point, we know that T1 and T2 are reference-related (at
3993 // least).
3994
3995 // If the type is an array type, promote the element qualifiers to the type
3996 // for comparison.
3997 if (isa<ArrayType>(T1) && T1Quals)
3998 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3999 if (isa<ArrayType>(T2) && T2Quals)
4000 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4001
4002 // C++ [dcl.init.ref]p4:
4003 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4004 // reference-related to T2 and cv1 is the same cv-qualification
4005 // as, or greater cv-qualification than, cv2. For purposes of
4006 // overload resolution, cases for which cv1 is greater
4007 // cv-qualification than cv2 are identified as
4008 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004009 //
4010 // Note that we also require equivalence of Objective-C GC and address-space
4011 // qualifiers when performing these computations, so that e.g., an int in
4012 // address space 1 is not reference-compatible with an int in address
4013 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00004014 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4015 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4016 T1Quals.removeObjCLifetime();
4017 T2Quals.removeObjCLifetime();
4018 ObjCLifetimeConversion = true;
4019 }
4020
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004021 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004022 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004023 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004024 return Ref_Compatible_With_Added_Qualification;
4025 else
4026 return Ref_Related;
4027}
4028
Douglas Gregor604eb652010-08-11 02:15:33 +00004029/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004030/// with DeclType. Return true if something definite is found.
4031static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004032FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4033 QualType DeclType, SourceLocation DeclLoc,
4034 Expr *Init, QualType T2, bool AllowRvalues,
4035 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004036 assert(T2->isRecordType() && "Can only find conversions of record types.");
4037 CXXRecordDecl *T2RecordDecl
4038 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4039
4040 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004041 std::pair<CXXRecordDecl::conversion_iterator,
4042 CXXRecordDecl::conversion_iterator>
4043 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4044 for (CXXRecordDecl::conversion_iterator
4045 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004046 NamedDecl *D = *I;
4047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4048 if (isa<UsingShadowDecl>(D))
4049 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4050
4051 FunctionTemplateDecl *ConvTemplate
4052 = dyn_cast<FunctionTemplateDecl>(D);
4053 CXXConversionDecl *Conv;
4054 if (ConvTemplate)
4055 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4056 else
4057 Conv = cast<CXXConversionDecl>(D);
4058
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004059 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004060 // explicit conversions, skip it.
4061 if (!AllowExplicit && Conv->isExplicit())
4062 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
Douglas Gregor604eb652010-08-11 02:15:33 +00004064 if (AllowRvalues) {
4065 bool DerivedToBase = false;
4066 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004067 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004068
4069 // If we are initializing an rvalue reference, don't permit conversion
4070 // functions that return lvalues.
4071 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4072 const ReferenceType *RefType
4073 = Conv->getConversionType()->getAs<LValueReferenceType>();
4074 if (RefType && !RefType->getPointeeType()->isFunctionType())
4075 continue;
4076 }
4077
Douglas Gregor604eb652010-08-11 02:15:33 +00004078 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004079 S.CompareReferenceRelationship(
4080 DeclLoc,
4081 Conv->getConversionType().getNonReferenceType()
4082 .getUnqualifiedType(),
4083 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004084 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004085 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004086 continue;
4087 } else {
4088 // If the conversion function doesn't return a reference type,
4089 // it can't be considered for this conversion. An rvalue reference
4090 // is only acceptable if its referencee is a function type.
4091
4092 const ReferenceType *RefType =
4093 Conv->getConversionType()->getAs<ReferenceType>();
4094 if (!RefType ||
4095 (!RefType->isLValueReferenceType() &&
4096 !RefType->getPointeeType()->isFunctionType()))
4097 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004098 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004099
Douglas Gregor604eb652010-08-11 02:15:33 +00004100 if (ConvTemplate)
4101 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004102 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004103 else
4104 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004105 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004106 }
4107
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004108 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4109
Sebastian Redl4680bf22010-06-30 18:13:39 +00004110 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004111 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004112 case OR_Success:
4113 // C++ [over.ics.ref]p1:
4114 //
4115 // [...] If the parameter binds directly to the result of
4116 // applying a conversion function to the argument
4117 // expression, the implicit conversion sequence is a
4118 // user-defined conversion sequence (13.3.3.1.2), with the
4119 // second standard conversion sequence either an identity
4120 // conversion or, if the conversion function returns an
4121 // entity of a type that is a derived class of the parameter
4122 // type, a derived-to-base Conversion.
4123 if (!Best->FinalConversion.DirectBinding)
4124 return false;
4125
4126 ICS.setUserDefined();
4127 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4128 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004129 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004130 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004131 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004132 ICS.UserDefined.EllipsisConversion = false;
4133 assert(ICS.UserDefined.After.ReferenceBinding &&
4134 ICS.UserDefined.After.DirectBinding &&
4135 "Expected a direct reference binding!");
4136 return true;
4137
4138 case OR_Ambiguous:
4139 ICS.setAmbiguous();
4140 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4141 Cand != CandidateSet.end(); ++Cand)
4142 if (Cand->Viable)
4143 ICS.Ambiguous.addConversion(Cand->Function);
4144 return true;
4145
4146 case OR_No_Viable_Function:
4147 case OR_Deleted:
4148 // There was no suitable conversion, or we found a deleted
4149 // conversion; continue with other checks.
4150 return false;
4151 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152
David Blaikie7530c032012-01-17 06:56:22 +00004153 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004154}
4155
Douglas Gregorabe183d2010-04-13 16:31:36 +00004156/// \brief Compute an implicit conversion sequence for reference
4157/// initialization.
4158static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004159TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004160 SourceLocation DeclLoc,
4161 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004162 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004163 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4164
4165 // Most paths end in a failed conversion.
4166 ImplicitConversionSequence ICS;
4167 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4168
4169 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4170 QualType T2 = Init->getType();
4171
4172 // If the initializer is the address of an overloaded function, try
4173 // to resolve the overloaded function. If all goes well, T2 is the
4174 // type of the resulting function.
4175 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4176 DeclAccessPair Found;
4177 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4178 false, Found))
4179 T2 = Fn->getType();
4180 }
4181
4182 // Compute some basic properties of the types and the initializer.
4183 bool isRValRef = DeclType->isRValueReferenceType();
4184 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004185 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004186 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004187 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004188 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004189 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004190 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004191
Douglas Gregorabe183d2010-04-13 16:31:36 +00004192
Sebastian Redl4680bf22010-06-30 18:13:39 +00004193 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004194 // A reference to type "cv1 T1" is initialized by an expression
4195 // of type "cv2 T2" as follows:
4196
Sebastian Redl4680bf22010-06-30 18:13:39 +00004197 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004198 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004199 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4200 // reference-compatible with "cv2 T2," or
4201 //
4202 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4203 if (InitCategory.isLValue() &&
4204 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004205 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004206 // When a parameter of reference type binds directly (8.5.3)
4207 // to an argument expression, the implicit conversion sequence
4208 // is the identity conversion, unless the argument expression
4209 // has a type that is a derived class of the parameter type,
4210 // in which case the implicit conversion sequence is a
4211 // derived-to-base Conversion (13.3.3.1).
4212 ICS.setStandard();
4213 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004214 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4215 : ObjCConversion? ICK_Compatible_Conversion
4216 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004217 ICS.Standard.Third = ICK_Identity;
4218 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4219 ICS.Standard.setToType(0, T2);
4220 ICS.Standard.setToType(1, T1);
4221 ICS.Standard.setToType(2, T1);
4222 ICS.Standard.ReferenceBinding = true;
4223 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004224 ICS.Standard.IsLvalueReference = !isRValRef;
4225 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4226 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004227 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004228 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004229 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004230
Sebastian Redl4680bf22010-06-30 18:13:39 +00004231 // Nothing more to do: the inaccessibility/ambiguity check for
4232 // derived-to-base conversions is suppressed when we're
4233 // computing the implicit conversion sequence (C++
4234 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004235 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004236 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004237
Sebastian Redl4680bf22010-06-30 18:13:39 +00004238 // -- has a class type (i.e., T2 is a class type), where T1 is
4239 // not reference-related to T2, and can be implicitly
4240 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4241 // is reference-compatible with "cv3 T3" 92) (this
4242 // conversion is selected by enumerating the applicable
4243 // conversion functions (13.3.1.6) and choosing the best
4244 // one through overload resolution (13.3)),
4245 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004247 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004248 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4249 Init, T2, /*AllowRvalues=*/false,
4250 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004251 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004252 }
4253 }
4254
Sebastian Redl4680bf22010-06-30 18:13:39 +00004255 // -- Otherwise, the reference shall be an lvalue reference to a
4256 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004257 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004259 // We actually handle one oddity of C++ [over.ics.ref] at this
4260 // point, which is that, due to p2 (which short-circuits reference
4261 // binding by only attempting a simple conversion for non-direct
4262 // bindings) and p3's strange wording, we allow a const volatile
4263 // reference to bind to an rvalue. Hence the check for the presence
4264 // of "const" rather than checking for "const" being the only
4265 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004266 // This is also the point where rvalue references and lvalue inits no longer
4267 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004268 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004269 return ICS;
4270
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004271 // -- If the initializer expression
4272 //
4273 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004274 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004275 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4276 (InitCategory.isXValue() ||
4277 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4278 (InitCategory.isLValue() && T2->isFunctionType()))) {
4279 ICS.setStandard();
4280 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 : ObjCConversion? ICK_Compatible_Conversion
4283 : ICK_Identity;
4284 ICS.Standard.Third = ICK_Identity;
4285 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4286 ICS.Standard.setToType(0, T2);
4287 ICS.Standard.setToType(1, T1);
4288 ICS.Standard.setToType(2, T1);
4289 ICS.Standard.ReferenceBinding = true;
4290 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4291 // binding unless we're binding to a class prvalue.
4292 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4293 // allow the use of rvalue references in C++98/03 for the benefit of
4294 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004296 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004297 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004298 ICS.Standard.IsLvalueReference = !isRValRef;
4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004303 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004307 // -- has a class type (i.e., T2 is a class type), where T1 is not
4308 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309 // an xvalue, class prvalue, or function lvalue of type
4310 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004311 // "cv3 T3",
4312 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004314 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004316 // class subobject).
4317 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004319 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320 Init, T2, /*AllowRvalues=*/true,
4321 AllowExplicit)) {
4322 // In the second case, if the reference is an rvalue reference
4323 // and the second standard conversion sequence of the
4324 // user-defined conversion sequence includes an lvalue-to-rvalue
4325 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004327 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004330 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004331 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332
Douglas Gregorabe183d2010-04-13 16:31:36 +00004333 // -- Otherwise, a temporary of type "cv1 T1" is created and
4334 // initialized from the initializer expression using the
4335 // rules for a non-reference copy initialization (8.5). The
4336 // reference is then bound to the temporary. If T1 is
4337 // reference-related to T2, cv1 must be the same
4338 // cv-qualification as, or greater cv-qualification than,
4339 // cv2; otherwise, the program is ill-formed.
4340 if (RefRelationship == Sema::Ref_Related) {
4341 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4342 // we would be reference-compatible or reference-compatible with
4343 // added qualification. But that wasn't the case, so the reference
4344 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004345 //
4346 // Note that we only want to check address spaces and cvr-qualifiers here.
4347 // ObjC GC and lifetime qualifiers aren't important.
4348 Qualifiers T1Quals = T1.getQualifiers();
4349 Qualifiers T2Quals = T2.getQualifiers();
4350 T1Quals.removeObjCGCAttr();
4351 T1Quals.removeObjCLifetime();
4352 T2Quals.removeObjCGCAttr();
4353 T2Quals.removeObjCLifetime();
4354 if (!T1Quals.compatiblyIncludes(T2Quals))
4355 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004356 }
4357
4358 // If at least one of the types is a class type, the types are not
4359 // related, and we aren't allowed any user conversions, the
4360 // reference binding fails. This case is important for breaking
4361 // recursion, since TryImplicitConversion below will attempt to
4362 // create a temporary through the use of a copy constructor.
4363 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4364 (T1->isRecordType() || T2->isRecordType()))
4365 return ICS;
4366
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004367 // If T1 is reference-related to T2 and the reference is an rvalue
4368 // reference, the initializer expression shall not be an lvalue.
4369 if (RefRelationship >= Sema::Ref_Related &&
4370 isRValRef && Init->Classify(S.Context).isLValue())
4371 return ICS;
4372
Douglas Gregorabe183d2010-04-13 16:31:36 +00004373 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004374 // When a parameter of reference type is not bound directly to
4375 // an argument expression, the conversion sequence is the one
4376 // required to convert the argument expression to the
4377 // underlying type of the reference according to
4378 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4379 // to copy-initializing a temporary of the underlying type with
4380 // the argument expression. Any difference in top-level
4381 // cv-qualification is subsumed by the initialization itself
4382 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004383 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4384 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004385 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004386 /*CStyle=*/false,
4387 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004388
4389 // Of course, that's still a reference binding.
4390 if (ICS.isStandard()) {
4391 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004392 ICS.Standard.IsLvalueReference = !isRValRef;
4393 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4394 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004395 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004396 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004397 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004398 // Don't allow rvalue references to bind to lvalues.
4399 if (DeclType->isRValueReferenceType()) {
4400 if (const ReferenceType *RefType
4401 = ICS.UserDefined.ConversionFunction->getResultType()
4402 ->getAs<LValueReferenceType>()) {
4403 if (!RefType->getPointeeType()->isFunctionType()) {
4404 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4405 DeclType);
4406 return ICS;
4407 }
4408 }
4409 }
4410
Douglas Gregorabe183d2010-04-13 16:31:36 +00004411 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004412 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4413 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4414 ICS.UserDefined.After.BindsToRvalue = true;
4415 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4416 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004417 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004418
Douglas Gregorabe183d2010-04-13 16:31:36 +00004419 return ICS;
4420}
4421
Sebastian Redl5405b812011-10-16 18:19:34 +00004422static ImplicitConversionSequence
4423TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4424 bool SuppressUserConversions,
4425 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004426 bool AllowObjCWritebackConversion,
4427 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004428
4429/// TryListConversion - Try to copy-initialize a value of type ToType from the
4430/// initializer list From.
4431static ImplicitConversionSequence
4432TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4433 bool SuppressUserConversions,
4434 bool InOverloadResolution,
4435 bool AllowObjCWritebackConversion) {
4436 // C++11 [over.ics.list]p1:
4437 // When an argument is an initializer list, it is not an expression and
4438 // special rules apply for converting it to a parameter type.
4439
4440 ImplicitConversionSequence Result;
4441 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004442 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004443
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004444 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004445 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004446 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004447 return Result;
4448
Sebastian Redl5405b812011-10-16 18:19:34 +00004449 // C++11 [over.ics.list]p2:
4450 // If the parameter type is std::initializer_list<X> or "array of X" and
4451 // all the elements can be implicitly converted to X, the implicit
4452 // conversion sequence is the worst conversion necessary to convert an
4453 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004454 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004455 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004456 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004457 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004458 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004459 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004460 if (!X.isNull()) {
4461 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4462 Expr *Init = From->getInit(i);
4463 ImplicitConversionSequence ICS =
4464 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4465 InOverloadResolution,
4466 AllowObjCWritebackConversion);
4467 // If a single element isn't convertible, fail.
4468 if (ICS.isBad()) {
4469 Result = ICS;
4470 break;
4471 }
4472 // Otherwise, look for the worst conversion.
4473 if (Result.isBad() ||
4474 CompareImplicitConversionSequences(S, ICS, Result) ==
4475 ImplicitConversionSequence::Worse)
4476 Result = ICS;
4477 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004478
4479 // For an empty list, we won't have computed any conversion sequence.
4480 // Introduce the identity conversion sequence.
4481 if (From->getNumInits() == 0) {
4482 Result.setStandard();
4483 Result.Standard.setAsIdentityConversion();
4484 Result.Standard.setFromType(ToType);
4485 Result.Standard.setAllToTypes(ToType);
4486 }
4487
Sebastian Redlfe592282012-01-17 22:49:48 +00004488 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004489 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004490 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004491 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004492
4493 // C++11 [over.ics.list]p3:
4494 // Otherwise, if the parameter is a non-aggregate class X and overload
4495 // resolution chooses a single best constructor [...] the implicit
4496 // conversion sequence is a user-defined conversion sequence. If multiple
4497 // constructors are viable but none is better than the others, the
4498 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004499 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4500 // This function can deal with initializer lists.
4501 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4502 /*AllowExplicit=*/false,
4503 InOverloadResolution, /*CStyle=*/false,
4504 AllowObjCWritebackConversion);
4505 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004506 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004507 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004508
4509 // C++11 [over.ics.list]p4:
4510 // Otherwise, if the parameter has an aggregate type which can be
4511 // initialized from the initializer list [...] the implicit conversion
4512 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004513 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004514 // Type is an aggregate, argument is an init list. At this point it comes
4515 // down to checking whether the initialization works.
4516 // FIXME: Find out whether this parameter is consumed or not.
4517 InitializedEntity Entity =
4518 InitializedEntity::InitializeParameter(S.Context, ToType,
4519 /*Consumed=*/false);
4520 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4521 Result.setUserDefined();
4522 Result.UserDefined.Before.setAsIdentityConversion();
4523 // Initializer lists don't have a type.
4524 Result.UserDefined.Before.setFromType(QualType());
4525 Result.UserDefined.Before.setAllToTypes(QualType());
4526
4527 Result.UserDefined.After.setAsIdentityConversion();
4528 Result.UserDefined.After.setFromType(ToType);
4529 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004530 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004531 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004532 return Result;
4533 }
4534
4535 // C++11 [over.ics.list]p5:
4536 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004537 if (ToType->isReferenceType()) {
4538 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4539 // mention initializer lists in any way. So we go by what list-
4540 // initialization would do and try to extrapolate from that.
4541
4542 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4543
4544 // If the initializer list has a single element that is reference-related
4545 // to the parameter type, we initialize the reference from that.
4546 if (From->getNumInits() == 1) {
4547 Expr *Init = From->getInit(0);
4548
4549 QualType T2 = Init->getType();
4550
4551 // If the initializer is the address of an overloaded function, try
4552 // to resolve the overloaded function. If all goes well, T2 is the
4553 // type of the resulting function.
4554 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4555 DeclAccessPair Found;
4556 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4557 Init, ToType, false, Found))
4558 T2 = Fn->getType();
4559 }
4560
4561 // Compute some basic properties of the types and the initializer.
4562 bool dummy1 = false;
4563 bool dummy2 = false;
4564 bool dummy3 = false;
4565 Sema::ReferenceCompareResult RefRelationship
4566 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4567 dummy2, dummy3);
4568
4569 if (RefRelationship >= Sema::Ref_Related)
4570 return TryReferenceInit(S, Init, ToType,
4571 /*FIXME:*/From->getLocStart(),
4572 SuppressUserConversions,
4573 /*AllowExplicit=*/false);
4574 }
4575
4576 // Otherwise, we bind the reference to a temporary created from the
4577 // initializer list.
4578 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4579 InOverloadResolution,
4580 AllowObjCWritebackConversion);
4581 if (Result.isFailure())
4582 return Result;
4583 assert(!Result.isEllipsis() &&
4584 "Sub-initialization cannot result in ellipsis conversion.");
4585
4586 // Can we even bind to a temporary?
4587 if (ToType->isRValueReferenceType() ||
4588 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4589 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4590 Result.UserDefined.After;
4591 SCS.ReferenceBinding = true;
4592 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4593 SCS.BindsToRvalue = true;
4594 SCS.BindsToFunctionLvalue = false;
4595 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4596 SCS.ObjCLifetimeConversionBinding = false;
4597 } else
4598 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4599 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004600 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004601 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004602
4603 // C++11 [over.ics.list]p6:
4604 // Otherwise, if the parameter type is not a class:
4605 if (!ToType->isRecordType()) {
4606 // - if the initializer list has one element, the implicit conversion
4607 // sequence is the one required to convert the element to the
4608 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004609 unsigned NumInits = From->getNumInits();
4610 if (NumInits == 1)
4611 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4612 SuppressUserConversions,
4613 InOverloadResolution,
4614 AllowObjCWritebackConversion);
4615 // - if the initializer list has no elements, the implicit conversion
4616 // sequence is the identity conversion.
4617 else if (NumInits == 0) {
4618 Result.setStandard();
4619 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004620 Result.Standard.setFromType(ToType);
4621 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004622 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004623 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004624 return Result;
4625 }
4626
4627 // C++11 [over.ics.list]p7:
4628 // In all cases other than those enumerated above, no conversion is possible
4629 return Result;
4630}
4631
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004632/// TryCopyInitialization - Try to copy-initialize a value of type
4633/// ToType from the expression From. Return the implicit conversion
4634/// sequence required to pass this argument, which may be a bad
4635/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004636/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004637/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004638static ImplicitConversionSequence
4639TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004641 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004642 bool AllowObjCWritebackConversion,
4643 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004644 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4645 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4646 InOverloadResolution,AllowObjCWritebackConversion);
4647
Douglas Gregorabe183d2010-04-13 16:31:36 +00004648 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004649 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004650 /*FIXME:*/From->getLocStart(),
4651 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004652 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004653
John McCall120d63c2010-08-24 20:38:10 +00004654 return TryImplicitConversion(S, From, ToType,
4655 SuppressUserConversions,
4656 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004657 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004658 /*CStyle=*/false,
4659 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004660}
4661
Anna Zaksf3546ee2011-07-28 19:46:48 +00004662static bool TryCopyInitialization(const CanQualType FromQTy,
4663 const CanQualType ToQTy,
4664 Sema &S,
4665 SourceLocation Loc,
4666 ExprValueKind FromVK) {
4667 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4668 ImplicitConversionSequence ICS =
4669 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4670
4671 return !ICS.isBad();
4672}
4673
Douglas Gregor96176b32008-11-18 23:14:02 +00004674/// TryObjectArgumentInitialization - Try to initialize the object
4675/// parameter of the given member function (@c Method) from the
4676/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004677static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004678TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004679 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004680 CXXMethodDecl *Method,
4681 CXXRecordDecl *ActingContext) {
4682 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004683 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4684 // const volatile object.
4685 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4686 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004687 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004688
4689 // Set up the conversion sequence as a "bad" conversion, to allow us
4690 // to exit early.
4691 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004692
4693 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004694 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004695 FromType = PT->getPointeeType();
4696
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004697 // When we had a pointer, it's implicitly dereferenced, so we
4698 // better have an lvalue.
4699 assert(FromClassification.isLValue());
4700 }
4701
Anders Carlssona552f7c2009-05-01 18:34:30 +00004702 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004703
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004704 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004705 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004706 // parameter is
4707 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004708 // - "lvalue reference to cv X" for functions declared without a
4709 // ref-qualifier or with the & ref-qualifier
4710 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004711 // ref-qualifier
4712 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004713 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004714 // cv-qualification on the member function declaration.
4715 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004716 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004717 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004718 // (C++ [over.match.funcs]p5). We perform a simplified version of
4719 // reference binding here, that allows class rvalues to bind to
4720 // non-constant references.
4721
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004722 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004723 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004724 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004725 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004726 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004727 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004728 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004729 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004730 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004731
4732 // Check that we have either the same type or a derived type. It
4733 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004734 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004735 ImplicitConversionKind SecondKind;
4736 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4737 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004738 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004739 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004740 else {
John McCallb1bdc622010-02-25 01:37:24 +00004741 ICS.setBad(BadConversionSequence::unrelated_class,
4742 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004743 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004744 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004745
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004746 // Check the ref-qualifier.
4747 switch (Method->getRefQualifier()) {
4748 case RQ_None:
4749 // Do nothing; we don't care about lvalueness or rvalueness.
4750 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004751
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004752 case RQ_LValue:
4753 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4754 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004755 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004756 ImplicitParamType);
4757 return ICS;
4758 }
4759 break;
4760
4761 case RQ_RValue:
4762 if (!FromClassification.isRValue()) {
4763 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004764 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004765 ImplicitParamType);
4766 return ICS;
4767 }
4768 break;
4769 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004770
Douglas Gregor96176b32008-11-18 23:14:02 +00004771 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004772 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004773 ICS.Standard.setAsIdentityConversion();
4774 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004775 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004776 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004777 ICS.Standard.ReferenceBinding = true;
4778 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004779 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004780 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004781 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4782 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4783 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004784 return ICS;
4785}
4786
4787/// PerformObjectArgumentInitialization - Perform initialization of
4788/// the implicit object parameter for the given Method with the given
4789/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004790ExprResult
4791Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004792 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004793 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004794 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004795 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004796 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004797 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004799 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004800 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004801 FromRecordType = PT->getPointeeType();
4802 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004803 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004804 } else {
4805 FromRecordType = From->getType();
4806 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004807 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004808 }
4809
John McCall701c89e2009-12-03 04:06:58 +00004810 // Note that we always use the true parent context when performing
4811 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004812 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004813 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4814 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004815 if (ICS.isBad()) {
4816 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4817 Qualifiers FromQs = FromRecordType.getQualifiers();
4818 Qualifiers ToQs = DestType.getQualifiers();
4819 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4820 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004821 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004822 diag::err_member_function_call_bad_cvr)
4823 << Method->getDeclName() << FromRecordType << (CVR - 1)
4824 << From->getSourceRange();
4825 Diag(Method->getLocation(), diag::note_previous_decl)
4826 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004827 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004828 }
4829 }
4830
Daniel Dunbar96a00142012-03-09 18:35:03 +00004831 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004832 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004833 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004834 }
Mike Stump1eb44332009-09-09 15:08:12 +00004835
John Wiegley429bb272011-04-08 18:41:53 +00004836 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4837 ExprResult FromRes =
4838 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4839 if (FromRes.isInvalid())
4840 return ExprError();
4841 From = FromRes.take();
4842 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004843
Douglas Gregor5fccd362010-03-03 23:55:11 +00004844 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004845 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004846 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004847 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004848}
4849
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004850/// TryContextuallyConvertToBool - Attempt to contextually convert the
4851/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004852static ImplicitConversionSequence
4853TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004854 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004855 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004856 // FIXME: Are these flags correct?
4857 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004858 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004859 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004860 /*CStyle=*/false,
4861 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004862}
4863
4864/// PerformContextuallyConvertToBool - Perform a contextual conversion
4865/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004866ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004867 if (checkPlaceholderForOverload(*this, From))
4868 return ExprError();
4869
John McCall120d63c2010-08-24 20:38:10 +00004870 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004871 if (!ICS.isBad())
4872 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004873
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004874 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004875 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004876 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004877 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004878 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004879}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004880
Richard Smith8ef7b202012-01-18 23:55:52 +00004881/// Check that the specified conversion is permitted in a converted constant
4882/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4883/// is acceptable.
4884static bool CheckConvertedConstantConversions(Sema &S,
4885 StandardConversionSequence &SCS) {
4886 // Since we know that the target type is an integral or unscoped enumeration
4887 // type, most conversion kinds are impossible. All possible First and Third
4888 // conversions are fine.
4889 switch (SCS.Second) {
4890 case ICK_Identity:
4891 case ICK_Integral_Promotion:
4892 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004893 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004894 return true;
4895
4896 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004897 // Conversion from an integral or unscoped enumeration type to bool is
4898 // classified as ICK_Boolean_Conversion, but it's also an integral
4899 // conversion, so it's permitted in a converted constant expression.
4900 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4901 SCS.getToType(2)->isBooleanType();
4902
Richard Smith8ef7b202012-01-18 23:55:52 +00004903 case ICK_Floating_Integral:
4904 case ICK_Complex_Real:
4905 return false;
4906
4907 case ICK_Lvalue_To_Rvalue:
4908 case ICK_Array_To_Pointer:
4909 case ICK_Function_To_Pointer:
4910 case ICK_NoReturn_Adjustment:
4911 case ICK_Qualification:
4912 case ICK_Compatible_Conversion:
4913 case ICK_Vector_Conversion:
4914 case ICK_Vector_Splat:
4915 case ICK_Derived_To_Base:
4916 case ICK_Pointer_Conversion:
4917 case ICK_Pointer_Member:
4918 case ICK_Block_Pointer_Conversion:
4919 case ICK_Writeback_Conversion:
4920 case ICK_Floating_Promotion:
4921 case ICK_Complex_Promotion:
4922 case ICK_Complex_Conversion:
4923 case ICK_Floating_Conversion:
4924 case ICK_TransparentUnionConversion:
4925 llvm_unreachable("unexpected second conversion kind");
4926
4927 case ICK_Num_Conversion_Kinds:
4928 break;
4929 }
4930
4931 llvm_unreachable("unknown conversion kind");
4932}
4933
4934/// CheckConvertedConstantExpression - Check that the expression From is a
4935/// converted constant expression of type T, perform the conversion and produce
4936/// the converted expression, per C++11 [expr.const]p3.
4937ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4938 llvm::APSInt &Value,
4939 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004940 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004941 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4942
4943 if (checkPlaceholderForOverload(*this, From))
4944 return ExprError();
4945
4946 // C++11 [expr.const]p3 with proposed wording fixes:
4947 // A converted constant expression of type T is a core constant expression,
4948 // implicitly converted to a prvalue of type T, where the converted
4949 // expression is a literal constant expression and the implicit conversion
4950 // sequence contains only user-defined conversions, lvalue-to-rvalue
4951 // conversions, integral promotions, and integral conversions other than
4952 // narrowing conversions.
4953 ImplicitConversionSequence ICS =
4954 TryImplicitConversion(From, T,
4955 /*SuppressUserConversions=*/false,
4956 /*AllowExplicit=*/false,
4957 /*InOverloadResolution=*/false,
4958 /*CStyle=*/false,
4959 /*AllowObjcWritebackConversion=*/false);
4960 StandardConversionSequence *SCS = 0;
4961 switch (ICS.getKind()) {
4962 case ImplicitConversionSequence::StandardConversion:
4963 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004964 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004965 diag::err_typecheck_converted_constant_expression_disallowed)
4966 << From->getType() << From->getSourceRange() << T;
4967 SCS = &ICS.Standard;
4968 break;
4969 case ImplicitConversionSequence::UserDefinedConversion:
4970 // We are converting from class type to an integral or enumeration type, so
4971 // the Before sequence must be trivial.
4972 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004973 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004974 diag::err_typecheck_converted_constant_expression_disallowed)
4975 << From->getType() << From->getSourceRange() << T;
4976 SCS = &ICS.UserDefined.After;
4977 break;
4978 case ImplicitConversionSequence::AmbiguousConversion:
4979 case ImplicitConversionSequence::BadConversion:
4980 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004981 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004982 diag::err_typecheck_converted_constant_expression)
4983 << From->getType() << From->getSourceRange() << T;
4984 return ExprError();
4985
4986 case ImplicitConversionSequence::EllipsisConversion:
4987 llvm_unreachable("ellipsis conversion in converted constant expression");
4988 }
4989
4990 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4991 if (Result.isInvalid())
4992 return Result;
4993
4994 // Check for a narrowing implicit conversion.
4995 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004996 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004997 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4998 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004999 case NK_Variable_Narrowing:
5000 // Implicit conversion to a narrower type, and the value is not a constant
5001 // expression. We'll diagnose this in a moment.
5002 case NK_Not_Narrowing:
5003 break;
5004
5005 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005006 Diag(From->getLocStart(),
5007 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5008 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005009 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00005010 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005011 break;
5012
5013 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005014 Diag(From->getLocStart(),
5015 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5016 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005017 << CCE << /*Constant*/0 << From->getType() << T;
5018 break;
5019 }
5020
5021 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005022 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005023 Expr::EvalResult Eval;
5024 Eval.Diag = &Notes;
5025
5026 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5027 // The expression can't be folded, so we can't keep it at this position in
5028 // the AST.
5029 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005030 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005031 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005032
5033 if (Notes.empty()) {
5034 // It's a constant expression.
5035 return Result;
5036 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005037 }
5038
5039 // It's not a constant expression. Produce an appropriate diagnostic.
5040 if (Notes.size() == 1 &&
5041 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5042 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5043 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005044 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005045 << CCE << From->getSourceRange();
5046 for (unsigned I = 0; I < Notes.size(); ++I)
5047 Diag(Notes[I].first, Notes[I].second);
5048 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005049 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005050}
5051
John McCall0bcc9bc2011-09-09 06:11:02 +00005052/// dropPointerConversions - If the given standard conversion sequence
5053/// involves any pointer conversions, remove them. This may change
5054/// the result type of the conversion sequence.
5055static void dropPointerConversion(StandardConversionSequence &SCS) {
5056 if (SCS.Second == ICK_Pointer_Conversion) {
5057 SCS.Second = ICK_Identity;
5058 SCS.Third = ICK_Identity;
5059 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5060 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005061}
John McCall120d63c2010-08-24 20:38:10 +00005062
John McCall0bcc9bc2011-09-09 06:11:02 +00005063/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5064/// convert the expression From to an Objective-C pointer type.
5065static ImplicitConversionSequence
5066TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5067 // Do an implicit conversion to 'id'.
5068 QualType Ty = S.Context.getObjCIdType();
5069 ImplicitConversionSequence ICS
5070 = TryImplicitConversion(S, From, Ty,
5071 // FIXME: Are these flags correct?
5072 /*SuppressUserConversions=*/false,
5073 /*AllowExplicit=*/true,
5074 /*InOverloadResolution=*/false,
5075 /*CStyle=*/false,
5076 /*AllowObjCWritebackConversion=*/false);
5077
5078 // Strip off any final conversions to 'id'.
5079 switch (ICS.getKind()) {
5080 case ImplicitConversionSequence::BadConversion:
5081 case ImplicitConversionSequence::AmbiguousConversion:
5082 case ImplicitConversionSequence::EllipsisConversion:
5083 break;
5084
5085 case ImplicitConversionSequence::UserDefinedConversion:
5086 dropPointerConversion(ICS.UserDefined.After);
5087 break;
5088
5089 case ImplicitConversionSequence::StandardConversion:
5090 dropPointerConversion(ICS.Standard);
5091 break;
5092 }
5093
5094 return ICS;
5095}
5096
5097/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5098/// conversion of the expression From to an Objective-C pointer type.
5099ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005100 if (checkPlaceholderForOverload(*this, From))
5101 return ExprError();
5102
John McCallc12c5bb2010-05-15 11:32:37 +00005103 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005104 ImplicitConversionSequence ICS =
5105 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005106 if (!ICS.isBad())
5107 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005108 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005109}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005110
Richard Smithf39aec12012-02-04 07:07:42 +00005111/// Determine whether the provided type is an integral type, or an enumeration
5112/// type of a permitted flavor.
5113static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5114 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5115 : T->isIntegralOrUnscopedEnumerationType();
5116}
5117
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005119/// enumeration type.
5120///
5121/// This routine will attempt to convert an expression of class type to an
5122/// integral or enumeration type, if that class type only has a single
5123/// conversion to an integral or enumeration type.
5124///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005125/// \param Loc The source location of the construct that requires the
5126/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005127///
James Dennett40ae6662012-06-22 08:52:37 +00005128/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005129///
James Dennett40ae6662012-06-22 08:52:37 +00005130/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005131///
Richard Smithf39aec12012-02-04 07:07:42 +00005132/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5133/// enumerations should be considered.
5134///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005135/// \returns The expression, converted to an integral or enumeration type if
5136/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005138Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005139 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005140 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005141 // We can't perform any more checking for type-dependent expressions.
5142 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005143 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005144
Eli Friedmanceccab92012-01-26 00:26:18 +00005145 // Process placeholders immediately.
5146 if (From->hasPlaceholderType()) {
5147 ExprResult result = CheckPlaceholderExpr(From);
5148 if (result.isInvalid()) return result;
5149 From = result.take();
5150 }
5151
Douglas Gregorc30614b2010-06-29 23:17:37 +00005152 // If the expression already has integral or enumeration type, we're golden.
5153 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005154 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005155 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005156
5157 // FIXME: Check for missing '()' if T is a function type?
5158
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005159 // 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 +00005160 // expression of integral or enumeration type.
5161 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005162 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005163 if (!Diagnoser.Suppress)
5164 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005165 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005167
Douglas Gregorc30614b2010-06-29 23:17:37 +00005168 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005169 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005170 ICEConvertDiagnoser &Diagnoser;
5171 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005172
Douglas Gregorab41fe92012-05-04 22:38:52 +00005173 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5174 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005175
5176 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005177 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005178 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005179 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005180
5181 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005182 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005183
Douglas Gregorc30614b2010-06-29 23:17:37 +00005184 // Look for a conversion to an integral or enumeration type.
5185 UnresolvedSet<4> ViableConversions;
5186 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005187 std::pair<CXXRecordDecl::conversion_iterator,
5188 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005189 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005190
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005191 bool HadMultipleCandidates
5192 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005193
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005194 for (CXXRecordDecl::conversion_iterator
5195 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005196 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005197 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5198 if (isIntegralOrEnumerationType(
5199 Conversion->getConversionType().getNonReferenceType(),
5200 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005201 if (Conversion->isExplicit())
5202 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5203 else
5204 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5205 }
Richard Smithf39aec12012-02-04 07:07:42 +00005206 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005207 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005208
Douglas Gregorc30614b2010-06-29 23:17:37 +00005209 switch (ViableConversions.size()) {
5210 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005211 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005212 DeclAccessPair Found = ExplicitConversions[0];
5213 CXXConversionDecl *Conversion
5214 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005215
Douglas Gregorc30614b2010-06-29 23:17:37 +00005216 // The user probably meant to invoke the given explicit
5217 // conversion; use it.
5218 QualType ConvTy
5219 = Conversion->getConversionType().getNonReferenceType();
5220 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005221 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005222
Douglas Gregorab41fe92012-05-04 22:38:52 +00005223 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005224 << FixItHint::CreateInsertion(From->getLocStart(),
5225 "static_cast<" + TypeStr + ">(")
5226 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5227 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005228 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005229
5230 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005231 // explicit conversion function.
5232 if (isSFINAEContext())
5233 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005234
Douglas Gregorc30614b2010-06-29 23:17:37 +00005235 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005236 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5237 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005238 if (Result.isInvalid())
5239 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005240 // Record usage of conversion in an implicit cast.
5241 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5242 CK_UserDefinedConversion,
5243 Result.get(), 0,
5244 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005246
Douglas Gregorc30614b2010-06-29 23:17:37 +00005247 // We'll complain below about a non-integral condition type.
5248 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005249
Douglas Gregorc30614b2010-06-29 23:17:37 +00005250 case 1: {
5251 // Apply this conversion.
5252 DeclAccessPair Found = ViableConversions[0];
5253 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005254
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005255 CXXConversionDecl *Conversion
5256 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5257 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005259 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005260 if (isSFINAEContext())
5261 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262
Douglas Gregorab41fe92012-05-04 22:38:52 +00005263 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5264 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005265 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005267 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5268 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005269 if (Result.isInvalid())
5270 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005271 // Record usage of conversion in an implicit cast.
5272 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5273 CK_UserDefinedConversion,
5274 Result.get(), 0,
5275 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005276 break;
5277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005278
Douglas Gregorc30614b2010-06-29 23:17:37 +00005279 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005280 if (Diagnoser.Suppress)
5281 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005282
Douglas Gregorab41fe92012-05-04 22:38:52 +00005283 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005284 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5285 CXXConversionDecl *Conv
5286 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5287 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005288 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005289 }
John McCall9ae2f072010-08-23 23:25:46 +00005290 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005292
Richard Smith282e7e62012-02-04 09:53:13 +00005293 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005294 !Diagnoser.Suppress) {
5295 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5296 << From->getSourceRange();
5297 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005298
Eli Friedmanceccab92012-01-26 00:26:18 +00005299 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005300}
5301
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005302/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005303/// candidate functions, using the given function call arguments. If
5304/// @p SuppressUserConversions, then don't allow user-defined
5305/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005306///
James Dennett699c9042012-06-15 07:13:21 +00005307/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005308/// based on an incomplete set of function arguments. This feature is used by
5309/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005310void
5311Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005312 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005313 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005314 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005315 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005316 bool PartialOverloading,
5317 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005318 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005319 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005320 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005321 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005322 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005323
Douglas Gregor88a35142008-12-22 05:46:06 +00005324 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005325 if (!isa<CXXConstructorDecl>(Method)) {
5326 // If we get here, it's because we're calling a member function
5327 // that is named without a member access expression (e.g.,
5328 // "this->f") that was either written explicitly or created
5329 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005330 // function, e.g., X::f(). We use an empty type for the implied
5331 // object argument (C++ [over.call.func]p3), and the acting context
5332 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005333 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005334 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005335 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005336 return;
5337 }
5338 // We treat a constructor like a non-member function, since its object
5339 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005340 }
5341
Douglas Gregorfd476482009-11-13 23:59:09 +00005342 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005343 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005344
Douglas Gregor7edfb692009-11-23 12:27:39 +00005345 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005346 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005347
Douglas Gregor66724ea2009-11-14 01:20:54 +00005348 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5349 // C++ [class.copy]p3:
5350 // A member function template is never instantiated to perform the copy
5351 // of a class object to an object of its class type.
5352 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005353 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005354 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005355 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5356 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005357 return;
5358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005359
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005360 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005361 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005362 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005363 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005364 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005365 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005366 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005367 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005368
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005369 unsigned NumArgsInProto = Proto->getNumArgs();
5370
5371 // (C++ 13.3.2p2): A candidate function having fewer than m
5372 // parameters is viable only if it has an ellipsis in its parameter
5373 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005374 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005375 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005376 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005377 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005378 return;
5379 }
5380
5381 // (C++ 13.3.2p2): A candidate function having more than m parameters
5382 // is viable only if the (m+1)st parameter has a default argument
5383 // (8.3.6). For the purposes of overload resolution, the
5384 // parameter list is truncated on the right, so that there are
5385 // exactly m parameters.
5386 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005387 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005388 // Not enough arguments.
5389 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005390 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005391 return;
5392 }
5393
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005394 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005395 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005396 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5397 if (CheckCUDATarget(Caller, Function)) {
5398 Candidate.Viable = false;
5399 Candidate.FailureKind = ovl_fail_bad_target;
5400 return;
5401 }
5402
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005403 // Determine the implicit conversion sequences for each of the
5404 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005405 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005406 if (ArgIdx < NumArgsInProto) {
5407 // (C++ 13.3.2p3): for F to be a viable function, there shall
5408 // exist for each argument an implicit conversion sequence
5409 // (13.3.3.1) that converts that argument to the corresponding
5410 // parameter of F.
5411 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005412 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005413 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005414 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005415 /*InOverloadResolution=*/true,
5416 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005417 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005418 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005419 if (Candidate.Conversions[ArgIdx].isBad()) {
5420 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005421 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005422 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005423 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005424 } else {
5425 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5426 // argument for which there is no corresponding parameter is
5427 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005428 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005429 }
5430 }
5431}
5432
Douglas Gregor063daf62009-03-13 18:40:31 +00005433/// \brief Add all of the function declarations in the given function set to
5434/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005435void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005436 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005437 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005438 bool SuppressUserConversions,
5439 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005440 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005441 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5442 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005443 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005444 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005445 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005446 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005447 Args.slice(1), CandidateSet,
5448 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005449 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005450 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005451 SuppressUserConversions);
5452 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005453 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005454 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5455 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005456 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005457 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005458 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005459 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005460 Args[0]->Classify(Context), Args.slice(1),
5461 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005462 else
John McCall9aa472c2010-03-19 07:35:19 +00005463 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005464 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005465 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005466 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005467 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005468}
5469
John McCall314be4e2009-11-17 07:50:12 +00005470/// AddMethodCandidate - Adds a named decl (which is some kind of
5471/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005472void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005473 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005474 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005475 Expr **Args, unsigned NumArgs,
5476 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005477 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005478 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005479 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005480
5481 if (isa<UsingShadowDecl>(Decl))
5482 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005483
John McCall314be4e2009-11-17 07:50:12 +00005484 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5485 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5486 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005487 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5488 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005489 ObjectType, ObjectClassification,
5490 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005491 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005492 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005493 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005494 ObjectType, ObjectClassification,
5495 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005496 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005497 }
5498}
5499
Douglas Gregor96176b32008-11-18 23:14:02 +00005500/// AddMethodCandidate - Adds the given C++ member function to the set
5501/// of candidate functions, using the given function call arguments
5502/// and the object argument (@c Object). For example, in a call
5503/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5504/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5505/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005506/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005507void
John McCall9aa472c2010-03-19 07:35:19 +00005508Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005509 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005510 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005511 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005512 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005513 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005514 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005515 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005516 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005517 assert(!isa<CXXConstructorDecl>(Method) &&
5518 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005519
Douglas Gregor3f396022009-09-28 04:47:19 +00005520 if (!CandidateSet.isNewCandidate(Method))
5521 return;
5522
Douglas Gregor7edfb692009-11-23 12:27:39 +00005523 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005524 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005525
Douglas Gregor96176b32008-11-18 23:14:02 +00005526 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005527 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005528 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005529 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005530 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005531 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005532 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005533
5534 unsigned NumArgsInProto = Proto->getNumArgs();
5535
5536 // (C++ 13.3.2p2): A candidate function having fewer than m
5537 // parameters is viable only if it has an ellipsis in its parameter
5538 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005539 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005540 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005541 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005542 return;
5543 }
5544
5545 // (C++ 13.3.2p2): A candidate function having more than m parameters
5546 // is viable only if the (m+1)st parameter has a default argument
5547 // (8.3.6). For the purposes of overload resolution, the
5548 // parameter list is truncated on the right, so that there are
5549 // exactly m parameters.
5550 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005551 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005552 // Not enough arguments.
5553 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005554 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005555 return;
5556 }
5557
5558 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005559
John McCall701c89e2009-12-03 04:06:58 +00005560 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005561 // The implicit object argument is ignored.
5562 Candidate.IgnoreObjectArgument = true;
5563 else {
5564 // Determine the implicit conversion sequence for the object
5565 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005566 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005567 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5568 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005569 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005570 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005571 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005572 return;
5573 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005574 }
5575
5576 // Determine the implicit conversion sequences for each of the
5577 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005578 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005579 if (ArgIdx < NumArgsInProto) {
5580 // (C++ 13.3.2p3): for F to be a viable function, there shall
5581 // exist for each argument an implicit conversion sequence
5582 // (13.3.3.1) that converts that argument to the corresponding
5583 // parameter of F.
5584 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005585 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005586 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005587 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005588 /*InOverloadResolution=*/true,
5589 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005590 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005591 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005592 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005593 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005594 break;
5595 }
5596 } else {
5597 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5598 // argument for which there is no corresponding parameter is
5599 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005600 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005601 }
5602 }
5603}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005604
Douglas Gregor6b906862009-08-21 00:16:32 +00005605/// \brief Add a C++ member function template as a candidate to the candidate
5606/// set, using template argument deduction to produce an appropriate member
5607/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005608void
Douglas Gregor6b906862009-08-21 00:16:32 +00005609Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005610 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005611 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005612 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005613 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005614 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005615 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005616 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005617 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005618 if (!CandidateSet.isNewCandidate(MethodTmpl))
5619 return;
5620
Douglas Gregor6b906862009-08-21 00:16:32 +00005621 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005622 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005623 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005624 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005625 // candidate functions in the usual way.113) A given name can refer to one
5626 // or more function templates and also to a set of overloaded non-template
5627 // functions. In such a case, the candidate functions generated from each
5628 // function template are combined with the set of non-template candidate
5629 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005630 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005631 FunctionDecl *Specialization = 0;
5632 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005633 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5634 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005635 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005636 Candidate.FoundDecl = FoundDecl;
5637 Candidate.Function = MethodTmpl->getTemplatedDecl();
5638 Candidate.Viable = false;
5639 Candidate.FailureKind = ovl_fail_bad_deduction;
5640 Candidate.IsSurrogate = false;
5641 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005642 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005643 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005644 Info);
5645 return;
5646 }
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Douglas Gregor6b906862009-08-21 00:16:32 +00005648 // Add the function template specialization produced by template argument
5649 // deduction as a candidate.
5650 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005651 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005652 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005653 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005654 ActingContext, ObjectType, ObjectClassification, Args,
5655 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005656}
5657
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005658/// \brief Add a C++ function template specialization as a candidate
5659/// in the candidate set, using template argument deduction to produce
5660/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005661void
Douglas Gregore53060f2009-06-25 22:08:12 +00005662Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005663 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005664 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005665 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005666 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005667 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005668 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5669 return;
5670
Douglas Gregore53060f2009-06-25 22:08:12 +00005671 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005672 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005673 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005674 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005675 // candidate functions in the usual way.113) A given name can refer to one
5676 // or more function templates and also to a set of overloaded non-template
5677 // functions. In such a case, the candidate functions generated from each
5678 // function template are combined with the set of non-template candidate
5679 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005680 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005681 FunctionDecl *Specialization = 0;
5682 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005683 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5684 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005685 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005686 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005687 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5688 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005689 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005690 Candidate.IsSurrogate = false;
5691 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005692 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005693 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005694 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005695 return;
5696 }
Mike Stump1eb44332009-09-09 15:08:12 +00005697
Douglas Gregore53060f2009-06-25 22:08:12 +00005698 // Add the function template specialization produced by template argument
5699 // deduction as a candidate.
5700 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005701 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005702 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005703}
Mike Stump1eb44332009-09-09 15:08:12 +00005704
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005705/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005706/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005707/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005708/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005709/// (which may or may not be the same type as the type that the
5710/// conversion function produces).
5711void
5712Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005713 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005714 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005715 Expr *From, QualType ToType,
5716 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005717 assert(!Conversion->getDescribedFunctionTemplate() &&
5718 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005719 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005720 if (!CandidateSet.isNewCandidate(Conversion))
5721 return;
5722
Douglas Gregor7edfb692009-11-23 12:27:39 +00005723 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005724 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005725
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005726 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005727 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005728 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005729 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005730 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005731 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005732 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005733 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005734 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005735 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005736 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005737
Douglas Gregorbca39322010-08-19 15:37:02 +00005738 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005739 // For conversion functions, the function is considered to be a member of
5740 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005741 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005742 //
5743 // Determine the implicit conversion sequence for the implicit
5744 // object parameter.
5745 QualType ImplicitParamType = From->getType();
5746 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5747 ImplicitParamType = FromPtrType->getPointeeType();
5748 CXXRecordDecl *ConversionContext
5749 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005750
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005751 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005752 = TryObjectArgumentInitialization(*this, From->getType(),
5753 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005754 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005755
John McCall1d318332010-01-12 00:44:57 +00005756 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005757 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005758 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005759 return;
5760 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005761
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005762 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005763 // derived to base as such conversions are given Conversion Rank. They only
5764 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5765 QualType FromCanon
5766 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5767 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5768 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5769 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005770 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005771 return;
5772 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005773
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005774 // To determine what the conversion from the result of calling the
5775 // conversion function to the type we're eventually trying to
5776 // convert to (ToType), we need to synthesize a call to the
5777 // conversion function and attempt copy initialization from it. This
5778 // makes sure that we get the right semantics with respect to
5779 // lvalues/rvalues and the type. Fortunately, we can allocate this
5780 // call on the stack and we don't need its arguments to be
5781 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005782 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005783 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005784 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5785 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005786 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005787 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005788
Richard Smith87c1f1f2011-07-13 22:53:21 +00005789 QualType ConversionType = Conversion->getConversionType();
5790 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005791 Candidate.Viable = false;
5792 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5793 return;
5794 }
5795
Richard Smith87c1f1f2011-07-13 22:53:21 +00005796 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005797
Mike Stump1eb44332009-09-09 15:08:12 +00005798 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005799 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5800 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005801 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005802 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005803 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005804 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005805 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005806 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005807 /*InOverloadResolution=*/false,
5808 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005809
John McCall1d318332010-01-12 00:44:57 +00005810 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005811 case ImplicitConversionSequence::StandardConversion:
5812 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005813
Douglas Gregorc520c842010-04-12 23:42:09 +00005814 // C++ [over.ics.user]p3:
5815 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005816 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005817 // shall have exact match rank.
5818 if (Conversion->getPrimaryTemplate() &&
5819 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5820 Candidate.Viable = false;
5821 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5822 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005823
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005824 // C++0x [dcl.init.ref]p5:
5825 // In the second case, if the reference is an rvalue reference and
5826 // the second standard conversion sequence of the user-defined
5827 // conversion sequence includes an lvalue-to-rvalue conversion, the
5828 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005829 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005830 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5831 Candidate.Viable = false;
5832 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5833 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005834 break;
5835
5836 case ImplicitConversionSequence::BadConversion:
5837 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005838 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005839 break;
5840
5841 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005842 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005843 "Can only end up with a standard conversion sequence or failure");
5844 }
5845}
5846
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005847/// \brief Adds a conversion function template specialization
5848/// candidate to the overload set, using template argument deduction
5849/// to deduce the template arguments of the conversion function
5850/// template from the type that we are converting to (C++
5851/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005852void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005853Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005854 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005855 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005856 Expr *From, QualType ToType,
5857 OverloadCandidateSet &CandidateSet) {
5858 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5859 "Only conversion function templates permitted here");
5860
Douglas Gregor3f396022009-09-28 04:47:19 +00005861 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5862 return;
5863
Craig Topper93e45992012-09-19 02:26:47 +00005864 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005865 CXXConversionDecl *Specialization = 0;
5866 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005867 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005868 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005869 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005870 Candidate.FoundDecl = FoundDecl;
5871 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5872 Candidate.Viable = false;
5873 Candidate.FailureKind = ovl_fail_bad_deduction;
5874 Candidate.IsSurrogate = false;
5875 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005876 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005877 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005878 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005879 return;
5880 }
Mike Stump1eb44332009-09-09 15:08:12 +00005881
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005882 // Add the conversion function template specialization produced by
5883 // template argument deduction as a candidate.
5884 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005885 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005886 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005887}
5888
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005889/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5890/// converts the given @c Object to a function pointer via the
5891/// conversion function @c Conversion, and then attempts to call it
5892/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5893/// the type of function that we'll eventually be calling.
5894void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005895 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005896 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005897 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005898 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005899 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005900 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005901 if (!CandidateSet.isNewCandidate(Conversion))
5902 return;
5903
Douglas Gregor7edfb692009-11-23 12:27:39 +00005904 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005905 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005906
Ahmed Charles13a140c2012-02-25 11:00:22 +00005907 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005908 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005909 Candidate.Function = 0;
5910 Candidate.Surrogate = Conversion;
5911 Candidate.Viable = true;
5912 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005913 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005914 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005915
5916 // Determine the implicit conversion sequence for the implicit
5917 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005918 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005919 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005920 Object->Classify(Context),
5921 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005922 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005923 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005924 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005925 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005926 return;
5927 }
5928
5929 // The first conversion is actually a user-defined conversion whose
5930 // first conversion is ObjectInit's standard conversion (which is
5931 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005932 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005933 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005934 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005935 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005936 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005937 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005938 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005939 = Candidate.Conversions[0].UserDefined.Before;
5940 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5941
Mike Stump1eb44332009-09-09 15:08:12 +00005942 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005943 unsigned NumArgsInProto = Proto->getNumArgs();
5944
5945 // (C++ 13.3.2p2): A candidate function having fewer than m
5946 // parameters is viable only if it has an ellipsis in its parameter
5947 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005948 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005949 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005950 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005951 return;
5952 }
5953
5954 // Function types don't have any default arguments, so just check if
5955 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005956 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005957 // Not enough arguments.
5958 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005959 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005960 return;
5961 }
5962
5963 // Determine the implicit conversion sequences for each of the
5964 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005965 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005966 if (ArgIdx < NumArgsInProto) {
5967 // (C++ 13.3.2p3): for F to be a viable function, there shall
5968 // exist for each argument an implicit conversion sequence
5969 // (13.3.3.1) that converts that argument to the corresponding
5970 // parameter of F.
5971 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005972 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005973 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005974 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005975 /*InOverloadResolution=*/false,
5976 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005977 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005978 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005979 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005980 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005981 break;
5982 }
5983 } else {
5984 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5985 // argument for which there is no corresponding parameter is
5986 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005987 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005988 }
5989 }
5990}
5991
Douglas Gregor063daf62009-03-13 18:40:31 +00005992/// \brief Add overload candidates for overloaded operators that are
5993/// member functions.
5994///
5995/// Add the overloaded operator candidates that are member functions
5996/// for the operator Op that was used in an operator expression such
5997/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5998/// CandidateSet will store the added overload candidates. (C++
5999/// [over.match.oper]).
6000void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6001 SourceLocation OpLoc,
6002 Expr **Args, unsigned NumArgs,
6003 OverloadCandidateSet& CandidateSet,
6004 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006005 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6006
6007 // C++ [over.match.oper]p3:
6008 // For a unary operator @ with an operand of a type whose
6009 // cv-unqualified version is T1, and for a binary operator @ with
6010 // a left operand of a type whose cv-unqualified version is T1 and
6011 // a right operand of a type whose cv-unqualified version is T2,
6012 // three sets of candidate functions, designated member
6013 // candidates, non-member candidates and built-in candidates, are
6014 // constructed as follows:
6015 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006016
6017 // -- If T1 is a class type, the set of member candidates is the
6018 // result of the qualified lookup of T1::operator@
6019 // (13.3.1.1.1); otherwise, the set of member candidates is
6020 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006021 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006022 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00006023 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006025
John McCalla24dc2e2009-11-17 02:14:36 +00006026 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6027 LookupQualifiedName(Operators, T1Rec->getDecl());
6028 Operators.suppressDiagnostics();
6029
Mike Stump1eb44332009-09-09 15:08:12 +00006030 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006031 OperEnd = Operators.end();
6032 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006033 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006034 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006035 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006036 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006037 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006038 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006039}
6040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006041/// AddBuiltinCandidate - Add a candidate for a built-in
6042/// operator. ResultTy and ParamTys are the result and parameter types
6043/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006044/// arguments being passed to the candidate. IsAssignmentOperator
6045/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006046/// operator. NumContextualBoolArguments is the number of arguments
6047/// (at the beginning of the argument list) that will be contextually
6048/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006049void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006050 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006051 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006052 bool IsAssignmentOperator,
6053 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006054 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006055 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006056
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006057 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006058 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006059 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006060 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006061 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006062 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006063 Candidate.BuiltinTypes.ResultTy = ResultTy;
6064 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6065 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6066
6067 // Determine the implicit conversion sequences for each of the
6068 // arguments.
6069 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006070 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006071 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006072 // C++ [over.match.oper]p4:
6073 // For the built-in assignment operators, conversions of the
6074 // left operand are restricted as follows:
6075 // -- no temporaries are introduced to hold the left operand, and
6076 // -- no user-defined conversions are applied to the left
6077 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006078 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006079 //
6080 // We block these conversions by turning off user-defined
6081 // conversions, since that is the only way that initialization of
6082 // a reference to a non-class type can occur from something that
6083 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006084 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006085 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006086 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006087 Candidate.Conversions[ArgIdx]
6088 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006089 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006090 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006091 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006092 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006093 /*InOverloadResolution=*/false,
6094 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006095 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006096 }
John McCall1d318332010-01-12 00:44:57 +00006097 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006098 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006099 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006100 break;
6101 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006102 }
6103}
6104
6105/// BuiltinCandidateTypeSet - A set of types that will be used for the
6106/// candidate operator functions for built-in operators (C++
6107/// [over.built]). The types are separated into pointer types and
6108/// enumeration types.
6109class BuiltinCandidateTypeSet {
6110 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006111 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006112
6113 /// PointerTypes - The set of pointer types that will be used in the
6114 /// built-in candidates.
6115 TypeSet PointerTypes;
6116
Sebastian Redl78eb8742009-04-19 21:53:20 +00006117 /// MemberPointerTypes - The set of member pointer types that will be
6118 /// used in the built-in candidates.
6119 TypeSet MemberPointerTypes;
6120
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006121 /// EnumerationTypes - The set of enumeration types that will be
6122 /// used in the built-in candidates.
6123 TypeSet EnumerationTypes;
6124
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006125 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006126 /// candidates.
6127 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006128
6129 /// \brief A flag indicating non-record types are viable candidates
6130 bool HasNonRecordTypes;
6131
6132 /// \brief A flag indicating whether either arithmetic or enumeration types
6133 /// were present in the candidate set.
6134 bool HasArithmeticOrEnumeralTypes;
6135
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006136 /// \brief A flag indicating whether the nullptr type was present in the
6137 /// candidate set.
6138 bool HasNullPtrType;
6139
Douglas Gregor5842ba92009-08-24 15:23:48 +00006140 /// Sema - The semantic analysis instance where we are building the
6141 /// candidate type set.
6142 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006143
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006144 /// Context - The AST context in which we will build the type sets.
6145 ASTContext &Context;
6146
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006147 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6148 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006149 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006150
6151public:
6152 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006153 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006154
Mike Stump1eb44332009-09-09 15:08:12 +00006155 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006156 : HasNonRecordTypes(false),
6157 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006158 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006159 SemaRef(SemaRef),
6160 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006161
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006162 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006163 SourceLocation Loc,
6164 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006165 bool AllowExplicitConversions,
6166 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006167
6168 /// pointer_begin - First pointer type found;
6169 iterator pointer_begin() { return PointerTypes.begin(); }
6170
Sebastian Redl78eb8742009-04-19 21:53:20 +00006171 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006172 iterator pointer_end() { return PointerTypes.end(); }
6173
Sebastian Redl78eb8742009-04-19 21:53:20 +00006174 /// member_pointer_begin - First member pointer type found;
6175 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6176
6177 /// member_pointer_end - Past the last member pointer type found;
6178 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6179
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006180 /// enumeration_begin - First enumeration type found;
6181 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6182
Sebastian Redl78eb8742009-04-19 21:53:20 +00006183 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006184 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006185
Douglas Gregor26bcf672010-05-19 03:21:00 +00006186 iterator vector_begin() { return VectorTypes.begin(); }
6187 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006188
6189 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6190 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006191 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006192};
6193
Sebastian Redl78eb8742009-04-19 21:53:20 +00006194/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006195/// the set of pointer types along with any more-qualified variants of
6196/// that type. For example, if @p Ty is "int const *", this routine
6197/// will add "int const *", "int const volatile *", "int const
6198/// restrict *", and "int const volatile restrict *" to the set of
6199/// pointer types. Returns true if the add of @p Ty itself succeeded,
6200/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006201///
6202/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006203bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006204BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6205 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006206
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006207 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006208 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006209 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006210
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006211 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006212 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006213 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006214 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006215 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6216 PointeeTy = PTy->getPointeeType();
6217 buildObjCPtr = true;
6218 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006219 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006220 }
6221
Sebastian Redla9efada2009-11-18 20:39:26 +00006222 // Don't add qualified variants of arrays. For one, they're not allowed
6223 // (the qualifier would sink to the element type), and for another, the
6224 // only overload situation where it matters is subscript or pointer +- int,
6225 // and those shouldn't have qualifier variants anyway.
6226 if (PointeeTy->isArrayType())
6227 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006228
John McCall0953e762009-09-24 19:53:00 +00006229 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006230 bool hasVolatile = VisibleQuals.hasVolatile();
6231 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006232
John McCall0953e762009-09-24 19:53:00 +00006233 // Iterate through all strict supersets of BaseCVR.
6234 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6235 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006236 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006237 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006238
6239 // Skip over restrict if no restrict found anywhere in the types, or if
6240 // the type cannot be restrict-qualified.
6241 if ((CVR & Qualifiers::Restrict) &&
6242 (!hasRestrict ||
6243 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6244 continue;
6245
6246 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006247 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006248
6249 // Build qualified pointer type.
6250 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006251 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006252 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006253 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006254 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6255
6256 // Insert qualified pointer type.
6257 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006258 }
6259
6260 return true;
6261}
6262
Sebastian Redl78eb8742009-04-19 21:53:20 +00006263/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6264/// to the set of pointer types along with any more-qualified variants of
6265/// that type. For example, if @p Ty is "int const *", this routine
6266/// will add "int const *", "int const volatile *", "int const
6267/// restrict *", and "int const volatile restrict *" to the set of
6268/// pointer types. Returns true if the add of @p Ty itself succeeded,
6269/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006270///
6271/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006272bool
6273BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6274 QualType Ty) {
6275 // Insert this type.
6276 if (!MemberPointerTypes.insert(Ty))
6277 return false;
6278
John McCall0953e762009-09-24 19:53:00 +00006279 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6280 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006281
John McCall0953e762009-09-24 19:53:00 +00006282 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006283 // Don't add qualified variants of arrays. For one, they're not allowed
6284 // (the qualifier would sink to the element type), and for another, the
6285 // only overload situation where it matters is subscript or pointer +- int,
6286 // and those shouldn't have qualifier variants anyway.
6287 if (PointeeTy->isArrayType())
6288 return true;
John McCall0953e762009-09-24 19:53:00 +00006289 const Type *ClassTy = PointerTy->getClass();
6290
6291 // Iterate through all strict supersets of the pointee type's CVR
6292 // qualifiers.
6293 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6294 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6295 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006296
John McCall0953e762009-09-24 19:53:00 +00006297 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006298 MemberPointerTypes.insert(
6299 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006300 }
6301
6302 return true;
6303}
6304
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006305/// AddTypesConvertedFrom - Add each of the types to which the type @p
6306/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006307/// primarily interested in pointer types and enumeration types. We also
6308/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006309/// AllowUserConversions is true if we should look at the conversion
6310/// functions of a class type, and AllowExplicitConversions if we
6311/// should also include the explicit conversion functions of a class
6312/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006313void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006314BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006315 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006316 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006317 bool AllowExplicitConversions,
6318 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006319 // Only deal with canonical types.
6320 Ty = Context.getCanonicalType(Ty);
6321
6322 // Look through reference types; they aren't part of the type of an
6323 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006324 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006325 Ty = RefTy->getPointeeType();
6326
John McCall3b657512011-01-19 10:06:00 +00006327 // If we're dealing with an array type, decay to the pointer.
6328 if (Ty->isArrayType())
6329 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6330
6331 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006332 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006333
Chandler Carruth6a577462010-12-13 01:44:01 +00006334 // Flag if we ever add a non-record type.
6335 const RecordType *TyRec = Ty->getAs<RecordType>();
6336 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6337
Chandler Carruth6a577462010-12-13 01:44:01 +00006338 // Flag if we encounter an arithmetic type.
6339 HasArithmeticOrEnumeralTypes =
6340 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6341
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006342 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6343 PointerTypes.insert(Ty);
6344 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006345 // Insert our type, and its more-qualified variants, into the set
6346 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006347 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006348 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006349 } else if (Ty->isMemberPointerType()) {
6350 // Member pointers are far easier, since the pointee can't be converted.
6351 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6352 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006353 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006354 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006355 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006356 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006357 // We treat vector types as arithmetic types in many contexts as an
6358 // extension.
6359 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006360 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006361 } else if (Ty->isNullPtrType()) {
6362 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006363 } else if (AllowUserConversions && TyRec) {
6364 // No conversion functions in incomplete types.
6365 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6366 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006367
Chandler Carruth6a577462010-12-13 01:44:01 +00006368 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006369 std::pair<CXXRecordDecl::conversion_iterator,
6370 CXXRecordDecl::conversion_iterator>
6371 Conversions = ClassDecl->getVisibleConversionFunctions();
6372 for (CXXRecordDecl::conversion_iterator
6373 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006374 NamedDecl *D = I.getDecl();
6375 if (isa<UsingShadowDecl>(D))
6376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006377
Chandler Carruth6a577462010-12-13 01:44:01 +00006378 // Skip conversion function templates; they don't tell us anything
6379 // about which builtin types we can convert to.
6380 if (isa<FunctionTemplateDecl>(D))
6381 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006382
Chandler Carruth6a577462010-12-13 01:44:01 +00006383 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6384 if (AllowExplicitConversions || !Conv->isExplicit()) {
6385 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6386 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006387 }
6388 }
6389 }
6390}
6391
Douglas Gregor19b7b152009-08-24 13:43:27 +00006392/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6393/// the volatile- and non-volatile-qualified assignment operators for the
6394/// given type to the candidate set.
6395static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6396 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006397 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006398 unsigned NumArgs,
6399 OverloadCandidateSet &CandidateSet) {
6400 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006401
Douglas Gregor19b7b152009-08-24 13:43:27 +00006402 // T& operator=(T&, T)
6403 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6404 ParamTypes[1] = T;
6405 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6406 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006407
Douglas Gregor19b7b152009-08-24 13:43:27 +00006408 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6409 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006410 ParamTypes[0]
6411 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006412 ParamTypes[1] = T;
6413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006414 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006415 }
6416}
Mike Stump1eb44332009-09-09 15:08:12 +00006417
Sebastian Redl9994a342009-10-25 17:03:50 +00006418/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6419/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006420static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6421 Qualifiers VRQuals;
6422 const RecordType *TyRec;
6423 if (const MemberPointerType *RHSMPType =
6424 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006425 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006426 else
6427 TyRec = ArgExpr->getType()->getAs<RecordType>();
6428 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006429 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006430 VRQuals.addVolatile();
6431 VRQuals.addRestrict();
6432 return VRQuals;
6433 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006434
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006436 if (!ClassDecl->hasDefinition())
6437 return VRQuals;
6438
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006439 std::pair<CXXRecordDecl::conversion_iterator,
6440 CXXRecordDecl::conversion_iterator>
6441 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006442
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006443 for (CXXRecordDecl::conversion_iterator
6444 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006445 NamedDecl *D = I.getDecl();
6446 if (isa<UsingShadowDecl>(D))
6447 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6448 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006449 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6450 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6451 CanTy = ResTypeRef->getPointeeType();
6452 // Need to go down the pointer/mempointer chain and add qualifiers
6453 // as see them.
6454 bool done = false;
6455 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006456 if (CanTy.isRestrictQualified())
6457 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006458 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6459 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006460 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006461 CanTy->getAs<MemberPointerType>())
6462 CanTy = ResTypeMPtr->getPointeeType();
6463 else
6464 done = true;
6465 if (CanTy.isVolatileQualified())
6466 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006467 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6468 return VRQuals;
6469 }
6470 }
6471 }
6472 return VRQuals;
6473}
John McCall00071ec2010-11-13 05:51:15 +00006474
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006475namespace {
John McCall00071ec2010-11-13 05:51:15 +00006476
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006477/// \brief Helper class to manage the addition of builtin operator overload
6478/// candidates. It provides shared state and utility methods used throughout
6479/// the process, as well as a helper method to add each group of builtin
6480/// operator overloads from the standard to a candidate set.
6481class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006482 // Common instance state available to all overload candidate addition methods.
6483 Sema &S;
6484 Expr **Args;
6485 unsigned NumArgs;
6486 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006487 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006488 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006489 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006490
Chandler Carruth6d695582010-12-12 10:35:00 +00006491 // Define some constants used to index and iterate over the arithemetic types
6492 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006493 // The "promoted arithmetic types" are the arithmetic
6494 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006495 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006496 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006497 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006498 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006499 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006500 LastPromotedArithmeticType = 11;
6501 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006502
Chandler Carruth6d695582010-12-12 10:35:00 +00006503 /// \brief Get the canonical type for a given arithmetic type index.
6504 CanQualType getArithmeticType(unsigned index) {
6505 assert(index < NumArithmeticTypes);
6506 static CanQualType ASTContext::* const
6507 ArithmeticTypes[NumArithmeticTypes] = {
6508 // Start of promoted types.
6509 &ASTContext::FloatTy,
6510 &ASTContext::DoubleTy,
6511 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006512
Chandler Carruth6d695582010-12-12 10:35:00 +00006513 // Start of integral types.
6514 &ASTContext::IntTy,
6515 &ASTContext::LongTy,
6516 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006517 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006518 &ASTContext::UnsignedIntTy,
6519 &ASTContext::UnsignedLongTy,
6520 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006521 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006522 // End of promoted types.
6523
6524 &ASTContext::BoolTy,
6525 &ASTContext::CharTy,
6526 &ASTContext::WCharTy,
6527 &ASTContext::Char16Ty,
6528 &ASTContext::Char32Ty,
6529 &ASTContext::SignedCharTy,
6530 &ASTContext::ShortTy,
6531 &ASTContext::UnsignedCharTy,
6532 &ASTContext::UnsignedShortTy,
6533 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006534 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006535 };
6536 return S.Context.*ArithmeticTypes[index];
6537 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006538
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006539 /// \brief Gets the canonical type resulting from the usual arithemetic
6540 /// converions for the given arithmetic types.
6541 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6542 // Accelerator table for performing the usual arithmetic conversions.
6543 // The rules are basically:
6544 // - if either is floating-point, use the wider floating-point
6545 // - if same signedness, use the higher rank
6546 // - if same size, use unsigned of the higher rank
6547 // - use the larger type
6548 // These rules, together with the axiom that higher ranks are
6549 // never smaller, are sufficient to precompute all of these results
6550 // *except* when dealing with signed types of higher rank.
6551 // (we could precompute SLL x UI for all known platforms, but it's
6552 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006553 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006554 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006555 Dep=-1,
6556 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006557 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006558 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006559 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006560/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6561/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6562/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6563/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6564/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6565/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6566/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6567/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6568/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6569/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6570/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006571 };
6572
6573 assert(L < LastPromotedArithmeticType);
6574 assert(R < LastPromotedArithmeticType);
6575 int Idx = ConversionsTable[L][R];
6576
6577 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006578 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006579
6580 // Slow path: we need to compare widths.
6581 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006582 CanQualType LT = getArithmeticType(L),
6583 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006584 unsigned LW = S.Context.getIntWidth(LT),
6585 RW = S.Context.getIntWidth(RT);
6586
6587 // If they're different widths, use the signed type.
6588 if (LW > RW) return LT;
6589 else if (LW < RW) return RT;
6590
6591 // Otherwise, use the unsigned type of the signed type's rank.
6592 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6593 assert(L == SLL || R == SLL);
6594 return S.Context.UnsignedLongLongTy;
6595 }
6596
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006597 /// \brief Helper method to factor out the common pattern of adding overloads
6598 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006600 bool HasVolatile,
6601 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006602 QualType ParamTypes[2] = {
6603 S.Context.getLValueReferenceType(CandidateTy),
6604 S.Context.IntTy
6605 };
6606
6607 // Non-volatile version.
6608 if (NumArgs == 1)
6609 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6610 else
6611 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6612
6613 // Use a heuristic to reduce number of builtin candidates in the set:
6614 // add volatile version only if there are conversions to a volatile type.
6615 if (HasVolatile) {
6616 ParamTypes[0] =
6617 S.Context.getLValueReferenceType(
6618 S.Context.getVolatileType(CandidateTy));
6619 if (NumArgs == 1)
6620 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6621 else
6622 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6623 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006624
6625 // Add restrict version only if there are conversions to a restrict type
6626 // and our candidate type is a non-restrict-qualified pointer.
6627 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6628 !CandidateTy.isRestrictQualified()) {
6629 ParamTypes[0]
6630 = S.Context.getLValueReferenceType(
6631 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6632 if (NumArgs == 1)
6633 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6634 else
6635 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6636
6637 if (HasVolatile) {
6638 ParamTypes[0]
6639 = S.Context.getLValueReferenceType(
6640 S.Context.getCVRQualifiedType(CandidateTy,
6641 (Qualifiers::Volatile |
6642 Qualifiers::Restrict)));
6643 if (NumArgs == 1)
6644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6645 CandidateSet);
6646 else
6647 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6648 }
6649 }
6650
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006651 }
6652
6653public:
6654 BuiltinOperatorOverloadBuilder(
6655 Sema &S, Expr **Args, unsigned NumArgs,
6656 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006657 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006658 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006659 OverloadCandidateSet &CandidateSet)
6660 : S(S), Args(Args), NumArgs(NumArgs),
6661 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006662 HasArithmeticOrEnumeralCandidateType(
6663 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006664 CandidateTypes(CandidateTypes),
6665 CandidateSet(CandidateSet) {
6666 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006667 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006668 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006669 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006670 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006671 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006672 assert(getArithmeticType(FirstPromotedArithmeticType)
6673 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006674 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006675 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006676 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006677 "Invalid last promoted arithmetic type");
6678 }
6679
6680 // C++ [over.built]p3:
6681 //
6682 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6683 // is either volatile or empty, there exist candidate operator
6684 // functions of the form
6685 //
6686 // VQ T& operator++(VQ T&);
6687 // T operator++(VQ T&, int);
6688 //
6689 // C++ [over.built]p4:
6690 //
6691 // For every pair (T, VQ), where T is an arithmetic type other
6692 // than bool, and VQ is either volatile or empty, there exist
6693 // candidate operator functions of the form
6694 //
6695 // VQ T& operator--(VQ T&);
6696 // T operator--(VQ T&, int);
6697 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006698 if (!HasArithmeticOrEnumeralCandidateType)
6699 return;
6700
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006701 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6702 Arith < NumArithmeticTypes; ++Arith) {
6703 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006704 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006705 VisibleTypeConversionsQuals.hasVolatile(),
6706 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006707 }
6708 }
6709
6710 // C++ [over.built]p5:
6711 //
6712 // For every pair (T, VQ), where T is a cv-qualified or
6713 // cv-unqualified object type, and VQ is either volatile or
6714 // empty, there exist candidate operator functions of the form
6715 //
6716 // T*VQ& operator++(T*VQ&);
6717 // T*VQ& operator--(T*VQ&);
6718 // T* operator++(T*VQ&, int);
6719 // T* operator--(T*VQ&, int);
6720 void addPlusPlusMinusMinusPointerOverloads() {
6721 for (BuiltinCandidateTypeSet::iterator
6722 Ptr = CandidateTypes[0].pointer_begin(),
6723 PtrEnd = CandidateTypes[0].pointer_end();
6724 Ptr != PtrEnd; ++Ptr) {
6725 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006726 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006727 continue;
6728
6729 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006730 (!(*Ptr).isVolatileQualified() &&
6731 VisibleTypeConversionsQuals.hasVolatile()),
6732 (!(*Ptr).isRestrictQualified() &&
6733 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006734 }
6735 }
6736
6737 // C++ [over.built]p6:
6738 // For every cv-qualified or cv-unqualified object type T, there
6739 // exist candidate operator functions of the form
6740 //
6741 // T& operator*(T*);
6742 //
6743 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006744 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006745 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006746 // T& operator*(T*);
6747 void addUnaryStarPointerOverloads() {
6748 for (BuiltinCandidateTypeSet::iterator
6749 Ptr = CandidateTypes[0].pointer_begin(),
6750 PtrEnd = CandidateTypes[0].pointer_end();
6751 Ptr != PtrEnd; ++Ptr) {
6752 QualType ParamTy = *Ptr;
6753 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006754 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6755 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006756
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006757 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6758 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6759 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006760
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006761 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6762 &ParamTy, Args, 1, CandidateSet);
6763 }
6764 }
6765
6766 // C++ [over.built]p9:
6767 // For every promoted arithmetic type T, there exist candidate
6768 // operator functions of the form
6769 //
6770 // T operator+(T);
6771 // T operator-(T);
6772 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006773 if (!HasArithmeticOrEnumeralCandidateType)
6774 return;
6775
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006776 for (unsigned Arith = FirstPromotedArithmeticType;
6777 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006778 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006779 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6780 }
6781
6782 // Extension: We also add these operators for vector types.
6783 for (BuiltinCandidateTypeSet::iterator
6784 Vec = CandidateTypes[0].vector_begin(),
6785 VecEnd = CandidateTypes[0].vector_end();
6786 Vec != VecEnd; ++Vec) {
6787 QualType VecTy = *Vec;
6788 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6789 }
6790 }
6791
6792 // C++ [over.built]p8:
6793 // For every type T, there exist candidate operator functions of
6794 // the form
6795 //
6796 // T* operator+(T*);
6797 void addUnaryPlusPointerOverloads() {
6798 for (BuiltinCandidateTypeSet::iterator
6799 Ptr = CandidateTypes[0].pointer_begin(),
6800 PtrEnd = CandidateTypes[0].pointer_end();
6801 Ptr != PtrEnd; ++Ptr) {
6802 QualType ParamTy = *Ptr;
6803 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6804 }
6805 }
6806
6807 // C++ [over.built]p10:
6808 // For every promoted integral type T, there exist candidate
6809 // operator functions of the form
6810 //
6811 // T operator~(T);
6812 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006813 if (!HasArithmeticOrEnumeralCandidateType)
6814 return;
6815
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006816 for (unsigned Int = FirstPromotedIntegralType;
6817 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006818 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006819 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6820 }
6821
6822 // Extension: We also add this operator for vector types.
6823 for (BuiltinCandidateTypeSet::iterator
6824 Vec = CandidateTypes[0].vector_begin(),
6825 VecEnd = CandidateTypes[0].vector_end();
6826 Vec != VecEnd; ++Vec) {
6827 QualType VecTy = *Vec;
6828 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6829 }
6830 }
6831
6832 // C++ [over.match.oper]p16:
6833 // For every pointer to member type T, there exist candidate operator
6834 // functions of the form
6835 //
6836 // bool operator==(T,T);
6837 // bool operator!=(T,T);
6838 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6839 /// Set of (canonical) types that we've already handled.
6840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6841
6842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6843 for (BuiltinCandidateTypeSet::iterator
6844 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6845 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6846 MemPtr != MemPtrEnd;
6847 ++MemPtr) {
6848 // Don't add the same builtin candidate twice.
6849 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6850 continue;
6851
6852 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6853 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6854 CandidateSet);
6855 }
6856 }
6857 }
6858
6859 // C++ [over.built]p15:
6860 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006861 // For every T, where T is an enumeration type, a pointer type, or
6862 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006863 //
6864 // bool operator<(T, T);
6865 // bool operator>(T, T);
6866 // bool operator<=(T, T);
6867 // bool operator>=(T, T);
6868 // bool operator==(T, T);
6869 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006870 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006871 // C++ [over.match.oper]p3:
6872 // [...]the built-in candidates include all of the candidate operator
6873 // functions defined in 13.6 that, compared to the given operator, [...]
6874 // do not have the same parameter-type-list as any non-template non-member
6875 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006876 //
Eli Friedman97c67392012-09-18 21:52:24 +00006877 // Note that in practice, this only affects enumeration types because there
6878 // aren't any built-in candidates of record type, and a user-defined operator
6879 // must have an operand of record or enumeration type. Also, the only other
6880 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006881 // cannot be overloaded for enumeration types, so this is the only place
6882 // where we must suppress candidates like this.
6883 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6884 UserDefinedBinaryOperators;
6885
6886 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6887 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6888 CandidateTypes[ArgIdx].enumeration_end()) {
6889 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6890 CEnd = CandidateSet.end();
6891 C != CEnd; ++C) {
6892 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6893 continue;
6894
Eli Friedman97c67392012-09-18 21:52:24 +00006895 if (C->Function->isFunctionTemplateSpecialization())
6896 continue;
6897
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006898 QualType FirstParamType =
6899 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6900 QualType SecondParamType =
6901 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6902
6903 // Skip if either parameter isn't of enumeral type.
6904 if (!FirstParamType->isEnumeralType() ||
6905 !SecondParamType->isEnumeralType())
6906 continue;
6907
6908 // Add this operator to the set of known user-defined operators.
6909 UserDefinedBinaryOperators.insert(
6910 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6911 S.Context.getCanonicalType(SecondParamType)));
6912 }
6913 }
6914 }
6915
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006916 /// Set of (canonical) types that we've already handled.
6917 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6918
6919 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6920 for (BuiltinCandidateTypeSet::iterator
6921 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6922 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6923 Ptr != PtrEnd; ++Ptr) {
6924 // Don't add the same builtin candidate twice.
6925 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6926 continue;
6927
6928 QualType ParamTypes[2] = { *Ptr, *Ptr };
6929 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6930 CandidateSet);
6931 }
6932 for (BuiltinCandidateTypeSet::iterator
6933 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6934 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6935 Enum != EnumEnd; ++Enum) {
6936 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6937
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006938 // Don't add the same builtin candidate twice, or if a user defined
6939 // candidate exists.
6940 if (!AddedTypes.insert(CanonType) ||
6941 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6942 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006943 continue;
6944
6945 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006946 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6947 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006948 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006949
6950 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6951 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6952 if (AddedTypes.insert(NullPtrTy) &&
6953 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6954 NullPtrTy))) {
6955 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6956 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6957 CandidateSet);
6958 }
6959 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006960 }
6961 }
6962
6963 // C++ [over.built]p13:
6964 //
6965 // For every cv-qualified or cv-unqualified object type T
6966 // there exist candidate operator functions of the form
6967 //
6968 // T* operator+(T*, ptrdiff_t);
6969 // T& operator[](T*, ptrdiff_t); [BELOW]
6970 // T* operator-(T*, ptrdiff_t);
6971 // T* operator+(ptrdiff_t, T*);
6972 // T& operator[](ptrdiff_t, T*); [BELOW]
6973 //
6974 // C++ [over.built]p14:
6975 //
6976 // For every T, where T is a pointer to object type, there
6977 // exist candidate operator functions of the form
6978 //
6979 // ptrdiff_t operator-(T, T);
6980 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6981 /// Set of (canonical) types that we've already handled.
6982 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6983
6984 for (int Arg = 0; Arg < 2; ++Arg) {
6985 QualType AsymetricParamTypes[2] = {
6986 S.Context.getPointerDiffType(),
6987 S.Context.getPointerDiffType(),
6988 };
6989 for (BuiltinCandidateTypeSet::iterator
6990 Ptr = CandidateTypes[Arg].pointer_begin(),
6991 PtrEnd = CandidateTypes[Arg].pointer_end();
6992 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006993 QualType PointeeTy = (*Ptr)->getPointeeType();
6994 if (!PointeeTy->isObjectType())
6995 continue;
6996
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006997 AsymetricParamTypes[Arg] = *Ptr;
6998 if (Arg == 0 || Op == OO_Plus) {
6999 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7000 // T* operator+(ptrdiff_t, T*);
7001 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
7002 CandidateSet);
7003 }
7004 if (Op == OO_Minus) {
7005 // ptrdiff_t operator-(T, T);
7006 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7007 continue;
7008
7009 QualType ParamTypes[2] = { *Ptr, *Ptr };
7010 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7011 Args, 2, CandidateSet);
7012 }
7013 }
7014 }
7015 }
7016
7017 // C++ [over.built]p12:
7018 //
7019 // For every pair of promoted arithmetic types L and R, there
7020 // exist candidate operator functions of the form
7021 //
7022 // LR operator*(L, R);
7023 // LR operator/(L, R);
7024 // LR operator+(L, R);
7025 // LR operator-(L, R);
7026 // bool operator<(L, R);
7027 // bool operator>(L, R);
7028 // bool operator<=(L, R);
7029 // bool operator>=(L, R);
7030 // bool operator==(L, R);
7031 // bool operator!=(L, R);
7032 //
7033 // where LR is the result of the usual arithmetic conversions
7034 // between types L and R.
7035 //
7036 // C++ [over.built]p24:
7037 //
7038 // For every pair of promoted arithmetic types L and R, there exist
7039 // candidate operator functions of the form
7040 //
7041 // LR operator?(bool, L, R);
7042 //
7043 // where LR is the result of the usual arithmetic conversions
7044 // between types L and R.
7045 // Our candidates ignore the first parameter.
7046 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007047 if (!HasArithmeticOrEnumeralCandidateType)
7048 return;
7049
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007050 for (unsigned Left = FirstPromotedArithmeticType;
7051 Left < LastPromotedArithmeticType; ++Left) {
7052 for (unsigned Right = FirstPromotedArithmeticType;
7053 Right < LastPromotedArithmeticType; ++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 =
7057 isComparison ? S.Context.BoolTy
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 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7064 // conditional operator for vector types.
7065 for (BuiltinCandidateTypeSet::iterator
7066 Vec1 = CandidateTypes[0].vector_begin(),
7067 Vec1End = CandidateTypes[0].vector_end();
7068 Vec1 != Vec1End; ++Vec1) {
7069 for (BuiltinCandidateTypeSet::iterator
7070 Vec2 = CandidateTypes[1].vector_begin(),
7071 Vec2End = CandidateTypes[1].vector_end();
7072 Vec2 != Vec2End; ++Vec2) {
7073 QualType LandR[2] = { *Vec1, *Vec2 };
7074 QualType Result = S.Context.BoolTy;
7075 if (!isComparison) {
7076 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7077 Result = *Vec1;
7078 else
7079 Result = *Vec2;
7080 }
7081
7082 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7083 }
7084 }
7085 }
7086
7087 // C++ [over.built]p17:
7088 //
7089 // For every pair of promoted integral types L and R, there
7090 // exist candidate operator functions of the form
7091 //
7092 // LR operator%(L, R);
7093 // LR operator&(L, R);
7094 // LR operator^(L, R);
7095 // LR operator|(L, R);
7096 // L operator<<(L, R);
7097 // L operator>>(L, R);
7098 //
7099 // where LR is the result of the usual arithmetic conversions
7100 // between types L and R.
7101 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007102 if (!HasArithmeticOrEnumeralCandidateType)
7103 return;
7104
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007105 for (unsigned Left = FirstPromotedIntegralType;
7106 Left < LastPromotedIntegralType; ++Left) {
7107 for (unsigned Right = FirstPromotedIntegralType;
7108 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007109 QualType LandR[2] = { getArithmeticType(Left),
7110 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007111 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7112 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007113 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007114 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7115 }
7116 }
7117 }
7118
7119 // C++ [over.built]p20:
7120 //
7121 // For every pair (T, VQ), where T is an enumeration or
7122 // pointer to member type and VQ is either volatile or
7123 // empty, there exist candidate operator functions of the form
7124 //
7125 // VQ T& operator=(VQ T&, T);
7126 void addAssignmentMemberPointerOrEnumeralOverloads() {
7127 /// Set of (canonical) types that we've already handled.
7128 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7129
7130 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7131 for (BuiltinCandidateTypeSet::iterator
7132 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7133 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7134 Enum != EnumEnd; ++Enum) {
7135 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7136 continue;
7137
7138 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7139 CandidateSet);
7140 }
7141
7142 for (BuiltinCandidateTypeSet::iterator
7143 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7144 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7145 MemPtr != MemPtrEnd; ++MemPtr) {
7146 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7147 continue;
7148
7149 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7150 CandidateSet);
7151 }
7152 }
7153 }
7154
7155 // C++ [over.built]p19:
7156 //
7157 // For every pair (T, VQ), where T is any type and VQ is either
7158 // volatile or empty, there exist candidate operator functions
7159 // of the form
7160 //
7161 // T*VQ& operator=(T*VQ&, T*);
7162 //
7163 // C++ [over.built]p21:
7164 //
7165 // For every pair (T, VQ), where T is a cv-qualified or
7166 // cv-unqualified object type and VQ is either volatile or
7167 // empty, there exist candidate operator functions of the form
7168 //
7169 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7170 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7171 void addAssignmentPointerOverloads(bool isEqualOp) {
7172 /// Set of (canonical) types that we've already handled.
7173 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7174
7175 for (BuiltinCandidateTypeSet::iterator
7176 Ptr = CandidateTypes[0].pointer_begin(),
7177 PtrEnd = CandidateTypes[0].pointer_end();
7178 Ptr != PtrEnd; ++Ptr) {
7179 // If this is operator=, keep track of the builtin candidates we added.
7180 if (isEqualOp)
7181 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007182 else if (!(*Ptr)->getPointeeType()->isObjectType())
7183 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007184
7185 // non-volatile version
7186 QualType ParamTypes[2] = {
7187 S.Context.getLValueReferenceType(*Ptr),
7188 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7189 };
7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7191 /*IsAssigmentOperator=*/ isEqualOp);
7192
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007193 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7194 VisibleTypeConversionsQuals.hasVolatile();
7195 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007196 // volatile version
7197 ParamTypes[0] =
7198 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7199 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7200 /*IsAssigmentOperator=*/isEqualOp);
7201 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007202
7203 if (!(*Ptr).isRestrictQualified() &&
7204 VisibleTypeConversionsQuals.hasRestrict()) {
7205 // restrict version
7206 ParamTypes[0]
7207 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7208 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7209 /*IsAssigmentOperator=*/isEqualOp);
7210
7211 if (NeedVolatile) {
7212 // volatile restrict version
7213 ParamTypes[0]
7214 = S.Context.getLValueReferenceType(
7215 S.Context.getCVRQualifiedType(*Ptr,
7216 (Qualifiers::Volatile |
7217 Qualifiers::Restrict)));
7218 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7219 CandidateSet,
7220 /*IsAssigmentOperator=*/isEqualOp);
7221 }
7222 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007223 }
7224
7225 if (isEqualOp) {
7226 for (BuiltinCandidateTypeSet::iterator
7227 Ptr = CandidateTypes[1].pointer_begin(),
7228 PtrEnd = CandidateTypes[1].pointer_end();
7229 Ptr != PtrEnd; ++Ptr) {
7230 // Make sure we don't add the same candidate twice.
7231 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7232 continue;
7233
Chandler Carruth6df868e2010-12-12 08:17:55 +00007234 QualType ParamTypes[2] = {
7235 S.Context.getLValueReferenceType(*Ptr),
7236 *Ptr,
7237 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007238
7239 // non-volatile version
7240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7241 /*IsAssigmentOperator=*/true);
7242
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007243 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7244 VisibleTypeConversionsQuals.hasVolatile();
7245 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007246 // volatile version
7247 ParamTypes[0] =
7248 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7250 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007251 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007252
7253 if (!(*Ptr).isRestrictQualified() &&
7254 VisibleTypeConversionsQuals.hasRestrict()) {
7255 // restrict version
7256 ParamTypes[0]
7257 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7259 CandidateSet, /*IsAssigmentOperator=*/true);
7260
7261 if (NeedVolatile) {
7262 // volatile restrict version
7263 ParamTypes[0]
7264 = S.Context.getLValueReferenceType(
7265 S.Context.getCVRQualifiedType(*Ptr,
7266 (Qualifiers::Volatile |
7267 Qualifiers::Restrict)));
7268 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7269 CandidateSet, /*IsAssigmentOperator=*/true);
7270
7271 }
7272 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007273 }
7274 }
7275 }
7276
7277 // C++ [over.built]p18:
7278 //
7279 // For every triple (L, VQ, R), where L is an arithmetic type,
7280 // VQ is either volatile or empty, and R is a promoted
7281 // arithmetic type, there exist candidate operator functions of
7282 // the form
7283 //
7284 // VQ L& operator=(VQ L&, R);
7285 // VQ L& operator*=(VQ L&, R);
7286 // VQ L& operator/=(VQ L&, R);
7287 // VQ L& operator+=(VQ L&, R);
7288 // VQ L& operator-=(VQ L&, R);
7289 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007290 if (!HasArithmeticOrEnumeralCandidateType)
7291 return;
7292
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007293 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7294 for (unsigned Right = FirstPromotedArithmeticType;
7295 Right < LastPromotedArithmeticType; ++Right) {
7296 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007297 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007298
7299 // Add this built-in operator as a candidate (VQ is empty).
7300 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007301 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7303 /*IsAssigmentOperator=*/isEqualOp);
7304
7305 // Add this built-in operator as a candidate (VQ is 'volatile').
7306 if (VisibleTypeConversionsQuals.hasVolatile()) {
7307 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007308 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007309 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007310 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7311 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007312 /*IsAssigmentOperator=*/isEqualOp);
7313 }
7314 }
7315 }
7316
7317 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7318 for (BuiltinCandidateTypeSet::iterator
7319 Vec1 = CandidateTypes[0].vector_begin(),
7320 Vec1End = CandidateTypes[0].vector_end();
7321 Vec1 != Vec1End; ++Vec1) {
7322 for (BuiltinCandidateTypeSet::iterator
7323 Vec2 = CandidateTypes[1].vector_begin(),
7324 Vec2End = CandidateTypes[1].vector_end();
7325 Vec2 != Vec2End; ++Vec2) {
7326 QualType ParamTypes[2];
7327 ParamTypes[1] = *Vec2;
7328 // Add this built-in operator as a candidate (VQ is empty).
7329 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7331 /*IsAssigmentOperator=*/isEqualOp);
7332
7333 // Add this built-in operator as a candidate (VQ is 'volatile').
7334 if (VisibleTypeConversionsQuals.hasVolatile()) {
7335 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7336 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007337 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7338 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007339 /*IsAssigmentOperator=*/isEqualOp);
7340 }
7341 }
7342 }
7343 }
7344
7345 // C++ [over.built]p22:
7346 //
7347 // For every triple (L, VQ, R), where L is an integral type, VQ
7348 // is either volatile or empty, and R is a promoted integral
7349 // type, there exist candidate operator functions of the form
7350 //
7351 // VQ L& operator%=(VQ L&, R);
7352 // VQ L& operator<<=(VQ L&, R);
7353 // VQ L& operator>>=(VQ L&, R);
7354 // VQ L& operator&=(VQ L&, R);
7355 // VQ L& operator^=(VQ L&, R);
7356 // VQ L& operator|=(VQ L&, R);
7357 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007358 if (!HasArithmeticOrEnumeralCandidateType)
7359 return;
7360
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007361 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7362 for (unsigned Right = FirstPromotedIntegralType;
7363 Right < LastPromotedIntegralType; ++Right) {
7364 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007365 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007366
7367 // Add this built-in operator as a candidate (VQ is empty).
7368 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007369 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007370 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7371 if (VisibleTypeConversionsQuals.hasVolatile()) {
7372 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007373 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007374 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7375 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7376 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7377 CandidateSet);
7378 }
7379 }
7380 }
7381 }
7382
7383 // C++ [over.operator]p23:
7384 //
7385 // There also exist candidate operator functions of the form
7386 //
7387 // bool operator!(bool);
7388 // bool operator&&(bool, bool);
7389 // bool operator||(bool, bool);
7390 void addExclaimOverload() {
7391 QualType ParamTy = S.Context.BoolTy;
7392 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7393 /*IsAssignmentOperator=*/false,
7394 /*NumContextualBoolArguments=*/1);
7395 }
7396 void addAmpAmpOrPipePipeOverload() {
7397 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7398 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7399 /*IsAssignmentOperator=*/false,
7400 /*NumContextualBoolArguments=*/2);
7401 }
7402
7403 // C++ [over.built]p13:
7404 //
7405 // For every cv-qualified or cv-unqualified object type T there
7406 // exist candidate operator functions of the form
7407 //
7408 // T* operator+(T*, ptrdiff_t); [ABOVE]
7409 // T& operator[](T*, ptrdiff_t);
7410 // T* operator-(T*, ptrdiff_t); [ABOVE]
7411 // T* operator+(ptrdiff_t, T*); [ABOVE]
7412 // T& operator[](ptrdiff_t, T*);
7413 void addSubscriptOverloads() {
7414 for (BuiltinCandidateTypeSet::iterator
7415 Ptr = CandidateTypes[0].pointer_begin(),
7416 PtrEnd = CandidateTypes[0].pointer_end();
7417 Ptr != PtrEnd; ++Ptr) {
7418 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7419 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007420 if (!PointeeType->isObjectType())
7421 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007422
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007423 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7424
7425 // T& operator[](T*, ptrdiff_t)
7426 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7427 }
7428
7429 for (BuiltinCandidateTypeSet::iterator
7430 Ptr = CandidateTypes[1].pointer_begin(),
7431 PtrEnd = CandidateTypes[1].pointer_end();
7432 Ptr != PtrEnd; ++Ptr) {
7433 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7434 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007435 if (!PointeeType->isObjectType())
7436 continue;
7437
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007438 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7439
7440 // T& operator[](ptrdiff_t, T*)
7441 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7442 }
7443 }
7444
7445 // C++ [over.built]p11:
7446 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7447 // C1 is the same type as C2 or is a derived class of C2, T is an object
7448 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7449 // there exist candidate operator functions of the form
7450 //
7451 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7452 //
7453 // where CV12 is the union of CV1 and CV2.
7454 void addArrowStarOverloads() {
7455 for (BuiltinCandidateTypeSet::iterator
7456 Ptr = CandidateTypes[0].pointer_begin(),
7457 PtrEnd = CandidateTypes[0].pointer_end();
7458 Ptr != PtrEnd; ++Ptr) {
7459 QualType C1Ty = (*Ptr);
7460 QualType C1;
7461 QualifierCollector Q1;
7462 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7463 if (!isa<RecordType>(C1))
7464 continue;
7465 // heuristic to reduce number of builtin candidates in the set.
7466 // Add volatile/restrict version only if there are conversions to a
7467 // volatile/restrict type.
7468 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7469 continue;
7470 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7471 continue;
7472 for (BuiltinCandidateTypeSet::iterator
7473 MemPtr = CandidateTypes[1].member_pointer_begin(),
7474 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7475 MemPtr != MemPtrEnd; ++MemPtr) {
7476 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7477 QualType C2 = QualType(mptr->getClass(), 0);
7478 C2 = C2.getUnqualifiedType();
7479 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7480 break;
7481 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7482 // build CV12 T&
7483 QualType T = mptr->getPointeeType();
7484 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7485 T.isVolatileQualified())
7486 continue;
7487 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7488 T.isRestrictQualified())
7489 continue;
7490 T = Q1.apply(S.Context, T);
7491 QualType ResultTy = S.Context.getLValueReferenceType(T);
7492 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7493 }
7494 }
7495 }
7496
7497 // Note that we don't consider the first argument, since it has been
7498 // contextually converted to bool long ago. The candidates below are
7499 // therefore added as binary.
7500 //
7501 // C++ [over.built]p25:
7502 // For every type T, where T is a pointer, pointer-to-member, or scoped
7503 // enumeration type, there exist candidate operator functions of the form
7504 //
7505 // T operator?(bool, T, T);
7506 //
7507 void addConditionalOperatorOverloads() {
7508 /// Set of (canonical) types that we've already handled.
7509 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7510
7511 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7512 for (BuiltinCandidateTypeSet::iterator
7513 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7514 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7515 Ptr != PtrEnd; ++Ptr) {
7516 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7517 continue;
7518
7519 QualType ParamTypes[2] = { *Ptr, *Ptr };
7520 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7521 }
7522
7523 for (BuiltinCandidateTypeSet::iterator
7524 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7525 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7526 MemPtr != MemPtrEnd; ++MemPtr) {
7527 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7528 continue;
7529
7530 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7531 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7532 }
7533
Richard Smith80ad52f2013-01-02 11:42:31 +00007534 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007535 for (BuiltinCandidateTypeSet::iterator
7536 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7537 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7538 Enum != EnumEnd; ++Enum) {
7539 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7540 continue;
7541
7542 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7543 continue;
7544
7545 QualType ParamTypes[2] = { *Enum, *Enum };
7546 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7547 }
7548 }
7549 }
7550 }
7551};
7552
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007553} // end anonymous namespace
7554
7555/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7556/// operator overloads to the candidate set (C++ [over.built]), based
7557/// on the operator @p Op and the arguments given. For example, if the
7558/// operator is a binary '+', this routine might add "int
7559/// operator+(int, int)" to cover integer addition.
7560void
7561Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7562 SourceLocation OpLoc,
7563 Expr **Args, unsigned NumArgs,
7564 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007565 // Find all of the types that the arguments can convert to, but only
7566 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007567 // that make use of these types. Also record whether we encounter non-record
7568 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007569 Qualifiers VisibleTypeConversionsQuals;
7570 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007571 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7572 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007573
7574 bool HasNonRecordCandidateType = false;
7575 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007576 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007577 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7578 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7579 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7580 OpLoc,
7581 true,
7582 (Op == OO_Exclaim ||
7583 Op == OO_AmpAmp ||
7584 Op == OO_PipePipe),
7585 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007586 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7587 CandidateTypes[ArgIdx].hasNonRecordTypes();
7588 HasArithmeticOrEnumeralCandidateType =
7589 HasArithmeticOrEnumeralCandidateType ||
7590 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007591 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007592
Chandler Carruth6a577462010-12-13 01:44:01 +00007593 // Exit early when no non-record types have been added to the candidate set
7594 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007595 //
7596 // We can't exit early for !, ||, or &&, since there we have always have
7597 // 'bool' overloads.
7598 if (!HasNonRecordCandidateType &&
7599 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007600 return;
7601
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007602 // Setup an object to manage the common state for building overloads.
7603 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7604 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007605 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007606 CandidateTypes, CandidateSet);
7607
7608 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007609 switch (Op) {
7610 case OO_None:
7611 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007612 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007613
Chandler Carruthabb71842010-12-12 08:51:33 +00007614 case OO_New:
7615 case OO_Delete:
7616 case OO_Array_New:
7617 case OO_Array_Delete:
7618 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007619 llvm_unreachable(
7620 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007621
7622 case OO_Comma:
7623 case OO_Arrow:
7624 // C++ [over.match.oper]p3:
7625 // -- For the operator ',', the unary operator '&', or the
7626 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007627 break;
7628
7629 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007630 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007631 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007632 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007633
7634 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007635 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007636 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007637 } else {
7638 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7639 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7640 }
Douglas Gregor74253732008-11-19 15:42:04 +00007641 break;
7642
Chandler Carruthabb71842010-12-12 08:51:33 +00007643 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007644 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007645 OpBuilder.addUnaryStarPointerOverloads();
7646 else
7647 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7648 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007649
Chandler Carruthabb71842010-12-12 08:51:33 +00007650 case OO_Slash:
7651 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007652 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007653
7654 case OO_PlusPlus:
7655 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007656 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7657 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007658 break;
7659
Douglas Gregor19b7b152009-08-24 13:43:27 +00007660 case OO_EqualEqual:
7661 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007662 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007663 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007664
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007665 case OO_Less:
7666 case OO_Greater:
7667 case OO_LessEqual:
7668 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007669 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007670 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7671 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007672
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007673 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007674 case OO_Caret:
7675 case OO_Pipe:
7676 case OO_LessLess:
7677 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007678 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007679 break;
7680
Chandler Carruthabb71842010-12-12 08:51:33 +00007681 case OO_Amp: // '&' is either unary or binary
7682 if (NumArgs == 1)
7683 // C++ [over.match.oper]p3:
7684 // -- For the operator ',', the unary operator '&', or the
7685 // operator '->', the built-in candidates set is empty.
7686 break;
7687
7688 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7689 break;
7690
7691 case OO_Tilde:
7692 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7693 break;
7694
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007695 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007696 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007697 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007698
7699 case OO_PlusEqual:
7700 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007701 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007702 // Fall through.
7703
7704 case OO_StarEqual:
7705 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007706 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007707 break;
7708
7709 case OO_PercentEqual:
7710 case OO_LessLessEqual:
7711 case OO_GreaterGreaterEqual:
7712 case OO_AmpEqual:
7713 case OO_CaretEqual:
7714 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007715 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007716 break;
7717
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007718 case OO_Exclaim:
7719 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007720 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007721
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007722 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007723 case OO_PipePipe:
7724 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007725 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007726
7727 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007728 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007729 break;
7730
7731 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007732 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007733 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007734
7735 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007736 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007737 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7738 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007739 }
7740}
7741
Douglas Gregorfa047642009-02-04 00:32:51 +00007742/// \brief Add function candidates found via argument-dependent lookup
7743/// to the set of overloading candidates.
7744///
7745/// This routine performs argument-dependent name lookup based on the
7746/// given function name (which may also be an operator name) and adds
7747/// all of the overload candidates found by ADL to the overload
7748/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007749void
Douglas Gregorfa047642009-02-04 00:32:51 +00007750Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007751 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007752 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007753 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007754 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007755 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007756 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007757
John McCalla113e722010-01-26 06:04:06 +00007758 // FIXME: This approach for uniquing ADL results (and removing
7759 // redundant candidates from the set) relies on pointer-equality,
7760 // which means we need to key off the canonical decl. However,
7761 // always going back to the canonical decl might not get us the
7762 // right set of default arguments. What default arguments are
7763 // we supposed to consider on ADL candidates, anyway?
7764
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007765 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007766 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007767
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007768 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007769 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7770 CandEnd = CandidateSet.end();
7771 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007772 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007773 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007774 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007775 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007776 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007777
7778 // For each of the ADL candidates we found, add it to the overload
7779 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007780 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007781 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007782 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007783 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007784 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007785
Ahmed Charles13a140c2012-02-25 11:00:22 +00007786 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7787 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007788 } else
John McCall6e266892010-01-26 03:27:55 +00007789 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007790 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007791 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007792 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007793}
7794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007795/// isBetterOverloadCandidate - Determines whether the first overload
7796/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007797bool
John McCall120d63c2010-08-24 20:38:10 +00007798isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007799 const OverloadCandidate &Cand1,
7800 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007801 SourceLocation Loc,
7802 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007803 // Define viable functions to be better candidates than non-viable
7804 // functions.
7805 if (!Cand2.Viable)
7806 return Cand1.Viable;
7807 else if (!Cand1.Viable)
7808 return false;
7809
Douglas Gregor88a35142008-12-22 05:46:06 +00007810 // C++ [over.match.best]p1:
7811 //
7812 // -- if F is a static member function, ICS1(F) is defined such
7813 // that ICS1(F) is neither better nor worse than ICS1(G) for
7814 // any function G, and, symmetrically, ICS1(G) is neither
7815 // better nor worse than ICS1(F).
7816 unsigned StartArg = 0;
7817 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7818 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007819
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007820 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007821 // A viable function F1 is defined to be a better function than another
7822 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007823 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007824 unsigned NumArgs = Cand1.NumConversions;
7825 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007826 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007827 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007828 switch (CompareImplicitConversionSequences(S,
7829 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007830 Cand2.Conversions[ArgIdx])) {
7831 case ImplicitConversionSequence::Better:
7832 // Cand1 has a better conversion sequence.
7833 HasBetterConversion = true;
7834 break;
7835
7836 case ImplicitConversionSequence::Worse:
7837 // Cand1 can't be better than Cand2.
7838 return false;
7839
7840 case ImplicitConversionSequence::Indistinguishable:
7841 // Do nothing.
7842 break;
7843 }
7844 }
7845
Mike Stump1eb44332009-09-09 15:08:12 +00007846 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007847 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007848 if (HasBetterConversion)
7849 return true;
7850
Mike Stump1eb44332009-09-09 15:08:12 +00007851 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007852 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007853 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007854 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7855 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007856
7857 // -- F1 and F2 are function template specializations, and the function
7858 // template for F1 is more specialized than the template for F2
7859 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007860 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007861 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007862 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007863 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007864 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7865 Cand2.Function->getPrimaryTemplate(),
7866 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007867 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007868 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007869 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007870 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007871 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007872
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007873 // -- the context is an initialization by user-defined conversion
7874 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7875 // from the return type of F1 to the destination type (i.e.,
7876 // the type of the entity being initialized) is a better
7877 // conversion sequence than the standard conversion sequence
7878 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007879 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007880 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007881 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007882 // First check whether we prefer one of the conversion functions over the
7883 // other. This only distinguishes the results in non-standard, extension
7884 // cases such as the conversion from a lambda closure type to a function
7885 // pointer or block.
7886 ImplicitConversionSequence::CompareKind FuncResult
7887 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7888 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7889 return FuncResult;
7890
John McCall120d63c2010-08-24 20:38:10 +00007891 switch (CompareStandardConversionSequences(S,
7892 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007893 Cand2.FinalConversion)) {
7894 case ImplicitConversionSequence::Better:
7895 // Cand1 has a better conversion sequence.
7896 return true;
7897
7898 case ImplicitConversionSequence::Worse:
7899 // Cand1 can't be better than Cand2.
7900 return false;
7901
7902 case ImplicitConversionSequence::Indistinguishable:
7903 // Do nothing
7904 break;
7905 }
7906 }
7907
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007908 return false;
7909}
7910
Mike Stump1eb44332009-09-09 15:08:12 +00007911/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007912/// within an overload candidate set.
7913///
James Dennettefce31f2012-06-22 08:10:18 +00007914/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007915/// which overload resolution occurs.
7916///
James Dennettefce31f2012-06-22 08:10:18 +00007917/// \param Best If overload resolution was successful or found a deleted
7918/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007919///
7920/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007921OverloadingResult
7922OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007923 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007924 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007925 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007926 Best = end();
7927 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7928 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007929 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007930 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007931 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007932 }
7933
7934 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007935 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007936 return OR_No_Viable_Function;
7937
7938 // Make sure that this function is better than every other viable
7939 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007940 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007941 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007942 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007943 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007944 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007945 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007946 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007947 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007948 }
Mike Stump1eb44332009-09-09 15:08:12 +00007949
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007950 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007951 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007952 (Best->Function->isDeleted() ||
7953 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007954 return OR_Deleted;
7955
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007956 return OR_Success;
7957}
7958
John McCall3c80f572010-01-12 02:15:36 +00007959namespace {
7960
7961enum OverloadCandidateKind {
7962 oc_function,
7963 oc_method,
7964 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007965 oc_function_template,
7966 oc_method_template,
7967 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007968 oc_implicit_default_constructor,
7969 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007970 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007971 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007972 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007973 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007974};
7975
John McCall220ccbf2010-01-13 00:25:19 +00007976OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7977 FunctionDecl *Fn,
7978 std::string &Description) {
7979 bool isTemplate = false;
7980
7981 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7982 isTemplate = true;
7983 Description = S.getTemplateArgumentBindingsText(
7984 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7985 }
John McCallb1622a12010-01-06 09:43:14 +00007986
7987 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007988 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007989 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007990
Sebastian Redlf677ea32011-02-05 19:23:19 +00007991 if (Ctor->getInheritedConstructor())
7992 return oc_implicit_inherited_constructor;
7993
Sean Hunt82713172011-05-25 23:16:36 +00007994 if (Ctor->isDefaultConstructor())
7995 return oc_implicit_default_constructor;
7996
7997 if (Ctor->isMoveConstructor())
7998 return oc_implicit_move_constructor;
7999
8000 assert(Ctor->isCopyConstructor() &&
8001 "unexpected sort of implicit constructor");
8002 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008003 }
8004
8005 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8006 // This actually gets spelled 'candidate function' for now, but
8007 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008008 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008009 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008010
Sean Hunt82713172011-05-25 23:16:36 +00008011 if (Meth->isMoveAssignmentOperator())
8012 return oc_implicit_move_assignment;
8013
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008014 if (Meth->isCopyAssignmentOperator())
8015 return oc_implicit_copy_assignment;
8016
8017 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8018 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008019 }
8020
John McCall220ccbf2010-01-13 00:25:19 +00008021 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008022}
8023
Sebastian Redlf677ea32011-02-05 19:23:19 +00008024void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8025 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8026 if (!Ctor) return;
8027
8028 Ctor = Ctor->getInheritedConstructor();
8029 if (!Ctor) return;
8030
8031 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8032}
8033
John McCall3c80f572010-01-12 02:15:36 +00008034} // end anonymous namespace
8035
8036// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008037void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008038 std::string FnDesc;
8039 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008040 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8041 << (unsigned) K << FnDesc;
8042 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8043 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008044 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008045}
8046
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008047//Notes the location of all overload candidates designated through
8048// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008049void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008050 assert(OverloadedExpr->getType() == Context.OverloadTy);
8051
8052 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8053 OverloadExpr *OvlExpr = Ovl.Expression;
8054
8055 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8056 IEnd = OvlExpr->decls_end();
8057 I != IEnd; ++I) {
8058 if (FunctionTemplateDecl *FunTmpl =
8059 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008060 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008061 } else if (FunctionDecl *Fun
8062 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008063 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008064 }
8065 }
8066}
8067
John McCall1d318332010-01-12 00:44:57 +00008068/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8069/// "lead" diagnostic; it will be given two arguments, the source and
8070/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008071void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8072 Sema &S,
8073 SourceLocation CaretLoc,
8074 const PartialDiagnostic &PDiag) const {
8075 S.Diag(CaretLoc, PDiag)
8076 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008077 // FIXME: The note limiting machinery is borrowed from
8078 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8079 // refactoring here.
8080 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8081 unsigned CandsShown = 0;
8082 AmbiguousConversionSequence::const_iterator I, E;
8083 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8084 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8085 break;
8086 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008087 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008088 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008089 if (I != E)
8090 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008091}
8092
John McCall1d318332010-01-12 00:44:57 +00008093namespace {
8094
John McCalladbb8f82010-01-13 09:16:55 +00008095void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8096 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8097 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008098 assert(Cand->Function && "for now, candidate must be a function");
8099 FunctionDecl *Fn = Cand->Function;
8100
8101 // There's a conversion slot for the object argument if this is a
8102 // non-constructor method. Note that 'I' corresponds the
8103 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008104 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008105 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008106 if (I == 0)
8107 isObjectArgument = true;
8108 else
8109 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008110 }
8111
John McCall220ccbf2010-01-13 00:25:19 +00008112 std::string FnDesc;
8113 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8114
John McCalladbb8f82010-01-13 09:16:55 +00008115 Expr *FromExpr = Conv.Bad.FromExpr;
8116 QualType FromTy = Conv.Bad.getFromType();
8117 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008118
John McCall5920dbb2010-02-02 02:42:52 +00008119 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008120 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008121 Expr *E = FromExpr->IgnoreParens();
8122 if (isa<UnaryOperator>(E))
8123 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008124 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008125
8126 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8127 << (unsigned) FnKind << FnDesc
8128 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8129 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008130 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008131 return;
8132 }
8133
John McCall258b2032010-01-23 08:10:49 +00008134 // Do some hand-waving analysis to see if the non-viability is due
8135 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008136 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8137 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8138 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8139 CToTy = RT->getPointeeType();
8140 else {
8141 // TODO: detect and diagnose the full richness of const mismatches.
8142 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8143 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8144 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8145 }
8146
8147 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8148 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008149 Qualifiers FromQs = CFromTy.getQualifiers();
8150 Qualifiers ToQs = CToTy.getQualifiers();
8151
8152 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8153 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8154 << (unsigned) FnKind << FnDesc
8155 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8156 << FromTy
8157 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8158 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008159 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008160 return;
8161 }
8162
John McCallf85e1932011-06-15 23:02:42 +00008163 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008165 << (unsigned) FnKind << FnDesc
8166 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8167 << FromTy
8168 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8169 << (unsigned) isObjectArgument << I+1;
8170 MaybeEmitInheritedConstructorNote(S, Fn);
8171 return;
8172 }
8173
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008174 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8175 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8176 << (unsigned) FnKind << FnDesc
8177 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8178 << FromTy
8179 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8180 << (unsigned) isObjectArgument << I+1;
8181 MaybeEmitInheritedConstructorNote(S, Fn);
8182 return;
8183 }
8184
John McCall651f3ee2010-01-14 03:28:57 +00008185 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8186 assert(CVR && "unexpected qualifiers mismatch");
8187
8188 if (isObjectArgument) {
8189 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8190 << (unsigned) FnKind << FnDesc
8191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8192 << FromTy << (CVR - 1);
8193 } else {
8194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8195 << (unsigned) FnKind << FnDesc
8196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8197 << FromTy << (CVR - 1) << I+1;
8198 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008199 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008200 return;
8201 }
8202
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008203 // Special diagnostic for failure to convert an initializer list, since
8204 // telling the user that it has type void is not useful.
8205 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8207 << (unsigned) FnKind << FnDesc
8208 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8209 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8210 MaybeEmitInheritedConstructorNote(S, Fn);
8211 return;
8212 }
8213
John McCall258b2032010-01-23 08:10:49 +00008214 // Diagnose references or pointers to incomplete types differently,
8215 // since it's far from impossible that the incompleteness triggered
8216 // the failure.
8217 QualType TempFromTy = FromTy.getNonReferenceType();
8218 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8219 TempFromTy = PTy->getPointeeType();
8220 if (TempFromTy->isIncompleteType()) {
8221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8222 << (unsigned) FnKind << FnDesc
8223 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8224 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008225 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008226 return;
8227 }
8228
Douglas Gregor85789812010-06-30 23:01:39 +00008229 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008230 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008231 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8232 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8233 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8234 FromPtrTy->getPointeeType()) &&
8235 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8236 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008237 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008238 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008239 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008240 }
8241 } else if (const ObjCObjectPointerType *FromPtrTy
8242 = FromTy->getAs<ObjCObjectPointerType>()) {
8243 if (const ObjCObjectPointerType *ToPtrTy
8244 = ToTy->getAs<ObjCObjectPointerType>())
8245 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8246 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8247 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8248 FromPtrTy->getPointeeType()) &&
8249 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008250 BaseToDerivedConversion = 2;
8251 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008252 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8253 !FromTy->isIncompleteType() &&
8254 !ToRefTy->getPointeeType()->isIncompleteType() &&
8255 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8256 BaseToDerivedConversion = 3;
8257 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8258 ToTy.getNonReferenceType().getCanonicalType() ==
8259 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8261 << (unsigned) FnKind << FnDesc
8262 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8263 << (unsigned) isObjectArgument << I + 1;
8264 MaybeEmitInheritedConstructorNote(S, Fn);
8265 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008266 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008267 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008268
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008269 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008270 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008271 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008272 << (unsigned) FnKind << FnDesc
8273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008274 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008275 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008276 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008277 return;
8278 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008279
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008280 if (isa<ObjCObjectPointerType>(CFromTy) &&
8281 isa<PointerType>(CToTy)) {
8282 Qualifiers FromQs = CFromTy.getQualifiers();
8283 Qualifiers ToQs = CToTy.getQualifiers();
8284 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8286 << (unsigned) FnKind << FnDesc
8287 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8288 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8289 MaybeEmitInheritedConstructorNote(S, Fn);
8290 return;
8291 }
8292 }
8293
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008294 // Emit the generic diagnostic and, optionally, add the hints to it.
8295 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8296 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008297 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008298 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8299 << (unsigned) (Cand->Fix.Kind);
8300
8301 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008302 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8303 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008304 FDiag << *HI;
8305 S.Diag(Fn->getLocation(), FDiag);
8306
Sebastian Redlf677ea32011-02-05 19:23:19 +00008307 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008308}
8309
8310void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8311 unsigned NumFormalArgs) {
8312 // TODO: treat calls to a missing default constructor as a special case
8313
8314 FunctionDecl *Fn = Cand->Function;
8315 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8316
8317 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008318
Douglas Gregor439d3c32011-05-05 00:13:13 +00008319 // With invalid overloaded operators, it's possible that we think we
8320 // have an arity mismatch when it fact it looks like we have the
8321 // right number of arguments, because only overloaded operators have
8322 // the weird behavior of overloading member and non-member functions.
8323 // Just don't report anything.
8324 if (Fn->isInvalidDecl() &&
8325 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8326 return;
8327
John McCalladbb8f82010-01-13 09:16:55 +00008328 // at least / at most / exactly
8329 unsigned mode, modeCount;
8330 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008331 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8332 (Cand->FailureKind == ovl_fail_bad_deduction &&
8333 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008334 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008335 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008336 mode = 0; // "at least"
8337 else
8338 mode = 2; // "exactly"
8339 modeCount = MinParams;
8340 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008341 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8342 (Cand->FailureKind == ovl_fail_bad_deduction &&
8343 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008344 if (MinParams != FnTy->getNumArgs())
8345 mode = 1; // "at most"
8346 else
8347 mode = 2; // "exactly"
8348 modeCount = FnTy->getNumArgs();
8349 }
8350
8351 std::string Description;
8352 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8353
Richard Smithf7b80562012-05-11 05:16:41 +00008354 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8355 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8356 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8357 << Fn->getParamDecl(0) << NumFormalArgs;
8358 else
8359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8360 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8361 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008362 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008363}
8364
John McCall342fec42010-02-01 18:53:26 +00008365/// Diagnose a failed template-argument deduction.
8366void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008367 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008368 FunctionDecl *Fn = Cand->Function; // pattern
8369
Douglas Gregora9333192010-05-08 17:41:32 +00008370 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008371 NamedDecl *ParamD;
8372 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8373 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8374 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008375 switch (Cand->DeductionFailure.Result) {
8376 case Sema::TDK_Success:
8377 llvm_unreachable("TDK_success while diagnosing bad deduction");
8378
8379 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008380 assert(ParamD && "no parameter found for incomplete deduction result");
8381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8382 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008383 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008384 return;
8385 }
8386
John McCall57e97782010-08-05 09:05:08 +00008387 case Sema::TDK_Underqualified: {
8388 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8389 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8390
8391 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8392
8393 // Param will have been canonicalized, but it should just be a
8394 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008395 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008396 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008397 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008398 assert(S.Context.hasSameType(Param, NonCanonParam));
8399
8400 // Arg has also been canonicalized, but there's nothing we can do
8401 // about that. It also doesn't matter as much, because it won't
8402 // have any template parameters in it (because deduction isn't
8403 // done on dependent types).
8404 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8405
8406 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8407 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008408 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008409 return;
8410 }
8411
8412 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008413 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008414 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008415 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008416 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008417 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008418 which = 1;
8419 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008420 which = 2;
8421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008422
Douglas Gregora9333192010-05-08 17:41:32 +00008423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008424 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008425 << *Cand->DeductionFailure.getFirstArg()
8426 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008427 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008428 return;
8429 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008430
Douglas Gregorf1a84452010-05-08 19:15:54 +00008431 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008432 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008433 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008434 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008435 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8436 << ParamD->getDeclName();
8437 else {
8438 int index = 0;
8439 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8440 index = TTP->getIndex();
8441 else if (NonTypeTemplateParmDecl *NTTP
8442 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8443 index = NTTP->getIndex();
8444 else
8445 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008446 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008447 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8448 << (index + 1);
8449 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008450 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008451 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008452
Douglas Gregora18592e2010-05-08 18:13:28 +00008453 case Sema::TDK_TooManyArguments:
8454 case Sema::TDK_TooFewArguments:
8455 DiagnoseArityMismatch(S, Cand, NumArgs);
8456 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008457
8458 case Sema::TDK_InstantiationDepth:
8459 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008460 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008461 return;
8462
8463 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008464 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008465 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008466 if (TemplateArgumentList *Args =
8467 Cand->DeductionFailure.getTemplateArgumentList()) {
8468 TemplateArgString = " ";
8469 TemplateArgString += S.getTemplateArgumentBindingsText(
8470 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8471 }
8472
Richard Smith4493c0a2012-05-09 05:17:00 +00008473 // If this candidate was disabled by enable_if, say so.
8474 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8475 if (PDiag && PDiag->second.getDiagID() ==
8476 diag::err_typename_nested_not_found_enable_if) {
8477 // FIXME: Use the source range of the condition, and the fully-qualified
8478 // name of the enable_if template. These are both present in PDiag.
8479 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8480 << "'enable_if'" << TemplateArgString;
8481 return;
8482 }
8483
Richard Smithb8590f32012-05-07 09:03:25 +00008484 // Format the SFINAE diagnostic into the argument string.
8485 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8486 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008487 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008488 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008489 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008490 SFINAEArgString = ": ";
8491 R = SourceRange(PDiag->first, PDiag->first);
8492 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8493 }
8494
Douglas Gregorec20f462010-05-08 20:07:26 +00008495 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008496 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008497 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008498 return;
8499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008500
Richard Smith0efa62f2013-01-31 04:03:12 +00008501 case Sema::TDK_FailedOverloadResolution: {
8502 OverloadExpr::FindResult R =
8503 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8504 S.Diag(Fn->getLocation(),
8505 diag::note_ovl_candidate_failed_overload_resolution)
8506 << R.Expression->getName();
8507 return;
8508 }
8509
Richard Smith29805ca2013-01-31 05:19:49 +00008510 case Sema::TDK_NonDeducedMismatch:
8511 // FIXME: Provide a source location to indicate what we couldn't match.
8512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8513 << *Cand->DeductionFailure.getFirstArg()
8514 << *Cand->DeductionFailure.getSecondArg();
8515 return;
8516
John McCall342fec42010-02-01 18:53:26 +00008517 // TODO: diagnose these individually, then kill off
8518 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008519 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008521 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008522 return;
8523 }
8524}
8525
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008526/// CUDA: diagnose an invalid call across targets.
8527void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8528 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8529 FunctionDecl *Callee = Cand->Function;
8530
8531 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8532 CalleeTarget = S.IdentifyCUDATarget(Callee);
8533
8534 std::string FnDesc;
8535 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8536
8537 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8538 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8539}
8540
John McCall342fec42010-02-01 18:53:26 +00008541/// Generates a 'note' diagnostic for an overload candidate. We've
8542/// already generated a primary error at the call site.
8543///
8544/// It really does need to be a single diagnostic with its caret
8545/// pointed at the candidate declaration. Yes, this creates some
8546/// major challenges of technical writing. Yes, this makes pointing
8547/// out problems with specific arguments quite awkward. It's still
8548/// better than generating twenty screens of text for every failed
8549/// overload.
8550///
8551/// It would be great to be able to express per-candidate problems
8552/// more richly for those diagnostic clients that cared, but we'd
8553/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008554void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008555 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008556 FunctionDecl *Fn = Cand->Function;
8557
John McCall81201622010-01-08 04:41:39 +00008558 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008559 if (Cand->Viable && (Fn->isDeleted() ||
8560 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008561 std::string FnDesc;
8562 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008563
8564 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008565 << FnKind << FnDesc
8566 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008567 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008568 return;
John McCall81201622010-01-08 04:41:39 +00008569 }
8570
John McCall220ccbf2010-01-13 00:25:19 +00008571 // We don't really have anything else to say about viable candidates.
8572 if (Cand->Viable) {
8573 S.NoteOverloadCandidate(Fn);
8574 return;
8575 }
John McCall1d318332010-01-12 00:44:57 +00008576
John McCalladbb8f82010-01-13 09:16:55 +00008577 switch (Cand->FailureKind) {
8578 case ovl_fail_too_many_arguments:
8579 case ovl_fail_too_few_arguments:
8580 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008581
John McCalladbb8f82010-01-13 09:16:55 +00008582 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008583 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008584
John McCall717e8912010-01-23 05:17:32 +00008585 case ovl_fail_trivial_conversion:
8586 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008587 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008588 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008589
John McCallb1bdc622010-02-25 01:37:24 +00008590 case ovl_fail_bad_conversion: {
8591 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008592 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008593 if (Cand->Conversions[I].isBad())
8594 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008595
John McCalladbb8f82010-01-13 09:16:55 +00008596 // FIXME: this currently happens when we're called from SemaInit
8597 // when user-conversion overload fails. Figure out how to handle
8598 // those conditions and diagnose them well.
8599 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008600 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008601
8602 case ovl_fail_bad_target:
8603 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008604 }
John McCalla1d7d622010-01-08 00:58:21 +00008605}
8606
8607void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8608 // Desugar the type of the surrogate down to a function type,
8609 // retaining as many typedefs as possible while still showing
8610 // the function type (and, therefore, its parameter types).
8611 QualType FnType = Cand->Surrogate->getConversionType();
8612 bool isLValueReference = false;
8613 bool isRValueReference = false;
8614 bool isPointer = false;
8615 if (const LValueReferenceType *FnTypeRef =
8616 FnType->getAs<LValueReferenceType>()) {
8617 FnType = FnTypeRef->getPointeeType();
8618 isLValueReference = true;
8619 } else if (const RValueReferenceType *FnTypeRef =
8620 FnType->getAs<RValueReferenceType>()) {
8621 FnType = FnTypeRef->getPointeeType();
8622 isRValueReference = true;
8623 }
8624 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8625 FnType = FnTypePtr->getPointeeType();
8626 isPointer = true;
8627 }
8628 // Desugar down to a function type.
8629 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8630 // Reconstruct the pointer/reference as appropriate.
8631 if (isPointer) FnType = S.Context.getPointerType(FnType);
8632 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8633 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8634
8635 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8636 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008637 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008638}
8639
8640void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008641 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008642 SourceLocation OpLoc,
8643 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008644 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008645 std::string TypeStr("operator");
8646 TypeStr += Opc;
8647 TypeStr += "(";
8648 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008649 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008650 TypeStr += ")";
8651 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8652 } else {
8653 TypeStr += ", ";
8654 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8655 TypeStr += ")";
8656 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8657 }
8658}
8659
8660void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8661 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008662 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008663 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8664 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008665 if (ICS.isBad()) break; // all meaningless after first invalid
8666 if (!ICS.isAmbiguous()) continue;
8667
John McCall120d63c2010-08-24 20:38:10 +00008668 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008669 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008670 }
8671}
8672
John McCall1b77e732010-01-15 23:32:50 +00008673SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8674 if (Cand->Function)
8675 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008676 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008677 return Cand->Surrogate->getLocation();
8678 return SourceLocation();
8679}
8680
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008681static unsigned
8682RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008683 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008684 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008685 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008686
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008687 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008688 case Sema::TDK_Incomplete:
8689 return 1;
8690
8691 case Sema::TDK_Underqualified:
8692 case Sema::TDK_Inconsistent:
8693 return 2;
8694
8695 case Sema::TDK_SubstitutionFailure:
8696 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008697 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008698 return 3;
8699
8700 case Sema::TDK_InstantiationDepth:
8701 case Sema::TDK_FailedOverloadResolution:
8702 return 4;
8703
8704 case Sema::TDK_InvalidExplicitArguments:
8705 return 5;
8706
8707 case Sema::TDK_TooManyArguments:
8708 case Sema::TDK_TooFewArguments:
8709 return 6;
8710 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008711 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008712}
8713
John McCallbf65c0b2010-01-12 00:48:53 +00008714struct CompareOverloadCandidatesForDisplay {
8715 Sema &S;
8716 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008717
8718 bool operator()(const OverloadCandidate *L,
8719 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008720 // Fast-path this check.
8721 if (L == R) return false;
8722
John McCall81201622010-01-08 04:41:39 +00008723 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008724 if (L->Viable) {
8725 if (!R->Viable) return true;
8726
8727 // TODO: introduce a tri-valued comparison for overload
8728 // candidates. Would be more worthwhile if we had a sort
8729 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008730 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8731 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008732 } else if (R->Viable)
8733 return false;
John McCall81201622010-01-08 04:41:39 +00008734
John McCall1b77e732010-01-15 23:32:50 +00008735 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008736
John McCall1b77e732010-01-15 23:32:50 +00008737 // Criteria by which we can sort non-viable candidates:
8738 if (!L->Viable) {
8739 // 1. Arity mismatches come after other candidates.
8740 if (L->FailureKind == ovl_fail_too_many_arguments ||
8741 L->FailureKind == ovl_fail_too_few_arguments)
8742 return false;
8743 if (R->FailureKind == ovl_fail_too_many_arguments ||
8744 R->FailureKind == ovl_fail_too_few_arguments)
8745 return true;
John McCall81201622010-01-08 04:41:39 +00008746
John McCall717e8912010-01-23 05:17:32 +00008747 // 2. Bad conversions come first and are ordered by the number
8748 // of bad conversions and quality of good conversions.
8749 if (L->FailureKind == ovl_fail_bad_conversion) {
8750 if (R->FailureKind != ovl_fail_bad_conversion)
8751 return true;
8752
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008753 // The conversion that can be fixed with a smaller number of changes,
8754 // comes first.
8755 unsigned numLFixes = L->Fix.NumConversionsFixed;
8756 unsigned numRFixes = R->Fix.NumConversionsFixed;
8757 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8758 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008759 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008760 if (numLFixes < numRFixes)
8761 return true;
8762 else
8763 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008764 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008765
John McCall717e8912010-01-23 05:17:32 +00008766 // If there's any ordering between the defined conversions...
8767 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008768 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008769
8770 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008771 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008772 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008773 switch (CompareImplicitConversionSequences(S,
8774 L->Conversions[I],
8775 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008776 case ImplicitConversionSequence::Better:
8777 leftBetter++;
8778 break;
8779
8780 case ImplicitConversionSequence::Worse:
8781 leftBetter--;
8782 break;
8783
8784 case ImplicitConversionSequence::Indistinguishable:
8785 break;
8786 }
8787 }
8788 if (leftBetter > 0) return true;
8789 if (leftBetter < 0) return false;
8790
8791 } else if (R->FailureKind == ovl_fail_bad_conversion)
8792 return false;
8793
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008794 if (L->FailureKind == ovl_fail_bad_deduction) {
8795 if (R->FailureKind != ovl_fail_bad_deduction)
8796 return true;
8797
8798 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8799 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008800 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008801 } else if (R->FailureKind == ovl_fail_bad_deduction)
8802 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008803
John McCall1b77e732010-01-15 23:32:50 +00008804 // TODO: others?
8805 }
8806
8807 // Sort everything else by location.
8808 SourceLocation LLoc = GetLocationForCandidate(L);
8809 SourceLocation RLoc = GetLocationForCandidate(R);
8810
8811 // Put candidates without locations (e.g. builtins) at the end.
8812 if (LLoc.isInvalid()) return false;
8813 if (RLoc.isInvalid()) return true;
8814
8815 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008816 }
8817};
8818
John McCall717e8912010-01-23 05:17:32 +00008819/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008820/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008821void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008822 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008823 assert(!Cand->Viable);
8824
8825 // Don't do anything on failures other than bad conversion.
8826 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8827
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008828 // We only want the FixIts if all the arguments can be corrected.
8829 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008830 // Use a implicit copy initialization to check conversion fixes.
8831 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008832
John McCall717e8912010-01-23 05:17:32 +00008833 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008834 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008835 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008836 while (true) {
8837 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8838 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008839 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008840 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008841 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008842 }
John McCall717e8912010-01-23 05:17:32 +00008843 }
8844
8845 if (ConvIdx == ConvCount)
8846 return;
8847
John McCallb1bdc622010-02-25 01:37:24 +00008848 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8849 "remaining conversion is initialized?");
8850
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008851 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008852 // operation somehow.
8853 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008854
8855 const FunctionProtoType* Proto;
8856 unsigned ArgIdx = ConvIdx;
8857
8858 if (Cand->IsSurrogate) {
8859 QualType ConvType
8860 = Cand->Surrogate->getConversionType().getNonReferenceType();
8861 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8862 ConvType = ConvPtrType->getPointeeType();
8863 Proto = ConvType->getAs<FunctionProtoType>();
8864 ArgIdx--;
8865 } else if (Cand->Function) {
8866 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8867 if (isa<CXXMethodDecl>(Cand->Function) &&
8868 !isa<CXXConstructorDecl>(Cand->Function))
8869 ArgIdx--;
8870 } else {
8871 // Builtin binary operator with a bad first conversion.
8872 assert(ConvCount <= 3);
8873 for (; ConvIdx != ConvCount; ++ConvIdx)
8874 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008875 = TryCopyInitialization(S, Args[ConvIdx],
8876 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008877 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008878 /*InOverloadResolution*/ true,
8879 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008880 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008881 return;
8882 }
8883
8884 // Fill in the rest of the conversions.
8885 unsigned NumArgsInProto = Proto->getNumArgs();
8886 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008887 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008888 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008889 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008890 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008891 /*InOverloadResolution=*/true,
8892 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008893 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008894 // Store the FixIt in the candidate if it exists.
8895 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008896 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008897 }
John McCall717e8912010-01-23 05:17:32 +00008898 else
8899 Cand->Conversions[ConvIdx].setEllipsis();
8900 }
8901}
8902
John McCalla1d7d622010-01-08 00:58:21 +00008903} // end anonymous namespace
8904
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008905/// PrintOverloadCandidates - When overload resolution fails, prints
8906/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008907/// set.
John McCall120d63c2010-08-24 20:38:10 +00008908void OverloadCandidateSet::NoteCandidates(Sema &S,
8909 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008910 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008911 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008912 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008913 // Sort the candidates by viability and position. Sorting directly would
8914 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008915 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008916 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8917 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008918 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008919 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008920 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008921 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008922 if (Cand->Function || Cand->IsSurrogate)
8923 Cands.push_back(Cand);
8924 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8925 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008926 }
8927 }
8928
John McCallbf65c0b2010-01-12 00:48:53 +00008929 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008930 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008931
John McCall1d318332010-01-12 00:44:57 +00008932 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008933
Chris Lattner5f9e2722011-07-23 10:55:15 +00008934 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008935 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008936 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008937 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8938 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008939
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008940 // Set an arbitrary limit on the number of candidate functions we'll spam
8941 // the user with. FIXME: This limit should depend on details of the
8942 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008943 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008944 break;
8945 }
8946 ++CandsShown;
8947
John McCalla1d7d622010-01-08 00:58:21 +00008948 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008949 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008950 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008951 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008952 else {
8953 assert(Cand->Viable &&
8954 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008955 // Generally we only see ambiguities including viable builtin
8956 // operators if overload resolution got screwed up by an
8957 // ambiguous user-defined conversion.
8958 //
8959 // FIXME: It's quite possible for different conversions to see
8960 // different ambiguities, though.
8961 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008962 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008963 ReportedAmbiguousConversions = true;
8964 }
John McCalla1d7d622010-01-08 00:58:21 +00008965
John McCall1d318332010-01-12 00:44:57 +00008966 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008967 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008968 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008969 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008970
8971 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008972 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008973}
8974
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008975// [PossiblyAFunctionType] --> [Return]
8976// NonFunctionType --> NonFunctionType
8977// R (A) --> R(A)
8978// R (*)(A) --> R (A)
8979// R (&)(A) --> R (A)
8980// R (S::*)(A) --> R (A)
8981QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8982 QualType Ret = PossiblyAFunctionType;
8983 if (const PointerType *ToTypePtr =
8984 PossiblyAFunctionType->getAs<PointerType>())
8985 Ret = ToTypePtr->getPointeeType();
8986 else if (const ReferenceType *ToTypeRef =
8987 PossiblyAFunctionType->getAs<ReferenceType>())
8988 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008989 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008990 PossiblyAFunctionType->getAs<MemberPointerType>())
8991 Ret = MemTypePtr->getPointeeType();
8992 Ret =
8993 Context.getCanonicalType(Ret).getUnqualifiedType();
8994 return Ret;
8995}
Douglas Gregor904eed32008-11-10 20:40:00 +00008996
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008997// A helper class to help with address of function resolution
8998// - allows us to avoid passing around all those ugly parameters
8999class AddressOfFunctionResolver
9000{
9001 Sema& S;
9002 Expr* SourceExpr;
9003 const QualType& TargetType;
9004 QualType TargetFunctionType; // Extracted function type from target type
9005
9006 bool Complain;
9007 //DeclAccessPair& ResultFunctionAccessPair;
9008 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009009
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009010 bool TargetTypeIsNonStaticMemberFunction;
9011 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009012
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009013 OverloadExpr::FindResult OvlExprInfo;
9014 OverloadExpr *OvlExpr;
9015 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009016 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009017
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009018public:
9019 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9020 const QualType& TargetType, bool Complain)
9021 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9022 Complain(Complain), Context(S.getASTContext()),
9023 TargetTypeIsNonStaticMemberFunction(
9024 !!TargetType->getAs<MemberPointerType>()),
9025 FoundNonTemplateFunction(false),
9026 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9027 OvlExpr(OvlExprInfo.Expression)
9028 {
9029 ExtractUnqualifiedFunctionTypeFromTargetType();
9030
9031 if (!TargetFunctionType->isFunctionType()) {
9032 if (OvlExpr->hasExplicitTemplateArgs()) {
9033 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009034 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009035 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009036
9037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9038 if (!Method->isStatic()) {
9039 // If the target type is a non-function type and the function
9040 // found is a non-static member function, pretend as if that was
9041 // the target, it's the only possible type to end up with.
9042 TargetTypeIsNonStaticMemberFunction = true;
9043
9044 // And skip adding the function if its not in the proper form.
9045 // We'll diagnose this due to an empty set of functions.
9046 if (!OvlExprInfo.HasFormOfMemberPointer)
9047 return;
9048 }
9049 }
9050
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009051 Matches.push_back(std::make_pair(dap,Fn));
9052 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009053 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009054 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009055 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009056
9057 if (OvlExpr->hasExplicitTemplateArgs())
9058 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009059
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009060 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9061 // C++ [over.over]p4:
9062 // If more than one function is selected, [...]
9063 if (Matches.size() > 1) {
9064 if (FoundNonTemplateFunction)
9065 EliminateAllTemplateMatches();
9066 else
9067 EliminateAllExceptMostSpecializedTemplate();
9068 }
9069 }
9070 }
9071
9072private:
9073 bool isTargetTypeAFunction() const {
9074 return TargetFunctionType->isFunctionType();
9075 }
9076
9077 // [ToType] [Return]
9078
9079 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9080 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9081 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9082 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9083 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9084 }
9085
9086 // return true if any matching specializations were found
9087 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9088 const DeclAccessPair& CurAccessFunPair) {
9089 if (CXXMethodDecl *Method
9090 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9091 // Skip non-static function templates when converting to pointer, and
9092 // static when converting to member pointer.
9093 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9094 return false;
9095 }
9096 else if (TargetTypeIsNonStaticMemberFunction)
9097 return false;
9098
9099 // C++ [over.over]p2:
9100 // If the name is a function template, template argument deduction is
9101 // done (14.8.2.2), and if the argument deduction succeeds, the
9102 // resulting template argument list is used to generate a single
9103 // function template specialization, which is added to the set of
9104 // overloaded functions considered.
9105 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009106 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009107 if (Sema::TemplateDeductionResult Result
9108 = S.DeduceTemplateArguments(FunctionTemplate,
9109 &OvlExplicitTemplateArgs,
9110 TargetFunctionType, Specialization,
9111 Info)) {
9112 // FIXME: make a note of the failed deduction for diagnostics.
9113 (void)Result;
9114 return false;
9115 }
9116
9117 // Template argument deduction ensures that we have an exact match.
9118 // This function template specicalization works.
9119 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9120 assert(TargetFunctionType
9121 == Context.getCanonicalType(Specialization->getType()));
9122 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9123 return true;
9124 }
9125
9126 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9127 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009129 // Skip non-static functions when converting to pointer, and static
9130 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009131 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9132 return false;
9133 }
9134 else if (TargetTypeIsNonStaticMemberFunction)
9135 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009136
Chandler Carruthbd647292009-12-29 06:17:27 +00009137 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009138 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009139 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9140 if (S.CheckCUDATarget(Caller, FunDecl))
9141 return false;
9142
Douglas Gregor43c79c22009-12-09 00:47:37 +00009143 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009144 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9145 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009146 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9147 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009148 Matches.push_back(std::make_pair(CurAccessFunPair,
9149 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009150 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009151 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009152 }
Mike Stump1eb44332009-09-09 15:08:12 +00009153 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009154
9155 return false;
9156 }
9157
9158 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9159 bool Ret = false;
9160
9161 // If the overload expression doesn't have the form of a pointer to
9162 // member, don't try to convert it to a pointer-to-member type.
9163 if (IsInvalidFormOfPointerToMemberFunction())
9164 return false;
9165
9166 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9167 E = OvlExpr->decls_end();
9168 I != E; ++I) {
9169 // Look through any using declarations to find the underlying function.
9170 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9171
9172 // C++ [over.over]p3:
9173 // Non-member functions and static member functions match
9174 // targets of type "pointer-to-function" or "reference-to-function."
9175 // Nonstatic member functions match targets of
9176 // type "pointer-to-member-function."
9177 // Note that according to DR 247, the containing class does not matter.
9178 if (FunctionTemplateDecl *FunctionTemplate
9179 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9180 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9181 Ret = true;
9182 }
9183 // If we have explicit template arguments supplied, skip non-templates.
9184 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9185 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9186 Ret = true;
9187 }
9188 assert(Ret || Matches.empty());
9189 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009190 }
9191
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009192 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009193 // [...] and any given function template specialization F1 is
9194 // eliminated if the set contains a second function template
9195 // specialization whose function template is more specialized
9196 // than the function template of F1 according to the partial
9197 // ordering rules of 14.5.5.2.
9198
9199 // The algorithm specified above is quadratic. We instead use a
9200 // two-pass algorithm (similar to the one used to identify the
9201 // best viable function in an overload set) that identifies the
9202 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009203
9204 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9205 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9206 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009207
John McCallc373d482010-01-27 01:50:18 +00009208 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009209 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9210 TPOC_Other, 0, SourceExpr->getLocStart(),
9211 S.PDiag(),
9212 S.PDiag(diag::err_addr_ovl_ambiguous)
9213 << Matches[0].second->getDeclName(),
9214 S.PDiag(diag::note_ovl_candidate)
9215 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009216 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009217
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009218 if (Result != MatchesCopy.end()) {
9219 // Make it the first and only element
9220 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9221 Matches[0].second = cast<FunctionDecl>(*Result);
9222 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009223 }
9224 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009225
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009226 void EliminateAllTemplateMatches() {
9227 // [...] any function template specializations in the set are
9228 // eliminated if the set also contains a non-template function, [...]
9229 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9230 if (Matches[I].second->getPrimaryTemplate() == 0)
9231 ++I;
9232 else {
9233 Matches[I] = Matches[--N];
9234 Matches.set_size(N);
9235 }
9236 }
9237 }
9238
9239public:
9240 void ComplainNoMatchesFound() const {
9241 assert(Matches.empty());
9242 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9243 << OvlExpr->getName() << TargetFunctionType
9244 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009245 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009246 }
9247
9248 bool IsInvalidFormOfPointerToMemberFunction() const {
9249 return TargetTypeIsNonStaticMemberFunction &&
9250 !OvlExprInfo.HasFormOfMemberPointer;
9251 }
9252
9253 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9254 // TODO: Should we condition this on whether any functions might
9255 // have matched, or is it more appropriate to do that in callers?
9256 // TODO: a fixit wouldn't hurt.
9257 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9258 << TargetType << OvlExpr->getSourceRange();
9259 }
9260
9261 void ComplainOfInvalidConversion() const {
9262 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9263 << OvlExpr->getName() << TargetType;
9264 }
9265
9266 void ComplainMultipleMatchesFound() const {
9267 assert(Matches.size() > 1);
9268 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9269 << OvlExpr->getName()
9270 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009271 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009272 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009273
9274 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9275
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009276 int getNumMatches() const { return Matches.size(); }
9277
9278 FunctionDecl* getMatchingFunctionDecl() const {
9279 if (Matches.size() != 1) return 0;
9280 return Matches[0].second;
9281 }
9282
9283 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9284 if (Matches.size() != 1) return 0;
9285 return &Matches[0].first;
9286 }
9287};
9288
9289/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9290/// an overloaded function (C++ [over.over]), where @p From is an
9291/// expression with overloaded function type and @p ToType is the type
9292/// we're trying to resolve to. For example:
9293///
9294/// @code
9295/// int f(double);
9296/// int f(int);
9297///
9298/// int (*pfd)(double) = f; // selects f(double)
9299/// @endcode
9300///
9301/// This routine returns the resulting FunctionDecl if it could be
9302/// resolved, and NULL otherwise. When @p Complain is true, this
9303/// routine will emit diagnostics if there is an error.
9304FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009305Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9306 QualType TargetType,
9307 bool Complain,
9308 DeclAccessPair &FoundResult,
9309 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009310 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009311
9312 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9313 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009314 int NumMatches = Resolver.getNumMatches();
9315 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009316 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009317 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9318 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9319 else
9320 Resolver.ComplainNoMatchesFound();
9321 }
9322 else if (NumMatches > 1 && Complain)
9323 Resolver.ComplainMultipleMatchesFound();
9324 else if (NumMatches == 1) {
9325 Fn = Resolver.getMatchingFunctionDecl();
9326 assert(Fn);
9327 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009328 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009329 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009330 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009331
9332 if (pHadMultipleCandidates)
9333 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009334 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009335}
9336
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009337/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009338/// resolve that overloaded function expression down to a single function.
9339///
9340/// This routine can only resolve template-ids that refer to a single function
9341/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009342/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009343/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009344FunctionDecl *
9345Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9346 bool Complain,
9347 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009348 // C++ [over.over]p1:
9349 // [...] [Note: any redundant set of parentheses surrounding the
9350 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009351 // C++ [over.over]p1:
9352 // [...] The overloaded function name can be preceded by the &
9353 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009354
Douglas Gregor4b52e252009-12-21 23:17:24 +00009355 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009356 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009357 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009358
9359 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009360 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009361
Douglas Gregor4b52e252009-12-21 23:17:24 +00009362 // Look through all of the overloaded functions, searching for one
9363 // whose type matches exactly.
9364 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009365 for (UnresolvedSetIterator I = ovl->decls_begin(),
9366 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009367 // C++0x [temp.arg.explicit]p3:
9368 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009369 // where deduction is not done, if a template argument list is
9370 // specified and it, along with any default template arguments,
9371 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009372 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009373 FunctionTemplateDecl *FunctionTemplate
9374 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009375
Douglas Gregor4b52e252009-12-21 23:17:24 +00009376 // C++ [over.over]p2:
9377 // If the name is a function template, template argument deduction is
9378 // done (14.8.2.2), and if the argument deduction succeeds, the
9379 // resulting template argument list is used to generate a single
9380 // function template specialization, which is added to the set of
9381 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009382 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009383 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009384 if (TemplateDeductionResult Result
9385 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9386 Specialization, Info)) {
9387 // FIXME: make a note of the failed deduction for diagnostics.
9388 (void)Result;
9389 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009390 }
9391
John McCall864c0412011-04-26 20:42:42 +00009392 assert(Specialization && "no specialization and no error?");
9393
Douglas Gregor4b52e252009-12-21 23:17:24 +00009394 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009395 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009396 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009397 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9398 << ovl->getName();
9399 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009400 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009401 return 0;
John McCall864c0412011-04-26 20:42:42 +00009402 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009403
John McCall864c0412011-04-26 20:42:42 +00009404 Matched = Specialization;
9405 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009407
Douglas Gregor4b52e252009-12-21 23:17:24 +00009408 return Matched;
9409}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009410
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009411
9412
9413
John McCall6dbba4f2011-10-11 23:14:30 +00009414// Resolve and fix an overloaded expression that can be resolved
9415// because it identifies a single function template specialization.
9416//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009417// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009418//
9419// Return true if it was logically possible to so resolve the
9420// expression, regardless of whether or not it succeeded. Always
9421// returns true if 'complain' is set.
9422bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9423 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9424 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009425 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009426 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009427 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009428
John McCall6dbba4f2011-10-11 23:14:30 +00009429 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009430
John McCall864c0412011-04-26 20:42:42 +00009431 DeclAccessPair found;
9432 ExprResult SingleFunctionExpression;
9433 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9434 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009435 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009436 SrcExpr = ExprError();
9437 return true;
9438 }
John McCall864c0412011-04-26 20:42:42 +00009439
9440 // It is only correct to resolve to an instance method if we're
9441 // resolving a form that's permitted to be a pointer to member.
9442 // Otherwise we'll end up making a bound member expression, which
9443 // is illegal in all the contexts we resolve like this.
9444 if (!ovl.HasFormOfMemberPointer &&
9445 isa<CXXMethodDecl>(fn) &&
9446 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009447 if (!complain) return false;
9448
9449 Diag(ovl.Expression->getExprLoc(),
9450 diag::err_bound_member_function)
9451 << 0 << ovl.Expression->getSourceRange();
9452
9453 // TODO: I believe we only end up here if there's a mix of
9454 // static and non-static candidates (otherwise the expression
9455 // would have 'bound member' type, not 'overload' type).
9456 // Ideally we would note which candidate was chosen and why
9457 // the static candidates were rejected.
9458 SrcExpr = ExprError();
9459 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009460 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009461
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009462 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009463 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009464 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009465
9466 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009467 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009468 SingleFunctionExpression =
9469 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009470 if (SingleFunctionExpression.isInvalid()) {
9471 SrcExpr = ExprError();
9472 return true;
9473 }
9474 }
John McCall864c0412011-04-26 20:42:42 +00009475 }
9476
9477 if (!SingleFunctionExpression.isUsable()) {
9478 if (complain) {
9479 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9480 << ovl.Expression->getName()
9481 << DestTypeForComplaining
9482 << OpRangeForComplaining
9483 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009484 NoteAllOverloadCandidates(SrcExpr.get());
9485
9486 SrcExpr = ExprError();
9487 return true;
9488 }
9489
9490 return false;
John McCall864c0412011-04-26 20:42:42 +00009491 }
9492
John McCall6dbba4f2011-10-11 23:14:30 +00009493 SrcExpr = SingleFunctionExpression;
9494 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009495}
9496
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009497/// \brief Add a single candidate to the overload set.
9498static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009499 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009500 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009501 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009502 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009503 bool PartialOverloading,
9504 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009505 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009506 if (isa<UsingShadowDecl>(Callee))
9507 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9508
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009509 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009510 if (ExplicitTemplateArgs) {
9511 assert(!KnownValid && "Explicit template arguments?");
9512 return;
9513 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009514 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9515 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009516 return;
John McCallba135432009-11-21 08:51:07 +00009517 }
9518
9519 if (FunctionTemplateDecl *FuncTemplate
9520 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009521 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009522 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009523 return;
9524 }
9525
Richard Smith2ced0442011-06-26 22:19:54 +00009526 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009527}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009528
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009529/// \brief Add the overload candidates named by callee and/or found by argument
9530/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009531void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009532 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009533 OverloadCandidateSet &CandidateSet,
9534 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009535
9536#ifndef NDEBUG
9537 // Verify that ArgumentDependentLookup is consistent with the rules
9538 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009539 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009540 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9541 // and let Y be the lookup set produced by argument dependent
9542 // lookup (defined as follows). If X contains
9543 //
9544 // -- a declaration of a class member, or
9545 //
9546 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009547 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009548 //
9549 // -- a declaration that is neither a function or a function
9550 // template
9551 //
9552 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009553
John McCall3b4294e2009-12-16 12:17:52 +00009554 if (ULE->requiresADL()) {
9555 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9556 E = ULE->decls_end(); I != E; ++I) {
9557 assert(!(*I)->getDeclContext()->isRecord());
9558 assert(isa<UsingShadowDecl>(*I) ||
9559 !(*I)->getDeclContext()->isFunctionOrMethod());
9560 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009561 }
9562 }
9563#endif
9564
John McCall3b4294e2009-12-16 12:17:52 +00009565 // It would be nice to avoid this copy.
9566 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009567 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009568 if (ULE->hasExplicitTemplateArgs()) {
9569 ULE->copyTemplateArgumentsInto(TABuffer);
9570 ExplicitTemplateArgs = &TABuffer;
9571 }
9572
9573 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9574 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009575 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9576 CandidateSet, PartialOverloading,
9577 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009578
John McCall3b4294e2009-12-16 12:17:52 +00009579 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009580 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009581 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009582 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009583 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009584}
John McCall578b69b2009-12-16 08:11:27 +00009585
Richard Smithf50e88a2011-06-05 22:42:48 +00009586/// Attempt to recover from an ill-formed use of a non-dependent name in a
9587/// template, where the non-dependent name was declared after the template
9588/// was defined. This is common in code written for a compilers which do not
9589/// correctly implement two-stage name lookup.
9590///
9591/// Returns true if a viable candidate was found and a diagnostic was issued.
9592static bool
9593DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9594 const CXXScopeSpec &SS, LookupResult &R,
9595 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009596 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009597 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9598 return false;
9599
9600 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009601 if (DC->isTransparentContext())
9602 continue;
9603
Richard Smithf50e88a2011-06-05 22:42:48 +00009604 SemaRef.LookupQualifiedName(R, DC);
9605
9606 if (!R.empty()) {
9607 R.suppressDiagnostics();
9608
9609 if (isa<CXXRecordDecl>(DC)) {
9610 // Don't diagnose names we find in classes; we get much better
9611 // diagnostics for these from DiagnoseEmptyLookup.
9612 R.clear();
9613 return false;
9614 }
9615
9616 OverloadCandidateSet Candidates(FnLoc);
9617 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9618 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009619 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009620 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009621
9622 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009623 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009624 // No viable functions. Don't bother the user with notes for functions
9625 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009626 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009627 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009628 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009629
9630 // Find the namespaces where ADL would have looked, and suggest
9631 // declaring the function there instead.
9632 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9633 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009634 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009635 AssociatedNamespaces,
9636 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009637 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009638 DeclContext *Std = SemaRef.getStdNamespace();
9639 for (Sema::AssociatedNamespaceSet::iterator
9640 it = AssociatedNamespaces.begin(),
9641 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009642 // Never suggest declaring a function within namespace 'std'.
9643 if (Std && Std->Encloses(*it))
9644 continue;
9645
9646 // Never suggest declaring a function within a namespace with a reserved
9647 // name, like __gnu_cxx.
9648 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9649 if (NS &&
9650 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9651 continue;
9652
9653 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009654 }
9655
9656 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9657 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009658 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009659 SemaRef.Diag(Best->Function->getLocation(),
9660 diag::note_not_found_by_two_phase_lookup)
9661 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009662 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009663 SemaRef.Diag(Best->Function->getLocation(),
9664 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009665 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009666 } else {
9667 // FIXME: It would be useful to list the associated namespaces here,
9668 // but the diagnostics infrastructure doesn't provide a way to produce
9669 // a localized representation of a list of items.
9670 SemaRef.Diag(Best->Function->getLocation(),
9671 diag::note_not_found_by_two_phase_lookup)
9672 << R.getLookupName() << 2;
9673 }
9674
9675 // Try to recover by calling this function.
9676 return true;
9677 }
9678
9679 R.clear();
9680 }
9681
9682 return false;
9683}
9684
9685/// Attempt to recover from ill-formed use of a non-dependent operator in a
9686/// template, where the non-dependent operator was declared after the template
9687/// was defined.
9688///
9689/// Returns true if a viable candidate was found and a diagnostic was issued.
9690static bool
9691DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9692 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009693 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009694 DeclarationName OpName =
9695 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9696 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9697 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009698 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009699}
9700
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009701namespace {
9702// Callback to limit the allowed keywords and to only accept typo corrections
9703// that are keywords or whose decls refer to functions (or template functions)
9704// that accept the given number of arguments.
9705class RecoveryCallCCC : public CorrectionCandidateCallback {
9706 public:
9707 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9708 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009709 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009710 WantRemainingKeywords = false;
9711 }
9712
9713 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9714 if (!candidate.getCorrectionDecl())
9715 return candidate.isKeyword();
9716
9717 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9718 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9719 FunctionDecl *FD = 0;
9720 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9721 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9722 FD = FTD->getTemplatedDecl();
9723 if (!HasExplicitTemplateArgs && !FD) {
9724 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9725 // If the Decl is neither a function nor a template function,
9726 // determine if it is a pointer or reference to a function. If so,
9727 // check against the number of arguments expected for the pointee.
9728 QualType ValType = cast<ValueDecl>(ND)->getType();
9729 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9730 ValType = ValType->getPointeeType();
9731 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9732 if (FPT->getNumArgs() == NumArgs)
9733 return true;
9734 }
9735 }
9736 if (FD && FD->getNumParams() >= NumArgs &&
9737 FD->getMinRequiredArguments() <= NumArgs)
9738 return true;
9739 }
9740 return false;
9741 }
9742
9743 private:
9744 unsigned NumArgs;
9745 bool HasExplicitTemplateArgs;
9746};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009747
9748// Callback that effectively disabled typo correction
9749class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9750 public:
9751 NoTypoCorrectionCCC() {
9752 WantTypeSpecifiers = false;
9753 WantExpressionKeywords = false;
9754 WantCXXNamedCasts = false;
9755 WantRemainingKeywords = false;
9756 }
9757
9758 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9759 return false;
9760 }
9761};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009762
9763class BuildRecoveryCallExprRAII {
9764 Sema &SemaRef;
9765public:
9766 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9767 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9768 SemaRef.IsBuildingRecoveryCallExpr = true;
9769 }
9770
9771 ~BuildRecoveryCallExprRAII() {
9772 SemaRef.IsBuildingRecoveryCallExpr = false;
9773 }
9774};
9775
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009776}
9777
John McCall578b69b2009-12-16 08:11:27 +00009778/// Attempts to recover from a call where no functions were found.
9779///
9780/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009781static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009782BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009783 UnresolvedLookupExpr *ULE,
9784 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009785 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009786 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009787 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009788 // Do not try to recover if it is already building a recovery call.
9789 // This stops infinite loops for template instantiations like
9790 //
9791 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9792 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9793 //
9794 if (SemaRef.IsBuildingRecoveryCallExpr)
9795 return ExprError();
9796 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009797
9798 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009799 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009800 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009801
John McCall3b4294e2009-12-16 12:17:52 +00009802 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009803 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009804 if (ULE->hasExplicitTemplateArgs()) {
9805 ULE->copyTemplateArgumentsInto(TABuffer);
9806 ExplicitTemplateArgs = &TABuffer;
9807 }
9808
John McCall578b69b2009-12-16 08:11:27 +00009809 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9810 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009811 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009812 NoTypoCorrectionCCC RejectAll;
9813 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9814 (CorrectionCandidateCallback*)&Validator :
9815 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009816 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009817 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009818 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009819 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009820 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009821 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009822
John McCall3b4294e2009-12-16 12:17:52 +00009823 assert(!R.empty() && "lookup results empty despite recovery");
9824
9825 // Build an implicit member call if appropriate. Just drop the
9826 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009827 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009828 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009829 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9830 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009831 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009832 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009833 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009834 else
9835 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9836
9837 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009838 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009839
9840 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009841 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009842 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009843 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009844 MultiExprArg(Args.data(), Args.size()),
9845 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009846}
Douglas Gregord7a95972010-06-08 17:35:15 +00009847
Sam Panzere1715b62012-08-21 00:52:01 +00009848/// \brief Constructs and populates an OverloadedCandidateSet from
9849/// the given function.
9850/// \returns true when an the ExprResult output parameter has been set.
9851bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9852 UnresolvedLookupExpr *ULE,
9853 Expr **Args, unsigned NumArgs,
9854 SourceLocation RParenLoc,
9855 OverloadCandidateSet *CandidateSet,
9856 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009857#ifndef NDEBUG
9858 if (ULE->requiresADL()) {
9859 // To do ADL, we must have found an unqualified name.
9860 assert(!ULE->getQualifier() && "qualified name with ADL");
9861
9862 // We don't perform ADL for implicit declarations of builtins.
9863 // Verify that this was correctly set up.
9864 FunctionDecl *F;
9865 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9866 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9867 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009868 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009869
John McCall3b4294e2009-12-16 12:17:52 +00009870 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009871 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009872 }
John McCall3b4294e2009-12-16 12:17:52 +00009873#endif
9874
John McCall5acb0c92011-10-17 18:40:02 +00009875 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009876 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9877 *Result = ExprError();
9878 return true;
9879 }
Douglas Gregor17330012009-02-04 15:01:18 +00009880
John McCall3b4294e2009-12-16 12:17:52 +00009881 // Add the functions denoted by the callee to the set of candidate
9882 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009883 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009884 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009885
9886 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009887 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9888 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009889 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009890 // In Microsoft mode, if we are inside a template class member function then
9891 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009892 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009893 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009894 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009895 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009896 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9897 llvm::makeArrayRef(Args, NumArgs),
9898 Context.DependentTy, VK_RValue,
9899 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009900 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009901 *Result = Owned(CE);
9902 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009903 }
Sam Panzere1715b62012-08-21 00:52:01 +00009904 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009905 }
John McCall578b69b2009-12-16 08:11:27 +00009906
John McCall5acb0c92011-10-17 18:40:02 +00009907 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009908 return false;
9909}
John McCall5acb0c92011-10-17 18:40:02 +00009910
Sam Panzere1715b62012-08-21 00:52:01 +00009911/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9912/// the completed call expression. If overload resolution fails, emits
9913/// diagnostics and returns ExprError()
9914static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9915 UnresolvedLookupExpr *ULE,
9916 SourceLocation LParenLoc,
9917 Expr **Args, unsigned NumArgs,
9918 SourceLocation RParenLoc,
9919 Expr *ExecConfig,
9920 OverloadCandidateSet *CandidateSet,
9921 OverloadCandidateSet::iterator *Best,
9922 OverloadingResult OverloadResult,
9923 bool AllowTypoCorrection) {
9924 if (CandidateSet->empty())
9925 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9926 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9927 RParenLoc, /*EmptyLookup=*/true,
9928 AllowTypoCorrection);
9929
9930 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009931 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009932 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +00009933 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9934 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9935 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9936 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9937 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009938 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009939
Richard Smithf50e88a2011-06-05 22:42:48 +00009940 case OR_No_Viable_Function: {
9941 // Try to recover by looking for viable functions which the user might
9942 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009943 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009944 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9945 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009946 /*EmptyLookup=*/false,
9947 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009948 if (!Recovery.isInvalid())
9949 return Recovery;
9950
Sam Panzere1715b62012-08-21 00:52:01 +00009951 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009952 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009953 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009954 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9955 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009956 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009957 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009958
9959 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009960 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009961 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009962 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9963 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009964 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009965
Sam Panzere1715b62012-08-21 00:52:01 +00009966 case OR_Deleted: {
9967 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9968 << (*Best)->Function->isDeleted()
9969 << ULE->getName()
9970 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9971 << Fn->getSourceRange();
9972 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9973 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009974
Sam Panzere1715b62012-08-21 00:52:01 +00009975 // We emitted an error for the unvailable/deleted function call but keep
9976 // the call in the AST.
9977 FunctionDecl *FDecl = (*Best)->Function;
9978 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9979 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9980 RParenLoc, ExecConfig);
9981 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009982 }
9983
Douglas Gregorff331c12010-07-25 18:17:45 +00009984 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009985 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009986}
9987
Sam Panzere1715b62012-08-21 00:52:01 +00009988/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9989/// (which eventually refers to the declaration Func) and the call
9990/// arguments Args/NumArgs, attempt to resolve the function call down
9991/// to a specific function. If overload resolution succeeds, returns
9992/// the call expression produced by overload resolution.
9993/// Otherwise, emits diagnostics and returns ExprError.
9994ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9995 UnresolvedLookupExpr *ULE,
9996 SourceLocation LParenLoc,
9997 Expr **Args, unsigned NumArgs,
9998 SourceLocation RParenLoc,
9999 Expr *ExecConfig,
10000 bool AllowTypoCorrection) {
10001 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10002 ExprResult result;
10003
10004 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
10005 &CandidateSet, &result))
10006 return result;
10007
10008 OverloadCandidateSet::iterator Best;
10009 OverloadingResult OverloadResult =
10010 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10011
10012 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
10013 RParenLoc, ExecConfig, &CandidateSet,
10014 &Best, OverloadResult,
10015 AllowTypoCorrection);
10016}
10017
John McCall6e266892010-01-26 03:27:55 +000010018static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010019 return Functions.size() > 1 ||
10020 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10021}
10022
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010023/// \brief Create a unary operation that may resolve to an overloaded
10024/// operator.
10025///
10026/// \param OpLoc The location of the operator itself (e.g., '*').
10027///
10028/// \param OpcIn The UnaryOperator::Opcode that describes this
10029/// operator.
10030///
James Dennett40ae6662012-06-22 08:52:37 +000010031/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010032/// considered by overload resolution. The caller needs to build this
10033/// set based on the context using, e.g.,
10034/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10035/// set should not contain any member functions; those will be added
10036/// by CreateOverloadedUnaryOp().
10037///
James Dennett8da16872012-06-22 10:32:46 +000010038/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010039ExprResult
John McCall6e266892010-01-26 03:27:55 +000010040Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10041 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010042 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010043 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010044
10045 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10046 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10047 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010048 // TODO: provide better source location info.
10049 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010050
John McCall5acb0c92011-10-17 18:40:02 +000010051 if (checkPlaceholderForOverload(*this, Input))
10052 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010053
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010054 Expr *Args[2] = { Input, 0 };
10055 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010056
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010057 // For post-increment and post-decrement, add the implicit '0' as
10058 // the second argument, so that we know this is a post-increment or
10059 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010060 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010061 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010062 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10063 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010064 NumArgs = 2;
10065 }
10066
10067 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010068 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010069 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010070 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010071 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010072 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010073 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010074
John McCallc373d482010-01-27 01:50:18 +000010075 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010076 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010077 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010078 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010079 /*ADL*/ true, IsOverloaded(Fns),
10080 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010081 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010082 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010083 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010084 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010085 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010086 }
10087
10088 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010089 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010090
10091 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010092 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10093 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010094
10095 // Add operator candidates that are member functions.
10096 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10097
John McCall6e266892010-01-26 03:27:55 +000010098 // Add candidates from ADL.
10099 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010100 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010101 /*ExplicitTemplateArgs*/ 0,
10102 CandidateSet);
10103
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010104 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010105 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010106
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010107 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10108
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010109 // Perform overload resolution.
10110 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010111 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010112 case OR_Success: {
10113 // We found a built-in operator or an overloaded operator.
10114 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010115
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010116 if (FnDecl) {
10117 // We matched an overloaded operator. Build a call to that
10118 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010119
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010120 // Convert the arguments.
10121 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010122 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010123
John Wiegley429bb272011-04-08 18:41:53 +000010124 ExprResult InputRes =
10125 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10126 Best->FoundDecl, Method);
10127 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010128 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010129 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010130 } else {
10131 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010132 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010133 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010134 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010135 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010136 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010137 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010138 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010139 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010140 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010141 }
10142
John McCallf89e55a2010-11-18 06:31:45 +000010143 // Determine the result type.
10144 QualType ResultTy = FnDecl->getResultType();
10145 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10146 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010147
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010148 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010149 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010150 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010151 if (FnExpr.isInvalid())
10152 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010153
Eli Friedman4c3b8962009-11-18 03:58:17 +000010154 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010155 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010156 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010157 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010158 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010159
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010160 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010161 FnDecl))
10162 return ExprError();
10163
John McCall9ae2f072010-08-23 23:25:46 +000010164 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010165 } else {
10166 // We matched a built-in operator. Convert the arguments, then
10167 // break out so that we will build the appropriate built-in
10168 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010169 ExprResult InputRes =
10170 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10171 Best->Conversions[0], AA_Passing);
10172 if (InputRes.isInvalid())
10173 return ExprError();
10174 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010175 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010176 }
John Wiegley429bb272011-04-08 18:41:53 +000010177 }
10178
10179 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010180 // This is an erroneous use of an operator which can be overloaded by
10181 // a non-member function. Check for non-member operators which were
10182 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010183 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10184 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010185 // FIXME: Recover by calling the found function.
10186 return ExprError();
10187
John Wiegley429bb272011-04-08 18:41:53 +000010188 // No viable function; fall through to handling this as a
10189 // built-in operator, which will produce an error message for us.
10190 break;
10191
10192 case OR_Ambiguous:
10193 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10194 << UnaryOperator::getOpcodeStr(Opc)
10195 << Input->getType()
10196 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010197 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10198 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010199 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10200 return ExprError();
10201
10202 case OR_Deleted:
10203 Diag(OpLoc, diag::err_ovl_deleted_oper)
10204 << Best->Function->isDeleted()
10205 << UnaryOperator::getOpcodeStr(Opc)
10206 << getDeletedOrUnavailableSuffix(Best->Function)
10207 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010208 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10209 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010210 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010211 return ExprError();
10212 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010213
10214 // Either we found no viable overloaded operator or we matched a
10215 // built-in operator. In either case, fall through to trying to
10216 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010217 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010218}
10219
Douglas Gregor063daf62009-03-13 18:40:31 +000010220/// \brief Create a binary operation that may resolve to an overloaded
10221/// operator.
10222///
10223/// \param OpLoc The location of the operator itself (e.g., '+').
10224///
10225/// \param OpcIn The BinaryOperator::Opcode that describes this
10226/// operator.
10227///
James Dennett40ae6662012-06-22 08:52:37 +000010228/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010229/// considered by overload resolution. The caller needs to build this
10230/// set based on the context using, e.g.,
10231/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10232/// set should not contain any member functions; those will be added
10233/// by CreateOverloadedBinOp().
10234///
10235/// \param LHS Left-hand argument.
10236/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010237ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010238Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010239 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010240 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010241 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010242 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010243 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010244
10245 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10246 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10247 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10248
10249 // If either side is type-dependent, create an appropriate dependent
10250 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010251 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010252 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010253 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010254 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010255 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010256 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010257 Context.DependentTy,
10258 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010259 OpLoc,
10260 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010261
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010262 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10263 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010264 VK_LValue,
10265 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010266 Context.DependentTy,
10267 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010268 OpLoc,
10269 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010270 }
John McCall6e266892010-01-26 03:27:55 +000010271
10272 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010273 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010274 // TODO: provide better source location info in DNLoc component.
10275 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010276 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010277 = UnresolvedLookupExpr::Create(Context, NamingClass,
10278 NestedNameSpecifierLoc(), OpNameInfo,
10279 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010280 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010281 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10282 Context.DependentTy, VK_RValue,
10283 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010284 }
10285
John McCall5acb0c92011-10-17 18:40:02 +000010286 // Always do placeholder-like conversions on the RHS.
10287 if (checkPlaceholderForOverload(*this, Args[1]))
10288 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010289
John McCall3c3b7f92011-10-25 17:37:35 +000010290 // Do placeholder-like conversion on the LHS; note that we should
10291 // not get here with a PseudoObject LHS.
10292 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010293 if (checkPlaceholderForOverload(*this, Args[0]))
10294 return ExprError();
10295
Sebastian Redl275c2b42009-11-18 23:10:33 +000010296 // If this is the assignment operator, we only perform overload resolution
10297 // if the left-hand side is a class or enumeration type. This is actually
10298 // a hack. The standard requires that we do overload resolution between the
10299 // various built-in candidates, but as DR507 points out, this can lead to
10300 // problems. So we do it this way, which pretty much follows what GCC does.
10301 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010302 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010303 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010304
John McCall0e800c92010-12-04 08:14:53 +000010305 // If this is the .* operator, which is not overloadable, just
10306 // create a built-in binary operator.
10307 if (Opc == BO_PtrMemD)
10308 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10309
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010310 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010311 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010312
10313 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010314 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010315
10316 // Add operator candidates that are member functions.
10317 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10318
John McCall6e266892010-01-26 03:27:55 +000010319 // Add candidates from ADL.
10320 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010321 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010322 /*ExplicitTemplateArgs*/ 0,
10323 CandidateSet);
10324
Douglas Gregor063daf62009-03-13 18:40:31 +000010325 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010326 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010327
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10329
Douglas Gregor063daf62009-03-13 18:40:31 +000010330 // Perform overload resolution.
10331 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010332 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010333 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010334 // We found a built-in operator or an overloaded operator.
10335 FunctionDecl *FnDecl = Best->Function;
10336
10337 if (FnDecl) {
10338 // We matched an overloaded operator. Build a call to that
10339 // operator.
10340
10341 // Convert the arguments.
10342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010343 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010344 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010345
Chandler Carruth6df868e2010-12-12 08:17:55 +000010346 ExprResult Arg1 =
10347 PerformCopyInitialization(
10348 InitializedEntity::InitializeParameter(Context,
10349 FnDecl->getParamDecl(0)),
10350 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010351 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010352 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010353
John Wiegley429bb272011-04-08 18:41:53 +000010354 ExprResult Arg0 =
10355 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10356 Best->FoundDecl, Method);
10357 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010358 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010359 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010360 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010361 } else {
10362 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010363 ExprResult Arg0 = PerformCopyInitialization(
10364 InitializedEntity::InitializeParameter(Context,
10365 FnDecl->getParamDecl(0)),
10366 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010367 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010368 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010369
Chandler Carruth6df868e2010-12-12 08:17:55 +000010370 ExprResult Arg1 =
10371 PerformCopyInitialization(
10372 InitializedEntity::InitializeParameter(Context,
10373 FnDecl->getParamDecl(1)),
10374 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010375 if (Arg1.isInvalid())
10376 return ExprError();
10377 Args[0] = LHS = Arg0.takeAs<Expr>();
10378 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010379 }
10380
John McCallf89e55a2010-11-18 06:31:45 +000010381 // Determine the result type.
10382 QualType ResultTy = FnDecl->getResultType();
10383 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10384 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010385
10386 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010387 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010388 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010389 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010390 if (FnExpr.isInvalid())
10391 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010392
John McCall9ae2f072010-08-23 23:25:46 +000010393 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010394 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010395 Args, ResultTy, VK, OpLoc,
10396 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010397
10398 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010399 FnDecl))
10400 return ExprError();
10401
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010402 ArrayRef<const Expr *> ArgsArray(Args, 2);
10403 // Cut off the implicit 'this'.
10404 if (isa<CXXMethodDecl>(FnDecl))
10405 ArgsArray = ArgsArray.slice(1);
10406 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10407 TheCall->getSourceRange(), VariadicDoesNotApply);
10408
John McCall9ae2f072010-08-23 23:25:46 +000010409 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010410 } else {
10411 // We matched a built-in operator. Convert the arguments, then
10412 // break out so that we will build the appropriate built-in
10413 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010414 ExprResult ArgsRes0 =
10415 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10416 Best->Conversions[0], AA_Passing);
10417 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010418 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010419 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010420
John Wiegley429bb272011-04-08 18:41:53 +000010421 ExprResult ArgsRes1 =
10422 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10423 Best->Conversions[1], AA_Passing);
10424 if (ArgsRes1.isInvalid())
10425 return ExprError();
10426 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010427 break;
10428 }
10429 }
10430
Douglas Gregor33074752009-09-30 21:46:01 +000010431 case OR_No_Viable_Function: {
10432 // C++ [over.match.oper]p9:
10433 // If the operator is the operator , [...] and there are no
10434 // viable functions, then the operator is assumed to be the
10435 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010436 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010437 break;
10438
Chandler Carruth6df868e2010-12-12 08:17:55 +000010439 // For class as left operand for assignment or compound assigment
10440 // operator do not fall through to handling in built-in, but report that
10441 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010442 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010443 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010444 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010445 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10446 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010447 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010448 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010449 // This is an erroneous use of an operator which can be overloaded by
10450 // a non-member function. Check for non-member operators which were
10451 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010452 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010453 // FIXME: Recover by calling the found function.
10454 return ExprError();
10455
Douglas Gregor33074752009-09-30 21:46:01 +000010456 // No viable function; try to create a built-in operation, which will
10457 // produce an error. Then, show the non-viable candidates.
10458 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010460 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010461 "C++ binary operator overloading is missing candidates!");
10462 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010463 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010464 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010465 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010466 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010467
10468 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010469 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010470 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010471 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010472 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010473 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010474 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010475 return ExprError();
10476
10477 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010478 if (isImplicitlyDeleted(Best->Function)) {
10479 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10480 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010481 << Context.getRecordType(Method->getParent())
10482 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010483
Richard Smith0f46e642012-12-28 12:23:24 +000010484 // The user probably meant to call this special member. Just
10485 // explain why it's deleted.
10486 NoteDeletedFunction(Method);
10487 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010488 } else {
10489 Diag(OpLoc, diag::err_ovl_deleted_oper)
10490 << Best->Function->isDeleted()
10491 << BinaryOperator::getOpcodeStr(Opc)
10492 << getDeletedOrUnavailableSuffix(Best->Function)
10493 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10494 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010495 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010496 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010497 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010498 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010499
Douglas Gregor33074752009-09-30 21:46:01 +000010500 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010501 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010502}
10503
John McCall60d7b3a2010-08-24 06:29:42 +000010504ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010505Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10506 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010507 Expr *Base, Expr *Idx) {
10508 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010509 DeclarationName OpName =
10510 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10511
10512 // If either side is type-dependent, create an appropriate dependent
10513 // expression.
10514 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10515
John McCallc373d482010-01-27 01:50:18 +000010516 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010517 // CHECKME: no 'operator' keyword?
10518 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10519 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010520 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010521 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010522 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010523 /*ADL*/ true, /*Overloaded*/ false,
10524 UnresolvedSetIterator(),
10525 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010526 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010527
Sebastian Redlf322ed62009-10-29 20:17:01 +000010528 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010529 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010530 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010531 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010532 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010533 }
10534
John McCall5acb0c92011-10-17 18:40:02 +000010535 // Handle placeholders on both operands.
10536 if (checkPlaceholderForOverload(*this, Args[0]))
10537 return ExprError();
10538 if (checkPlaceholderForOverload(*this, Args[1]))
10539 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010540
Sebastian Redlf322ed62009-10-29 20:17:01 +000010541 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010542 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010543
10544 // Subscript can only be overloaded as a member function.
10545
10546 // Add operator candidates that are member functions.
10547 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10548
10549 // Add builtin operator candidates.
10550 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10551
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010552 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10553
Sebastian Redlf322ed62009-10-29 20:17:01 +000010554 // Perform overload resolution.
10555 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010556 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010557 case OR_Success: {
10558 // We found a built-in operator or an overloaded operator.
10559 FunctionDecl *FnDecl = Best->Function;
10560
10561 if (FnDecl) {
10562 // We matched an overloaded operator. Build a call to that
10563 // operator.
10564
John McCall9aa472c2010-03-19 07:35:19 +000010565 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010566
Sebastian Redlf322ed62009-10-29 20:17:01 +000010567 // Convert the arguments.
10568 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010569 ExprResult Arg0 =
10570 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10571 Best->FoundDecl, Method);
10572 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010573 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010574 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010575
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010576 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010577 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010578 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010579 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010580 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010581 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010582 Owned(Args[1]));
10583 if (InputInit.isInvalid())
10584 return ExprError();
10585
10586 Args[1] = InputInit.takeAs<Expr>();
10587
Sebastian Redlf322ed62009-10-29 20:17:01 +000010588 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010589 QualType ResultTy = FnDecl->getResultType();
10590 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10591 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010592
10593 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010594 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10595 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010596 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010597 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010598 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010599 OpLocInfo.getLoc(),
10600 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010601 if (FnExpr.isInvalid())
10602 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010603
John McCall9ae2f072010-08-23 23:25:46 +000010604 CXXOperatorCallExpr *TheCall =
10605 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010606 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010607 ResultTy, VK, RLoc,
10608 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010609
John McCall9ae2f072010-08-23 23:25:46 +000010610 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010611 FnDecl))
10612 return ExprError();
10613
John McCall9ae2f072010-08-23 23:25:46 +000010614 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010615 } else {
10616 // We matched a built-in operator. Convert the arguments, then
10617 // break out so that we will build the appropriate built-in
10618 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010619 ExprResult ArgsRes0 =
10620 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10621 Best->Conversions[0], AA_Passing);
10622 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010623 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010624 Args[0] = ArgsRes0.take();
10625
10626 ExprResult ArgsRes1 =
10627 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10628 Best->Conversions[1], AA_Passing);
10629 if (ArgsRes1.isInvalid())
10630 return ExprError();
10631 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010632
10633 break;
10634 }
10635 }
10636
10637 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010638 if (CandidateSet.empty())
10639 Diag(LLoc, diag::err_ovl_no_oper)
10640 << Args[0]->getType() << /*subscript*/ 0
10641 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10642 else
10643 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10644 << Args[0]->getType()
10645 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010646 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010647 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010648 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010649 }
10650
10651 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010652 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010653 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010654 << Args[0]->getType() << Args[1]->getType()
10655 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010656 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010657 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010658 return ExprError();
10659
10660 case OR_Deleted:
10661 Diag(LLoc, diag::err_ovl_deleted_oper)
10662 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010663 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010664 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010665 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010666 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010667 return ExprError();
10668 }
10669
10670 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010671 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010672}
10673
Douglas Gregor88a35142008-12-22 05:46:06 +000010674/// BuildCallToMemberFunction - Build a call to a member
10675/// function. MemExpr is the expression that refers to the member
10676/// function (and includes the object parameter), Args/NumArgs are the
10677/// arguments to the function call (not including the object
10678/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010679/// expression refers to a non-static member function or an overloaded
10680/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010681ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010682Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10683 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010684 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010685 assert(MemExprE->getType() == Context.BoundMemberTy ||
10686 MemExprE->getType() == Context.OverloadTy);
10687
Douglas Gregor88a35142008-12-22 05:46:06 +000010688 // Dig out the member expression. This holds both the object
10689 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010690 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010691
John McCall864c0412011-04-26 20:42:42 +000010692 // Determine whether this is a call to a pointer-to-member function.
10693 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10694 assert(op->getType() == Context.BoundMemberTy);
10695 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10696
10697 QualType fnType =
10698 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10699
10700 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10701 QualType resultType = proto->getCallResultType(Context);
10702 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10703
10704 // Check that the object type isn't more qualified than the
10705 // member function we're calling.
10706 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10707
10708 QualType objectType = op->getLHS()->getType();
10709 if (op->getOpcode() == BO_PtrMemI)
10710 objectType = objectType->castAs<PointerType>()->getPointeeType();
10711 Qualifiers objectQuals = objectType.getQualifiers();
10712
10713 Qualifiers difference = objectQuals - funcQuals;
10714 difference.removeObjCGCAttr();
10715 difference.removeAddressSpace();
10716 if (difference) {
10717 std::string qualsString = difference.getAsString();
10718 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10719 << fnType.getUnqualifiedType()
10720 << qualsString
10721 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10722 }
10723
10724 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010725 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10726 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010727 resultType, valueKind, RParenLoc);
10728
10729 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010730 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010731 call, 0))
10732 return ExprError();
10733
10734 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10735 return ExprError();
10736
10737 return MaybeBindToTemporary(call);
10738 }
10739
John McCall5acb0c92011-10-17 18:40:02 +000010740 UnbridgedCastsSet UnbridgedCasts;
10741 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10742 return ExprError();
10743
John McCall129e2df2009-11-30 22:42:35 +000010744 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010745 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010746 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010747 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010748 if (isa<MemberExpr>(NakedMemExpr)) {
10749 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010750 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010751 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010752 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010753 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010754 } else {
10755 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010756 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010757
John McCall701c89e2009-12-03 04:06:58 +000010758 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010759 Expr::Classification ObjectClassification
10760 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10761 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010762
Douglas Gregor88a35142008-12-22 05:46:06 +000010763 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010764 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010765
John McCallaa81e162009-12-01 22:10:20 +000010766 // FIXME: avoid copy.
10767 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10768 if (UnresExpr->hasExplicitTemplateArgs()) {
10769 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10770 TemplateArgs = &TemplateArgsBuffer;
10771 }
10772
John McCall129e2df2009-11-30 22:42:35 +000010773 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10774 E = UnresExpr->decls_end(); I != E; ++I) {
10775
John McCall701c89e2009-12-03 04:06:58 +000010776 NamedDecl *Func = *I;
10777 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10778 if (isa<UsingShadowDecl>(Func))
10779 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10780
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010781
Francois Pichetdbee3412011-01-18 05:04:39 +000010782 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010783 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010784 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10785 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010786 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010787 // If explicit template arguments were provided, we can't call a
10788 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010789 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010790 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010791
John McCall9aa472c2010-03-19 07:35:19 +000010792 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010793 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010794 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010795 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010796 } else {
John McCall129e2df2009-11-30 22:42:35 +000010797 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010798 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010799 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010800 llvm::makeArrayRef(Args, NumArgs),
10801 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010802 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010803 }
Douglas Gregordec06662009-08-21 18:42:58 +000010804 }
Mike Stump1eb44332009-09-09 15:08:12 +000010805
John McCall129e2df2009-11-30 22:42:35 +000010806 DeclarationName DeclName = UnresExpr->getMemberName();
10807
John McCall5acb0c92011-10-17 18:40:02 +000010808 UnbridgedCasts.restore();
10809
Douglas Gregor88a35142008-12-22 05:46:06 +000010810 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010811 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010812 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010813 case OR_Success:
10814 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010815 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010816 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010817 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010818 break;
10819
10820 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010821 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010822 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010823 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010824 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10825 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010826 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010827 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010828
10829 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010830 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010831 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010832 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10833 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010834 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010835 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010836
10837 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010838 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010839 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010840 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010841 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010842 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010843 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10844 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010845 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010846 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010847 }
10848
John McCall6bb80172010-03-30 21:47:33 +000010849 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010850
John McCallaa81e162009-12-01 22:10:20 +000010851 // If overload resolution picked a static member, build a
10852 // non-member call based on that function.
10853 if (Method->isStatic()) {
10854 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10855 Args, NumArgs, RParenLoc);
10856 }
10857
John McCall129e2df2009-11-30 22:42:35 +000010858 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010859 }
10860
John McCallf89e55a2010-11-18 06:31:45 +000010861 QualType ResultType = Method->getResultType();
10862 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10863 ResultType = ResultType.getNonLValueExprType(Context);
10864
Douglas Gregor88a35142008-12-22 05:46:06 +000010865 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010866 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010867 new (Context) CXXMemberCallExpr(Context, MemExprE,
10868 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010869 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010870
Anders Carlssoneed3e692009-10-10 00:06:20 +000010871 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010872 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010873 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010874 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010875
Douglas Gregor88a35142008-12-22 05:46:06 +000010876 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010877 // We only need to do this if there was actually an overload; otherwise
10878 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010879 if (!Method->isStatic()) {
10880 ExprResult ObjectArg =
10881 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10882 FoundDecl, Method);
10883 if (ObjectArg.isInvalid())
10884 return ExprError();
10885 MemExpr->setBase(ObjectArg.take());
10886 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010887
10888 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010889 const FunctionProtoType *Proto =
10890 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010891 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010892 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010893 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010894
Eli Friedmane61eb042012-02-18 04:48:30 +000010895 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10896
Richard Smith831421f2012-06-25 20:30:08 +000010897 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010898 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010899
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010900 if ((isa<CXXConstructorDecl>(CurContext) ||
10901 isa<CXXDestructorDecl>(CurContext)) &&
10902 TheCall->getMethodDecl()->isPure()) {
10903 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10904
Chandler Carruthae198062011-06-27 08:31:58 +000010905 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010906 Diag(MemExpr->getLocStart(),
10907 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10908 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10909 << MD->getParent()->getDeclName();
10910
10911 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010912 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010913 }
John McCall9ae2f072010-08-23 23:25:46 +000010914 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010915}
10916
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010917/// BuildCallToObjectOfClassType - Build a call to an object of class
10918/// type (C++ [over.call.object]), which can end up invoking an
10919/// overloaded function call operator (@c operator()) or performing a
10920/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010921ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010922Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010923 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010924 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010925 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010926 if (checkPlaceholderForOverload(*this, Obj))
10927 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010928 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010929
10930 UnbridgedCastsSet UnbridgedCasts;
10931 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10932 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010933
John Wiegley429bb272011-04-08 18:41:53 +000010934 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10935 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010936
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010937 // C++ [over.call.object]p1:
10938 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010939 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010940 // candidate functions includes at least the function call
10941 // operators of T. The function call operators of T are obtained by
10942 // ordinary lookup of the name operator() in the context of
10943 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010944 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010945 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010946
John Wiegley429bb272011-04-08 18:41:53 +000010947 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010948 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010949 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010950
John McCalla24dc2e2009-11-17 02:14:36 +000010951 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10952 LookupQualifiedName(R, Record->getDecl());
10953 R.suppressDiagnostics();
10954
Douglas Gregor593564b2009-11-15 07:48:03 +000010955 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010956 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010957 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10958 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010959 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010960 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010961
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010962 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010963 // In addition, for each (non-explicit in C++0x) conversion function
10964 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010965 //
10966 // operator conversion-type-id () cv-qualifier;
10967 //
10968 // where cv-qualifier is the same cv-qualification as, or a
10969 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010970 // denotes the type "pointer to function of (P1,...,Pn) returning
10971 // R", or the type "reference to pointer to function of
10972 // (P1,...,Pn) returning R", or the type "reference to function
10973 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010974 // is also considered as a candidate function. Similarly,
10975 // surrogate call functions are added to the set of candidate
10976 // functions for each conversion function declared in an
10977 // accessible base class provided the function is not hidden
10978 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010979 std::pair<CXXRecordDecl::conversion_iterator,
10980 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010981 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010982 for (CXXRecordDecl::conversion_iterator
10983 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010984 NamedDecl *D = *I;
10985 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10986 if (isa<UsingShadowDecl>(D))
10987 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010988
Douglas Gregor4a27d702009-10-21 06:18:39 +000010989 // Skip over templated conversion functions; they aren't
10990 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010991 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010992 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010993
John McCall701c89e2009-12-03 04:06:58 +000010994 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010995 if (!Conv->isExplicit()) {
10996 // Strip the reference type (if any) and then the pointer type (if
10997 // any) to get down to what might be a function type.
10998 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10999 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11000 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011001
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011002 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11003 {
11004 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000011005 Object.get(), llvm::makeArrayRef(Args, NumArgs),
11006 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011007 }
11008 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011009 }
Mike Stump1eb44332009-09-09 15:08:12 +000011010
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011011 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11012
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011013 // Perform overload resolution.
11014 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011015 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011016 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011017 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011018 // Overload resolution succeeded; we'll build the appropriate call
11019 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011020 break;
11021
11022 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011023 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011024 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011025 << Object.get()->getType() << /*call*/ 1
11026 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011027 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011028 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011029 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011030 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011031 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11032 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011033 break;
11034
11035 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011036 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011037 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011038 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011039 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11040 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011041 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011042
11043 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011044 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011045 diag::err_ovl_deleted_object_call)
11046 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011047 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011048 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011049 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011050 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11051 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011052 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011053 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011054
Douglas Gregorff331c12010-07-25 18:17:45 +000011055 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011056 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011057
John McCall5acb0c92011-10-17 18:40:02 +000011058 UnbridgedCasts.restore();
11059
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011060 if (Best->Function == 0) {
11061 // Since there is no function declaration, this is one of the
11062 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011063 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011064 = cast<CXXConversionDecl>(
11065 Best->Conversions[0].UserDefined.ConversionFunction);
11066
John Wiegley429bb272011-04-08 18:41:53 +000011067 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011068 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011069
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011070 // We selected one of the surrogate functions that converts the
11071 // object parameter to a function pointer. Perform the conversion
11072 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011073
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011074 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011075 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011076 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11077 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011078 if (Call.isInvalid())
11079 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011080 // Record usage of conversion in an implicit cast.
11081 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11082 CK_UserDefinedConversion,
11083 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011084
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011085 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011086 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011087 }
11088
John Wiegley429bb272011-04-08 18:41:53 +000011089 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011090
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011091 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11092 // that calls this method, using Object for the implicit object
11093 // parameter and passing along the remaining arguments.
11094 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011095
11096 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011097 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011098 return ExprError();
11099
Chandler Carruth6df868e2010-12-12 08:17:55 +000011100 const FunctionProtoType *Proto =
11101 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011102
11103 unsigned NumArgsInProto = Proto->getNumArgs();
11104 unsigned NumArgsToCheck = NumArgs;
11105
11106 // Build the full argument list for the method call (the
11107 // implicit object parameter is placed at the beginning of the
11108 // list).
11109 Expr **MethodArgs;
11110 if (NumArgs < NumArgsInProto) {
11111 NumArgsToCheck = NumArgsInProto;
11112 MethodArgs = new Expr*[NumArgsInProto + 1];
11113 } else {
11114 MethodArgs = new Expr*[NumArgs + 1];
11115 }
John Wiegley429bb272011-04-08 18:41:53 +000011116 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011117 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11118 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011119
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011120 DeclarationNameInfo OpLocInfo(
11121 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11122 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011123 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011124 HadMultipleCandidates,
11125 OpLocInfo.getLoc(),
11126 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011127 if (NewFn.isInvalid())
11128 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011129
11130 // Once we've built TheCall, all of the expressions are properly
11131 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011132 QualType ResultTy = Method->getResultType();
11133 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11134 ResultTy = ResultTy.getNonLValueExprType(Context);
11135
John McCall9ae2f072010-08-23 23:25:46 +000011136 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011137 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011138 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011139 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011140 delete [] MethodArgs;
11141
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011142 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011143 Method))
11144 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011145
Douglas Gregor518fda12009-01-13 05:10:00 +000011146 // We may have default arguments. If so, we need to allocate more
11147 // slots in the call for them.
11148 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011149 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011150 else if (NumArgs > NumArgsInProto)
11151 NumArgsToCheck = NumArgsInProto;
11152
Chris Lattner312531a2009-04-12 08:11:20 +000011153 bool IsError = false;
11154
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011155 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011156 ExprResult ObjRes =
11157 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11158 Best->FoundDecl, Method);
11159 if (ObjRes.isInvalid())
11160 IsError = true;
11161 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011162 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011163 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011164
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011165 // Check the argument types.
11166 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011167 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011168 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011169 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011170
Douglas Gregor518fda12009-01-13 05:10:00 +000011171 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011172
John McCall60d7b3a2010-08-24 06:29:42 +000011173 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011174 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011175 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011176 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011177 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011178
Anders Carlsson3faa4862010-01-29 18:43:53 +000011179 IsError |= InputInit.isInvalid();
11180 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011181 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011182 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011183 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11184 if (DefArg.isInvalid()) {
11185 IsError = true;
11186 break;
11187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011188
Douglas Gregord47c47d2009-11-09 19:27:57 +000011189 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011190 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011191
11192 TheCall->setArg(i + 1, Arg);
11193 }
11194
11195 // If this is a variadic call, handle args passed through "...".
11196 if (Proto->isVariadic()) {
11197 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011198 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011199 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11200 IsError |= Arg.isInvalid();
11201 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011202 }
11203 }
11204
Chris Lattner312531a2009-04-12 08:11:20 +000011205 if (IsError) return true;
11206
Eli Friedmane61eb042012-02-18 04:48:30 +000011207 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11208
Richard Smith831421f2012-06-25 20:30:08 +000011209 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011210 return true;
11211
John McCall182f7092010-08-24 06:09:16 +000011212 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011213}
11214
Douglas Gregor8ba10742008-11-20 16:27:02 +000011215/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011216/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011217/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011218ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011219Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011220 assert(Base->getType()->isRecordType() &&
11221 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011222
John McCall5acb0c92011-10-17 18:40:02 +000011223 if (checkPlaceholderForOverload(*this, Base))
11224 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011225
John McCall5769d612010-02-08 23:07:23 +000011226 SourceLocation Loc = Base->getExprLoc();
11227
Douglas Gregor8ba10742008-11-20 16:27:02 +000011228 // C++ [over.ref]p1:
11229 //
11230 // [...] An expression x->m is interpreted as (x.operator->())->m
11231 // for a class object x of type T if T::operator->() exists and if
11232 // the operator is selected as the best match function by the
11233 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011234 DeclarationName OpName =
11235 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011236 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011237 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011238
John McCall5769d612010-02-08 23:07:23 +000011239 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011240 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011241 return ExprError();
11242
John McCalla24dc2e2009-11-17 02:14:36 +000011243 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11244 LookupQualifiedName(R, BaseRecord->getDecl());
11245 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011246
11247 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011248 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011249 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11250 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011251 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011252
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011253 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11254
Douglas Gregor8ba10742008-11-20 16:27:02 +000011255 // Perform overload resolution.
11256 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011257 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011258 case OR_Success:
11259 // Overload resolution succeeded; we'll build the call below.
11260 break;
11261
11262 case OR_No_Viable_Function:
11263 if (CandidateSet.empty())
11264 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011265 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011266 else
11267 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011268 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011269 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011270 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011271
11272 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011273 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11274 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011275 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011276 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011277
11278 case OR_Deleted:
11279 Diag(OpLoc, diag::err_ovl_deleted_oper)
11280 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011281 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011282 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011283 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011284 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011285 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011286 }
11287
John McCall9aa472c2010-03-19 07:35:19 +000011288 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11289
Douglas Gregor8ba10742008-11-20 16:27:02 +000011290 // Convert the object parameter.
11291 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011292 ExprResult BaseResult =
11293 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11294 Best->FoundDecl, Method);
11295 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011296 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011297 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011298
Douglas Gregor8ba10742008-11-20 16:27:02 +000011299 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011300 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011301 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011302 if (FnExpr.isInvalid())
11303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011304
John McCallf89e55a2010-11-18 06:31:45 +000011305 QualType ResultTy = Method->getResultType();
11306 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11307 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011308 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011309 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011310 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011311
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011312 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011313 Method))
11314 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011315
11316 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011317}
11318
Richard Smith36f5cfe2012-03-09 08:00:36 +000011319/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11320/// a literal operator described by the provided lookup results.
11321ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11322 DeclarationNameInfo &SuffixInfo,
11323 ArrayRef<Expr*> Args,
11324 SourceLocation LitEndLoc,
11325 TemplateArgumentListInfo *TemplateArgs) {
11326 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011327
Richard Smith36f5cfe2012-03-09 08:00:36 +000011328 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11329 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11330 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011331
Richard Smith36f5cfe2012-03-09 08:00:36 +000011332 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11333
Richard Smith36f5cfe2012-03-09 08:00:36 +000011334 // Perform overload resolution. This will usually be trivial, but might need
11335 // to perform substitutions for a literal operator template.
11336 OverloadCandidateSet::iterator Best;
11337 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11338 case OR_Success:
11339 case OR_Deleted:
11340 break;
11341
11342 case OR_No_Viable_Function:
11343 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11344 << R.getLookupName();
11345 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11346 return ExprError();
11347
11348 case OR_Ambiguous:
11349 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11350 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11351 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011352 }
11353
Richard Smith36f5cfe2012-03-09 08:00:36 +000011354 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011355 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11356 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011357 SuffixInfo.getLoc(),
11358 SuffixInfo.getInfo());
11359 if (Fn.isInvalid())
11360 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011361
11362 // Check the argument types. This should almost always be a no-op, except
11363 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011364 Expr *ConvArgs[2];
11365 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11366 ExprResult InputInit = PerformCopyInitialization(
11367 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11368 SourceLocation(), Args[ArgIdx]);
11369 if (InputInit.isInvalid())
11370 return true;
11371 ConvArgs[ArgIdx] = InputInit.take();
11372 }
11373
Richard Smith9fcce652012-03-07 08:35:16 +000011374 QualType ResultTy = FD->getResultType();
11375 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11376 ResultTy = ResultTy.getNonLValueExprType(Context);
11377
Richard Smith9fcce652012-03-07 08:35:16 +000011378 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011379 new (Context) UserDefinedLiteral(Context, Fn.take(),
11380 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011381 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11382
11383 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11384 return ExprError();
11385
Richard Smith831421f2012-06-25 20:30:08 +000011386 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011387 return ExprError();
11388
11389 return MaybeBindToTemporary(UDL);
11390}
11391
Sam Panzere1715b62012-08-21 00:52:01 +000011392/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11393/// given LookupResult is non-empty, it is assumed to describe a member which
11394/// will be invoked. Otherwise, the function will be found via argument
11395/// dependent lookup.
11396/// CallExpr is set to a valid expression and FRS_Success returned on success,
11397/// otherwise CallExpr is set to ExprError() and some non-success value
11398/// is returned.
11399Sema::ForRangeStatus
11400Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11401 SourceLocation RangeLoc, VarDecl *Decl,
11402 BeginEndFunction BEF,
11403 const DeclarationNameInfo &NameInfo,
11404 LookupResult &MemberLookup,
11405 OverloadCandidateSet *CandidateSet,
11406 Expr *Range, ExprResult *CallExpr) {
11407 CandidateSet->clear();
11408 if (!MemberLookup.empty()) {
11409 ExprResult MemberRef =
11410 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11411 /*IsPtr=*/false, CXXScopeSpec(),
11412 /*TemplateKWLoc=*/SourceLocation(),
11413 /*FirstQualifierInScope=*/0,
11414 MemberLookup,
11415 /*TemplateArgs=*/0);
11416 if (MemberRef.isInvalid()) {
11417 *CallExpr = ExprError();
11418 Diag(Range->getLocStart(), diag::note_in_for_range)
11419 << RangeLoc << BEF << Range->getType();
11420 return FRS_DiagnosticIssued;
11421 }
11422 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11423 if (CallExpr->isInvalid()) {
11424 *CallExpr = ExprError();
11425 Diag(Range->getLocStart(), diag::note_in_for_range)
11426 << RangeLoc << BEF << Range->getType();
11427 return FRS_DiagnosticIssued;
11428 }
11429 } else {
11430 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011431 UnresolvedLookupExpr *Fn =
11432 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11433 NestedNameSpecifierLoc(), NameInfo,
11434 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011435 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011436
11437 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11438 CandidateSet, CallExpr);
11439 if (CandidateSet->empty() || CandidateSetError) {
11440 *CallExpr = ExprError();
11441 return FRS_NoViableFunction;
11442 }
11443 OverloadCandidateSet::iterator Best;
11444 OverloadingResult OverloadResult =
11445 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11446
11447 if (OverloadResult == OR_No_Viable_Function) {
11448 *CallExpr = ExprError();
11449 return FRS_NoViableFunction;
11450 }
11451 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11452 Loc, 0, CandidateSet, &Best,
11453 OverloadResult,
11454 /*AllowTypoCorrection=*/false);
11455 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11456 *CallExpr = ExprError();
11457 Diag(Range->getLocStart(), diag::note_in_for_range)
11458 << RangeLoc << BEF << Range->getType();
11459 return FRS_DiagnosticIssued;
11460 }
11461 }
11462 return FRS_Success;
11463}
11464
11465
Douglas Gregor904eed32008-11-10 20:40:00 +000011466/// FixOverloadedFunctionReference - E is an expression that refers to
11467/// a C++ overloaded function (possibly with some parentheses and
11468/// perhaps a '&' around it). We have resolved the overloaded function
11469/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011470/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011471Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011472 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011473 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011474 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11475 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011476 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011477 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011478
Douglas Gregor699ee522009-11-20 19:42:02 +000011479 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011480 }
11481
Douglas Gregor699ee522009-11-20 19:42:02 +000011482 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011483 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11484 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011485 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011486 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011487 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011488 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011489 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011490 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011491
11492 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011493 ICE->getCastKind(),
11494 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011495 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011496 }
11497
Douglas Gregor699ee522009-11-20 19:42:02 +000011498 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011499 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011500 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011501 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11502 if (Method->isStatic()) {
11503 // Do nothing: static member functions aren't any different
11504 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011505 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011506 // Fix the sub expression, which really has to be an
11507 // UnresolvedLookupExpr holding an overloaded member function
11508 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011509 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11510 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011511 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011512 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011513
John McCallba135432009-11-21 08:51:07 +000011514 assert(isa<DeclRefExpr>(SubExpr)
11515 && "fixed to something other than a decl ref");
11516 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11517 && "fixed to a member ref with no nested name qualifier");
11518
11519 // We have taken the address of a pointer to member
11520 // function. Perform the computation here so that we get the
11521 // appropriate pointer to member type.
11522 QualType ClassType
11523 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11524 QualType MemPtrType
11525 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11526
John McCallf89e55a2010-11-18 06:31:45 +000011527 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11528 VK_RValue, OK_Ordinary,
11529 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011530 }
11531 }
John McCall6bb80172010-03-30 21:47:33 +000011532 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11533 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011534 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011535 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011536
John McCall2de56d12010-08-25 11:45:40 +000011537 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011538 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011539 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011540 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011541 }
John McCallba135432009-11-21 08:51:07 +000011542
11543 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011544 // FIXME: avoid copy.
11545 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011546 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011547 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11548 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011549 }
11550
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011551 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11552 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011553 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011554 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011555 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011556 ULE->getNameLoc(),
11557 Fn->getType(),
11558 VK_LValue,
11559 Found.getDecl(),
11560 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011561 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011562 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11563 return DRE;
John McCallba135432009-11-21 08:51:07 +000011564 }
11565
John McCall129e2df2009-11-30 22:42:35 +000011566 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011567 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011568 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11569 if (MemExpr->hasExplicitTemplateArgs()) {
11570 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11571 TemplateArgs = &TemplateArgsBuffer;
11572 }
John McCalld5532b62009-11-23 01:53:49 +000011573
John McCallaa81e162009-12-01 22:10:20 +000011574 Expr *Base;
11575
John McCallf89e55a2010-11-18 06:31:45 +000011576 // If we're filling in a static method where we used to have an
11577 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011578 if (MemExpr->isImplicitAccess()) {
11579 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011580 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11581 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011582 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011583 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011584 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011585 MemExpr->getMemberLoc(),
11586 Fn->getType(),
11587 VK_LValue,
11588 Found.getDecl(),
11589 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011590 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011591 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11592 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011593 } else {
11594 SourceLocation Loc = MemExpr->getMemberLoc();
11595 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011596 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011597 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011598 Base = new (Context) CXXThisExpr(Loc,
11599 MemExpr->getBaseType(),
11600 /*isImplicit=*/true);
11601 }
John McCallaa81e162009-12-01 22:10:20 +000011602 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011603 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011604
John McCallf5307512011-04-27 00:36:17 +000011605 ExprValueKind valueKind;
11606 QualType type;
11607 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11608 valueKind = VK_LValue;
11609 type = Fn->getType();
11610 } else {
11611 valueKind = VK_RValue;
11612 type = Context.BoundMemberTy;
11613 }
11614
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011615 MemberExpr *ME = MemberExpr::Create(Context, Base,
11616 MemExpr->isArrow(),
11617 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011618 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011619 Fn,
11620 Found,
11621 MemExpr->getMemberNameInfo(),
11622 TemplateArgs,
11623 type, valueKind, OK_Ordinary);
11624 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011625 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011626 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011627 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011628
John McCall3fa5cae2010-10-26 07:05:15 +000011629 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011630}
11631
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011632ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011633 DeclAccessPair Found,
11634 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011635 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011636}
11637
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011638} // end namespace clang