blob: 3ed046579417f48254ed42d51d73ba4242123847 [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 Gregorabe183d2010-04-13 16:31:36 +00003940/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3941/// determine whether they are reference-related,
3942/// reference-compatible, reference-compatible with added
3943/// qualification, or incompatible, for use in C++ initialization by
3944/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3945/// type, and the first type (T1) is the pointee type of the reference
3946/// type being initialized.
3947Sema::ReferenceCompareResult
3948Sema::CompareReferenceRelationship(SourceLocation Loc,
3949 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003950 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003951 bool &ObjCConversion,
3952 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003953 assert(!OrigT1->isReferenceType() &&
3954 "T1 must be the pointee type of the reference type");
3955 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3956
3957 QualType T1 = Context.getCanonicalType(OrigT1);
3958 QualType T2 = Context.getCanonicalType(OrigT2);
3959 Qualifiers T1Quals, T2Quals;
3960 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3961 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3962
3963 // C++ [dcl.init.ref]p4:
3964 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3965 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3966 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003967 DerivedToBase = false;
3968 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003969 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003970 if (UnqualT1 == UnqualT2) {
3971 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003972 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003973 IsDerivedFrom(UnqualT2, UnqualT1))
3974 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003975 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3976 UnqualT2->isObjCObjectOrInterfaceType() &&
3977 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3978 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003979 else
3980 return Ref_Incompatible;
3981
3982 // At this point, we know that T1 and T2 are reference-related (at
3983 // least).
3984
3985 // If the type is an array type, promote the element qualifiers to the type
3986 // for comparison.
3987 if (isa<ArrayType>(T1) && T1Quals)
3988 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3989 if (isa<ArrayType>(T2) && T2Quals)
3990 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3991
3992 // C++ [dcl.init.ref]p4:
3993 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3994 // reference-related to T2 and cv1 is the same cv-qualification
3995 // as, or greater cv-qualification than, cv2. For purposes of
3996 // overload resolution, cases for which cv1 is greater
3997 // cv-qualification than cv2 are identified as
3998 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003999 //
4000 // Note that we also require equivalence of Objective-C GC and address-space
4001 // qualifiers when performing these computations, so that e.g., an int in
4002 // address space 1 is not reference-compatible with an int in address
4003 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00004004 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4005 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4006 T1Quals.removeObjCLifetime();
4007 T2Quals.removeObjCLifetime();
4008 ObjCLifetimeConversion = true;
4009 }
4010
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004011 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004012 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004013 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004014 return Ref_Compatible_With_Added_Qualification;
4015 else
4016 return Ref_Related;
4017}
4018
Douglas Gregor604eb652010-08-11 02:15:33 +00004019/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004020/// with DeclType. Return true if something definite is found.
4021static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004022FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4023 QualType DeclType, SourceLocation DeclLoc,
4024 Expr *Init, QualType T2, bool AllowRvalues,
4025 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004026 assert(T2->isRecordType() && "Can only find conversions of record types.");
4027 CXXRecordDecl *T2RecordDecl
4028 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4029
4030 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004031 std::pair<CXXRecordDecl::conversion_iterator,
4032 CXXRecordDecl::conversion_iterator>
4033 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4034 for (CXXRecordDecl::conversion_iterator
4035 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004036 NamedDecl *D = *I;
4037 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4038 if (isa<UsingShadowDecl>(D))
4039 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4040
4041 FunctionTemplateDecl *ConvTemplate
4042 = dyn_cast<FunctionTemplateDecl>(D);
4043 CXXConversionDecl *Conv;
4044 if (ConvTemplate)
4045 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4046 else
4047 Conv = cast<CXXConversionDecl>(D);
4048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004049 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004050 // explicit conversions, skip it.
4051 if (!AllowExplicit && Conv->isExplicit())
4052 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004053
Douglas Gregor604eb652010-08-11 02:15:33 +00004054 if (AllowRvalues) {
4055 bool DerivedToBase = false;
4056 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004057 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004058
4059 // If we are initializing an rvalue reference, don't permit conversion
4060 // functions that return lvalues.
4061 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4062 const ReferenceType *RefType
4063 = Conv->getConversionType()->getAs<LValueReferenceType>();
4064 if (RefType && !RefType->getPointeeType()->isFunctionType())
4065 continue;
4066 }
4067
Douglas Gregor604eb652010-08-11 02:15:33 +00004068 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004069 S.CompareReferenceRelationship(
4070 DeclLoc,
4071 Conv->getConversionType().getNonReferenceType()
4072 .getUnqualifiedType(),
4073 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004074 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004075 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004076 continue;
4077 } else {
4078 // If the conversion function doesn't return a reference type,
4079 // it can't be considered for this conversion. An rvalue reference
4080 // is only acceptable if its referencee is a function type.
4081
4082 const ReferenceType *RefType =
4083 Conv->getConversionType()->getAs<ReferenceType>();
4084 if (!RefType ||
4085 (!RefType->isLValueReferenceType() &&
4086 !RefType->getPointeeType()->isFunctionType()))
4087 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004088 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004089
Douglas Gregor604eb652010-08-11 02:15:33 +00004090 if (ConvTemplate)
4091 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004092 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004093 else
4094 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004095 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004096 }
4097
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004098 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4099
Sebastian Redl4680bf22010-06-30 18:13:39 +00004100 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004101 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004102 case OR_Success:
4103 // C++ [over.ics.ref]p1:
4104 //
4105 // [...] If the parameter binds directly to the result of
4106 // applying a conversion function to the argument
4107 // expression, the implicit conversion sequence is a
4108 // user-defined conversion sequence (13.3.3.1.2), with the
4109 // second standard conversion sequence either an identity
4110 // conversion or, if the conversion function returns an
4111 // entity of a type that is a derived class of the parameter
4112 // type, a derived-to-base Conversion.
4113 if (!Best->FinalConversion.DirectBinding)
4114 return false;
4115
4116 ICS.setUserDefined();
4117 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4118 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004119 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004120 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004121 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004122 ICS.UserDefined.EllipsisConversion = false;
4123 assert(ICS.UserDefined.After.ReferenceBinding &&
4124 ICS.UserDefined.After.DirectBinding &&
4125 "Expected a direct reference binding!");
4126 return true;
4127
4128 case OR_Ambiguous:
4129 ICS.setAmbiguous();
4130 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4131 Cand != CandidateSet.end(); ++Cand)
4132 if (Cand->Viable)
4133 ICS.Ambiguous.addConversion(Cand->Function);
4134 return true;
4135
4136 case OR_No_Viable_Function:
4137 case OR_Deleted:
4138 // There was no suitable conversion, or we found a deleted
4139 // conversion; continue with other checks.
4140 return false;
4141 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004142
David Blaikie7530c032012-01-17 06:56:22 +00004143 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004144}
4145
Douglas Gregorabe183d2010-04-13 16:31:36 +00004146/// \brief Compute an implicit conversion sequence for reference
4147/// initialization.
4148static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004149TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004150 SourceLocation DeclLoc,
4151 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004152 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004153 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4154
4155 // Most paths end in a failed conversion.
4156 ImplicitConversionSequence ICS;
4157 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4158
4159 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4160 QualType T2 = Init->getType();
4161
4162 // If the initializer is the address of an overloaded function, try
4163 // to resolve the overloaded function. If all goes well, T2 is the
4164 // type of the resulting function.
4165 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4166 DeclAccessPair Found;
4167 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4168 false, Found))
4169 T2 = Fn->getType();
4170 }
4171
4172 // Compute some basic properties of the types and the initializer.
4173 bool isRValRef = DeclType->isRValueReferenceType();
4174 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004175 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004176 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004177 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004178 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004179 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004180 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004181
Douglas Gregorabe183d2010-04-13 16:31:36 +00004182
Sebastian Redl4680bf22010-06-30 18:13:39 +00004183 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004184 // A reference to type "cv1 T1" is initialized by an expression
4185 // of type "cv2 T2" as follows:
4186
Sebastian Redl4680bf22010-06-30 18:13:39 +00004187 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004188 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004189 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4190 // reference-compatible with "cv2 T2," or
4191 //
4192 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4193 if (InitCategory.isLValue() &&
4194 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004195 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004196 // When a parameter of reference type binds directly (8.5.3)
4197 // to an argument expression, the implicit conversion sequence
4198 // is the identity conversion, unless the argument expression
4199 // has a type that is a derived class of the parameter type,
4200 // in which case the implicit conversion sequence is a
4201 // derived-to-base Conversion (13.3.3.1).
4202 ICS.setStandard();
4203 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004204 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4205 : ObjCConversion? ICK_Compatible_Conversion
4206 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004207 ICS.Standard.Third = ICK_Identity;
4208 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4209 ICS.Standard.setToType(0, T2);
4210 ICS.Standard.setToType(1, T1);
4211 ICS.Standard.setToType(2, T1);
4212 ICS.Standard.ReferenceBinding = true;
4213 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004214 ICS.Standard.IsLvalueReference = !isRValRef;
4215 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4216 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004217 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004218 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004219 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004220
Sebastian Redl4680bf22010-06-30 18:13:39 +00004221 // Nothing more to do: the inaccessibility/ambiguity check for
4222 // derived-to-base conversions is suppressed when we're
4223 // computing the implicit conversion sequence (C++
4224 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004225 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004226 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004227
Sebastian Redl4680bf22010-06-30 18:13:39 +00004228 // -- has a class type (i.e., T2 is a class type), where T1 is
4229 // not reference-related to T2, and can be implicitly
4230 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4231 // is reference-compatible with "cv3 T3" 92) (this
4232 // conversion is selected by enumerating the applicable
4233 // conversion functions (13.3.1.6) and choosing the best
4234 // one through overload resolution (13.3)),
4235 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004237 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004238 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4239 Init, T2, /*AllowRvalues=*/false,
4240 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004241 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004242 }
4243 }
4244
Sebastian Redl4680bf22010-06-30 18:13:39 +00004245 // -- Otherwise, the reference shall be an lvalue reference to a
4246 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004247 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004248 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004249 // We actually handle one oddity of C++ [over.ics.ref] at this
4250 // point, which is that, due to p2 (which short-circuits reference
4251 // binding by only attempting a simple conversion for non-direct
4252 // bindings) and p3's strange wording, we allow a const volatile
4253 // reference to bind to an rvalue. Hence the check for the presence
4254 // of "const" rather than checking for "const" being the only
4255 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004256 // This is also the point where rvalue references and lvalue inits no longer
4257 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004258 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004259 return ICS;
4260
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004261 // -- If the initializer expression
4262 //
4263 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004264 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004265 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4266 (InitCategory.isXValue() ||
4267 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4268 (InitCategory.isLValue() && T2->isFunctionType()))) {
4269 ICS.setStandard();
4270 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004271 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004272 : ObjCConversion? ICK_Compatible_Conversion
4273 : ICK_Identity;
4274 ICS.Standard.Third = ICK_Identity;
4275 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4276 ICS.Standard.setToType(0, T2);
4277 ICS.Standard.setToType(1, T1);
4278 ICS.Standard.setToType(2, T1);
4279 ICS.Standard.ReferenceBinding = true;
4280 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4281 // binding unless we're binding to a class prvalue.
4282 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4283 // allow the use of rvalue references in C++98/03 for the benefit of
4284 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004286 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004287 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004288 ICS.Standard.IsLvalueReference = !isRValRef;
4289 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004291 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004292 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004293 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004295 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004296
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004297 // -- has a class type (i.e., T2 is a class type), where T1 is not
4298 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004299 // an xvalue, class prvalue, or function lvalue of type
4300 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004301 // "cv3 T3",
4302 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004303 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004304 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004306 // class subobject).
4307 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004309 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4310 Init, T2, /*AllowRvalues=*/true,
4311 AllowExplicit)) {
4312 // In the second case, if the reference is an rvalue reference
4313 // and the second standard conversion sequence of the
4314 // user-defined conversion sequence includes an lvalue-to-rvalue
4315 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004317 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4318 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4319
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004320 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004322
Douglas Gregorabe183d2010-04-13 16:31:36 +00004323 // -- Otherwise, a temporary of type "cv1 T1" is created and
4324 // initialized from the initializer expression using the
4325 // rules for a non-reference copy initialization (8.5). The
4326 // reference is then bound to the temporary. If T1 is
4327 // reference-related to T2, cv1 must be the same
4328 // cv-qualification as, or greater cv-qualification than,
4329 // cv2; otherwise, the program is ill-formed.
4330 if (RefRelationship == Sema::Ref_Related) {
4331 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4332 // we would be reference-compatible or reference-compatible with
4333 // added qualification. But that wasn't the case, so the reference
4334 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004335 //
4336 // Note that we only want to check address spaces and cvr-qualifiers here.
4337 // ObjC GC and lifetime qualifiers aren't important.
4338 Qualifiers T1Quals = T1.getQualifiers();
4339 Qualifiers T2Quals = T2.getQualifiers();
4340 T1Quals.removeObjCGCAttr();
4341 T1Quals.removeObjCLifetime();
4342 T2Quals.removeObjCGCAttr();
4343 T2Quals.removeObjCLifetime();
4344 if (!T1Quals.compatiblyIncludes(T2Quals))
4345 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004346 }
4347
4348 // If at least one of the types is a class type, the types are not
4349 // related, and we aren't allowed any user conversions, the
4350 // reference binding fails. This case is important for breaking
4351 // recursion, since TryImplicitConversion below will attempt to
4352 // create a temporary through the use of a copy constructor.
4353 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4354 (T1->isRecordType() || T2->isRecordType()))
4355 return ICS;
4356
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004357 // If T1 is reference-related to T2 and the reference is an rvalue
4358 // reference, the initializer expression shall not be an lvalue.
4359 if (RefRelationship >= Sema::Ref_Related &&
4360 isRValRef && Init->Classify(S.Context).isLValue())
4361 return ICS;
4362
Douglas Gregorabe183d2010-04-13 16:31:36 +00004363 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004364 // When a parameter of reference type is not bound directly to
4365 // an argument expression, the conversion sequence is the one
4366 // required to convert the argument expression to the
4367 // underlying type of the reference according to
4368 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4369 // to copy-initializing a temporary of the underlying type with
4370 // the argument expression. Any difference in top-level
4371 // cv-qualification is subsumed by the initialization itself
4372 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004373 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4374 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004375 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004376 /*CStyle=*/false,
4377 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004378
4379 // Of course, that's still a reference binding.
4380 if (ICS.isStandard()) {
4381 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004382 ICS.Standard.IsLvalueReference = !isRValRef;
4383 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4384 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004385 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004386 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004387 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004388 // Don't allow rvalue references to bind to lvalues.
4389 if (DeclType->isRValueReferenceType()) {
4390 if (const ReferenceType *RefType
4391 = ICS.UserDefined.ConversionFunction->getResultType()
4392 ->getAs<LValueReferenceType>()) {
4393 if (!RefType->getPointeeType()->isFunctionType()) {
4394 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4395 DeclType);
4396 return ICS;
4397 }
4398 }
4399 }
4400
Douglas Gregorabe183d2010-04-13 16:31:36 +00004401 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004402 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4403 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4404 ICS.UserDefined.After.BindsToRvalue = true;
4405 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4406 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004407 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004408
Douglas Gregorabe183d2010-04-13 16:31:36 +00004409 return ICS;
4410}
4411
Sebastian Redl5405b812011-10-16 18:19:34 +00004412static ImplicitConversionSequence
4413TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4414 bool SuppressUserConversions,
4415 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004416 bool AllowObjCWritebackConversion,
4417 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004418
4419/// TryListConversion - Try to copy-initialize a value of type ToType from the
4420/// initializer list From.
4421static ImplicitConversionSequence
4422TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4423 bool SuppressUserConversions,
4424 bool InOverloadResolution,
4425 bool AllowObjCWritebackConversion) {
4426 // C++11 [over.ics.list]p1:
4427 // When an argument is an initializer list, it is not an expression and
4428 // special rules apply for converting it to a parameter type.
4429
4430 ImplicitConversionSequence Result;
4431 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004432 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004433
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004434 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004435 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004436 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004437 return Result;
4438
Sebastian Redl5405b812011-10-16 18:19:34 +00004439 // C++11 [over.ics.list]p2:
4440 // If the parameter type is std::initializer_list<X> or "array of X" and
4441 // all the elements can be implicitly converted to X, the implicit
4442 // conversion sequence is the worst conversion necessary to convert an
4443 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004444 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004445 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004446 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004447 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004448 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004449 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004450 if (!X.isNull()) {
4451 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4452 Expr *Init = From->getInit(i);
4453 ImplicitConversionSequence ICS =
4454 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4455 InOverloadResolution,
4456 AllowObjCWritebackConversion);
4457 // If a single element isn't convertible, fail.
4458 if (ICS.isBad()) {
4459 Result = ICS;
4460 break;
4461 }
4462 // Otherwise, look for the worst conversion.
4463 if (Result.isBad() ||
4464 CompareImplicitConversionSequences(S, ICS, Result) ==
4465 ImplicitConversionSequence::Worse)
4466 Result = ICS;
4467 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004468
4469 // For an empty list, we won't have computed any conversion sequence.
4470 // Introduce the identity conversion sequence.
4471 if (From->getNumInits() == 0) {
4472 Result.setStandard();
4473 Result.Standard.setAsIdentityConversion();
4474 Result.Standard.setFromType(ToType);
4475 Result.Standard.setAllToTypes(ToType);
4476 }
4477
Sebastian Redlfe592282012-01-17 22:49:48 +00004478 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004479 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004480 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004481 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004482
4483 // C++11 [over.ics.list]p3:
4484 // Otherwise, if the parameter is a non-aggregate class X and overload
4485 // resolution chooses a single best constructor [...] the implicit
4486 // conversion sequence is a user-defined conversion sequence. If multiple
4487 // constructors are viable but none is better than the others, the
4488 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004489 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4490 // This function can deal with initializer lists.
4491 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4492 /*AllowExplicit=*/false,
4493 InOverloadResolution, /*CStyle=*/false,
4494 AllowObjCWritebackConversion);
4495 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004496 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004497 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004498
4499 // C++11 [over.ics.list]p4:
4500 // Otherwise, if the parameter has an aggregate type which can be
4501 // initialized from the initializer list [...] the implicit conversion
4502 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004503 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004504 // Type is an aggregate, argument is an init list. At this point it comes
4505 // down to checking whether the initialization works.
4506 // FIXME: Find out whether this parameter is consumed or not.
4507 InitializedEntity Entity =
4508 InitializedEntity::InitializeParameter(S.Context, ToType,
4509 /*Consumed=*/false);
4510 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4511 Result.setUserDefined();
4512 Result.UserDefined.Before.setAsIdentityConversion();
4513 // Initializer lists don't have a type.
4514 Result.UserDefined.Before.setFromType(QualType());
4515 Result.UserDefined.Before.setAllToTypes(QualType());
4516
4517 Result.UserDefined.After.setAsIdentityConversion();
4518 Result.UserDefined.After.setFromType(ToType);
4519 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004520 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004521 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004522 return Result;
4523 }
4524
4525 // C++11 [over.ics.list]p5:
4526 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004527 if (ToType->isReferenceType()) {
4528 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4529 // mention initializer lists in any way. So we go by what list-
4530 // initialization would do and try to extrapolate from that.
4531
4532 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4533
4534 // If the initializer list has a single element that is reference-related
4535 // to the parameter type, we initialize the reference from that.
4536 if (From->getNumInits() == 1) {
4537 Expr *Init = From->getInit(0);
4538
4539 QualType T2 = Init->getType();
4540
4541 // If the initializer is the address of an overloaded function, try
4542 // to resolve the overloaded function. If all goes well, T2 is the
4543 // type of the resulting function.
4544 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4545 DeclAccessPair Found;
4546 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4547 Init, ToType, false, Found))
4548 T2 = Fn->getType();
4549 }
4550
4551 // Compute some basic properties of the types and the initializer.
4552 bool dummy1 = false;
4553 bool dummy2 = false;
4554 bool dummy3 = false;
4555 Sema::ReferenceCompareResult RefRelationship
4556 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4557 dummy2, dummy3);
4558
4559 if (RefRelationship >= Sema::Ref_Related)
4560 return TryReferenceInit(S, Init, ToType,
4561 /*FIXME:*/From->getLocStart(),
4562 SuppressUserConversions,
4563 /*AllowExplicit=*/false);
4564 }
4565
4566 // Otherwise, we bind the reference to a temporary created from the
4567 // initializer list.
4568 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4569 InOverloadResolution,
4570 AllowObjCWritebackConversion);
4571 if (Result.isFailure())
4572 return Result;
4573 assert(!Result.isEllipsis() &&
4574 "Sub-initialization cannot result in ellipsis conversion.");
4575
4576 // Can we even bind to a temporary?
4577 if (ToType->isRValueReferenceType() ||
4578 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4579 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4580 Result.UserDefined.After;
4581 SCS.ReferenceBinding = true;
4582 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4583 SCS.BindsToRvalue = true;
4584 SCS.BindsToFunctionLvalue = false;
4585 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4586 SCS.ObjCLifetimeConversionBinding = false;
4587 } else
4588 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4589 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004590 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004591 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004592
4593 // C++11 [over.ics.list]p6:
4594 // Otherwise, if the parameter type is not a class:
4595 if (!ToType->isRecordType()) {
4596 // - if the initializer list has one element, the implicit conversion
4597 // sequence is the one required to convert the element to the
4598 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004599 unsigned NumInits = From->getNumInits();
4600 if (NumInits == 1)
4601 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4602 SuppressUserConversions,
4603 InOverloadResolution,
4604 AllowObjCWritebackConversion);
4605 // - if the initializer list has no elements, the implicit conversion
4606 // sequence is the identity conversion.
4607 else if (NumInits == 0) {
4608 Result.setStandard();
4609 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004610 Result.Standard.setFromType(ToType);
4611 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004612 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004613 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004614 return Result;
4615 }
4616
4617 // C++11 [over.ics.list]p7:
4618 // In all cases other than those enumerated above, no conversion is possible
4619 return Result;
4620}
4621
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004622/// TryCopyInitialization - Try to copy-initialize a value of type
4623/// ToType from the expression From. Return the implicit conversion
4624/// sequence required to pass this argument, which may be a bad
4625/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004626/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004627/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004628static ImplicitConversionSequence
4629TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004630 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004631 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004632 bool AllowObjCWritebackConversion,
4633 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004634 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4635 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4636 InOverloadResolution,AllowObjCWritebackConversion);
4637
Douglas Gregorabe183d2010-04-13 16:31:36 +00004638 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004639 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004640 /*FIXME:*/From->getLocStart(),
4641 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004642 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004643
John McCall120d63c2010-08-24 20:38:10 +00004644 return TryImplicitConversion(S, From, ToType,
4645 SuppressUserConversions,
4646 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004647 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004648 /*CStyle=*/false,
4649 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004650}
4651
Anna Zaksf3546ee2011-07-28 19:46:48 +00004652static bool TryCopyInitialization(const CanQualType FromQTy,
4653 const CanQualType ToQTy,
4654 Sema &S,
4655 SourceLocation Loc,
4656 ExprValueKind FromVK) {
4657 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4658 ImplicitConversionSequence ICS =
4659 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4660
4661 return !ICS.isBad();
4662}
4663
Douglas Gregor96176b32008-11-18 23:14:02 +00004664/// TryObjectArgumentInitialization - Try to initialize the object
4665/// parameter of the given member function (@c Method) from the
4666/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004667static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004668TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004669 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004670 CXXMethodDecl *Method,
4671 CXXRecordDecl *ActingContext) {
4672 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004673 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4674 // const volatile object.
4675 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4676 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004677 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004678
4679 // Set up the conversion sequence as a "bad" conversion, to allow us
4680 // to exit early.
4681 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004682
4683 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004684 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004685 FromType = PT->getPointeeType();
4686
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004687 // When we had a pointer, it's implicitly dereferenced, so we
4688 // better have an lvalue.
4689 assert(FromClassification.isLValue());
4690 }
4691
Anders Carlssona552f7c2009-05-01 18:34:30 +00004692 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004693
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004694 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004696 // parameter is
4697 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004698 // - "lvalue reference to cv X" for functions declared without a
4699 // ref-qualifier or with the & ref-qualifier
4700 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004701 // ref-qualifier
4702 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004704 // cv-qualification on the member function declaration.
4705 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004706 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004707 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004708 // (C++ [over.match.funcs]p5). We perform a simplified version of
4709 // reference binding here, that allows class rvalues to bind to
4710 // non-constant references.
4711
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004712 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004713 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004715 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004716 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004717 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004718 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004719 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004720 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004721
4722 // Check that we have either the same type or a derived type. It
4723 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004724 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004725 ImplicitConversionKind SecondKind;
4726 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4727 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004728 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004729 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004730 else {
John McCallb1bdc622010-02-25 01:37:24 +00004731 ICS.setBad(BadConversionSequence::unrelated_class,
4732 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004733 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004734 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004735
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004736 // Check the ref-qualifier.
4737 switch (Method->getRefQualifier()) {
4738 case RQ_None:
4739 // Do nothing; we don't care about lvalueness or rvalueness.
4740 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004741
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004742 case RQ_LValue:
4743 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4744 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004746 ImplicitParamType);
4747 return ICS;
4748 }
4749 break;
4750
4751 case RQ_RValue:
4752 if (!FromClassification.isRValue()) {
4753 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004754 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004755 ImplicitParamType);
4756 return ICS;
4757 }
4758 break;
4759 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregor96176b32008-11-18 23:14:02 +00004761 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004762 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004763 ICS.Standard.setAsIdentityConversion();
4764 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004765 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004766 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004767 ICS.Standard.ReferenceBinding = true;
4768 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004769 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004770 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004771 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4772 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4773 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004774 return ICS;
4775}
4776
4777/// PerformObjectArgumentInitialization - Perform initialization of
4778/// the implicit object parameter for the given Method with the given
4779/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004780ExprResult
4781Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004782 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004783 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004784 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004785 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004786 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004787 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004789 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004790 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004791 FromRecordType = PT->getPointeeType();
4792 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004793 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004794 } else {
4795 FromRecordType = From->getType();
4796 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004797 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004798 }
4799
John McCall701c89e2009-12-03 04:06:58 +00004800 // Note that we always use the true parent context when performing
4801 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004802 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004803 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4804 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004805 if (ICS.isBad()) {
4806 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4807 Qualifiers FromQs = FromRecordType.getQualifiers();
4808 Qualifiers ToQs = DestType.getQualifiers();
4809 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4810 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004811 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004812 diag::err_member_function_call_bad_cvr)
4813 << Method->getDeclName() << FromRecordType << (CVR - 1)
4814 << From->getSourceRange();
4815 Diag(Method->getLocation(), diag::note_previous_decl)
4816 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004817 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004818 }
4819 }
4820
Daniel Dunbar96a00142012-03-09 18:35:03 +00004821 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004822 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004823 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004824 }
Mike Stump1eb44332009-09-09 15:08:12 +00004825
John Wiegley429bb272011-04-08 18:41:53 +00004826 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4827 ExprResult FromRes =
4828 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4829 if (FromRes.isInvalid())
4830 return ExprError();
4831 From = FromRes.take();
4832 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004833
Douglas Gregor5fccd362010-03-03 23:55:11 +00004834 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004835 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004836 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004837 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004838}
4839
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004840/// TryContextuallyConvertToBool - Attempt to contextually convert the
4841/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004842static ImplicitConversionSequence
4843TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004844 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004845 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004846 // FIXME: Are these flags correct?
4847 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004848 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004849 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004850 /*CStyle=*/false,
4851 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004852}
4853
4854/// PerformContextuallyConvertToBool - Perform a contextual conversion
4855/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004856ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004857 if (checkPlaceholderForOverload(*this, From))
4858 return ExprError();
4859
John McCall120d63c2010-08-24 20:38:10 +00004860 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004861 if (!ICS.isBad())
4862 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004863
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004864 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004865 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004866 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004867 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004868 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004869}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004870
Richard Smith8ef7b202012-01-18 23:55:52 +00004871/// Check that the specified conversion is permitted in a converted constant
4872/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4873/// is acceptable.
4874static bool CheckConvertedConstantConversions(Sema &S,
4875 StandardConversionSequence &SCS) {
4876 // Since we know that the target type is an integral or unscoped enumeration
4877 // type, most conversion kinds are impossible. All possible First and Third
4878 // conversions are fine.
4879 switch (SCS.Second) {
4880 case ICK_Identity:
4881 case ICK_Integral_Promotion:
4882 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004883 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004884 return true;
4885
4886 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004887 // Conversion from an integral or unscoped enumeration type to bool is
4888 // classified as ICK_Boolean_Conversion, but it's also an integral
4889 // conversion, so it's permitted in a converted constant expression.
4890 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4891 SCS.getToType(2)->isBooleanType();
4892
Richard Smith8ef7b202012-01-18 23:55:52 +00004893 case ICK_Floating_Integral:
4894 case ICK_Complex_Real:
4895 return false;
4896
4897 case ICK_Lvalue_To_Rvalue:
4898 case ICK_Array_To_Pointer:
4899 case ICK_Function_To_Pointer:
4900 case ICK_NoReturn_Adjustment:
4901 case ICK_Qualification:
4902 case ICK_Compatible_Conversion:
4903 case ICK_Vector_Conversion:
4904 case ICK_Vector_Splat:
4905 case ICK_Derived_To_Base:
4906 case ICK_Pointer_Conversion:
4907 case ICK_Pointer_Member:
4908 case ICK_Block_Pointer_Conversion:
4909 case ICK_Writeback_Conversion:
4910 case ICK_Floating_Promotion:
4911 case ICK_Complex_Promotion:
4912 case ICK_Complex_Conversion:
4913 case ICK_Floating_Conversion:
4914 case ICK_TransparentUnionConversion:
4915 llvm_unreachable("unexpected second conversion kind");
4916
4917 case ICK_Num_Conversion_Kinds:
4918 break;
4919 }
4920
4921 llvm_unreachable("unknown conversion kind");
4922}
4923
4924/// CheckConvertedConstantExpression - Check that the expression From is a
4925/// converted constant expression of type T, perform the conversion and produce
4926/// the converted expression, per C++11 [expr.const]p3.
4927ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4928 llvm::APSInt &Value,
4929 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004930 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004931 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4932
4933 if (checkPlaceholderForOverload(*this, From))
4934 return ExprError();
4935
4936 // C++11 [expr.const]p3 with proposed wording fixes:
4937 // A converted constant expression of type T is a core constant expression,
4938 // implicitly converted to a prvalue of type T, where the converted
4939 // expression is a literal constant expression and the implicit conversion
4940 // sequence contains only user-defined conversions, lvalue-to-rvalue
4941 // conversions, integral promotions, and integral conversions other than
4942 // narrowing conversions.
4943 ImplicitConversionSequence ICS =
4944 TryImplicitConversion(From, T,
4945 /*SuppressUserConversions=*/false,
4946 /*AllowExplicit=*/false,
4947 /*InOverloadResolution=*/false,
4948 /*CStyle=*/false,
4949 /*AllowObjcWritebackConversion=*/false);
4950 StandardConversionSequence *SCS = 0;
4951 switch (ICS.getKind()) {
4952 case ImplicitConversionSequence::StandardConversion:
4953 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004954 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004955 diag::err_typecheck_converted_constant_expression_disallowed)
4956 << From->getType() << From->getSourceRange() << T;
4957 SCS = &ICS.Standard;
4958 break;
4959 case ImplicitConversionSequence::UserDefinedConversion:
4960 // We are converting from class type to an integral or enumeration type, so
4961 // the Before sequence must be trivial.
4962 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004963 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004964 diag::err_typecheck_converted_constant_expression_disallowed)
4965 << From->getType() << From->getSourceRange() << T;
4966 SCS = &ICS.UserDefined.After;
4967 break;
4968 case ImplicitConversionSequence::AmbiguousConversion:
4969 case ImplicitConversionSequence::BadConversion:
4970 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004971 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004972 diag::err_typecheck_converted_constant_expression)
4973 << From->getType() << From->getSourceRange() << T;
4974 return ExprError();
4975
4976 case ImplicitConversionSequence::EllipsisConversion:
4977 llvm_unreachable("ellipsis conversion in converted constant expression");
4978 }
4979
4980 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4981 if (Result.isInvalid())
4982 return Result;
4983
4984 // Check for a narrowing implicit conversion.
4985 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004986 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004987 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4988 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004989 case NK_Variable_Narrowing:
4990 // Implicit conversion to a narrower type, and the value is not a constant
4991 // expression. We'll diagnose this in a moment.
4992 case NK_Not_Narrowing:
4993 break;
4994
4995 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004996 Diag(From->getLocStart(),
4997 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4998 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004999 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00005000 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005001 break;
5002
5003 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005004 Diag(From->getLocStart(),
5005 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5006 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005007 << CCE << /*Constant*/0 << From->getType() << T;
5008 break;
5009 }
5010
5011 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005012 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005013 Expr::EvalResult Eval;
5014 Eval.Diag = &Notes;
5015
5016 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5017 // The expression can't be folded, so we can't keep it at this position in
5018 // the AST.
5019 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005020 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005021 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005022
5023 if (Notes.empty()) {
5024 // It's a constant expression.
5025 return Result;
5026 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005027 }
5028
5029 // It's not a constant expression. Produce an appropriate diagnostic.
5030 if (Notes.size() == 1 &&
5031 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5032 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5033 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005034 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005035 << CCE << From->getSourceRange();
5036 for (unsigned I = 0; I < Notes.size(); ++I)
5037 Diag(Notes[I].first, Notes[I].second);
5038 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005039 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005040}
5041
John McCall0bcc9bc2011-09-09 06:11:02 +00005042/// dropPointerConversions - If the given standard conversion sequence
5043/// involves any pointer conversions, remove them. This may change
5044/// the result type of the conversion sequence.
5045static void dropPointerConversion(StandardConversionSequence &SCS) {
5046 if (SCS.Second == ICK_Pointer_Conversion) {
5047 SCS.Second = ICK_Identity;
5048 SCS.Third = ICK_Identity;
5049 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5050 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005051}
John McCall120d63c2010-08-24 20:38:10 +00005052
John McCall0bcc9bc2011-09-09 06:11:02 +00005053/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5054/// convert the expression From to an Objective-C pointer type.
5055static ImplicitConversionSequence
5056TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5057 // Do an implicit conversion to 'id'.
5058 QualType Ty = S.Context.getObjCIdType();
5059 ImplicitConversionSequence ICS
5060 = TryImplicitConversion(S, From, Ty,
5061 // FIXME: Are these flags correct?
5062 /*SuppressUserConversions=*/false,
5063 /*AllowExplicit=*/true,
5064 /*InOverloadResolution=*/false,
5065 /*CStyle=*/false,
5066 /*AllowObjCWritebackConversion=*/false);
5067
5068 // Strip off any final conversions to 'id'.
5069 switch (ICS.getKind()) {
5070 case ImplicitConversionSequence::BadConversion:
5071 case ImplicitConversionSequence::AmbiguousConversion:
5072 case ImplicitConversionSequence::EllipsisConversion:
5073 break;
5074
5075 case ImplicitConversionSequence::UserDefinedConversion:
5076 dropPointerConversion(ICS.UserDefined.After);
5077 break;
5078
5079 case ImplicitConversionSequence::StandardConversion:
5080 dropPointerConversion(ICS.Standard);
5081 break;
5082 }
5083
5084 return ICS;
5085}
5086
5087/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5088/// conversion of the expression From to an Objective-C pointer type.
5089ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005090 if (checkPlaceholderForOverload(*this, From))
5091 return ExprError();
5092
John McCallc12c5bb2010-05-15 11:32:37 +00005093 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005094 ImplicitConversionSequence ICS =
5095 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005096 if (!ICS.isBad())
5097 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005098 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005099}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005100
Richard Smithf39aec12012-02-04 07:07:42 +00005101/// Determine whether the provided type is an integral type, or an enumeration
5102/// type of a permitted flavor.
5103static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5104 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5105 : T->isIntegralOrUnscopedEnumerationType();
5106}
5107
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005108/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005109/// enumeration type.
5110///
5111/// This routine will attempt to convert an expression of class type to an
5112/// integral or enumeration type, if that class type only has a single
5113/// conversion to an integral or enumeration type.
5114///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005115/// \param Loc The source location of the construct that requires the
5116/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005117///
James Dennett40ae6662012-06-22 08:52:37 +00005118/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005119///
James Dennett40ae6662012-06-22 08:52:37 +00005120/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005121///
Richard Smithf39aec12012-02-04 07:07:42 +00005122/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5123/// enumerations should be considered.
5124///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005125/// \returns The expression, converted to an integral or enumeration type if
5126/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005127ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005128Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005129 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005130 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005131 // We can't perform any more checking for type-dependent expressions.
5132 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005133 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134
Eli Friedmanceccab92012-01-26 00:26:18 +00005135 // Process placeholders immediately.
5136 if (From->hasPlaceholderType()) {
5137 ExprResult result = CheckPlaceholderExpr(From);
5138 if (result.isInvalid()) return result;
5139 From = result.take();
5140 }
5141
Douglas Gregorc30614b2010-06-29 23:17:37 +00005142 // If the expression already has integral or enumeration type, we're golden.
5143 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005144 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005145 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005146
5147 // FIXME: Check for missing '()' if T is a function type?
5148
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005149 // 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 +00005150 // expression of integral or enumeration type.
5151 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005152 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005153 if (!Diagnoser.Suppress)
5154 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005155 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005156 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
Douglas Gregorc30614b2010-06-29 23:17:37 +00005158 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005159 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005160 ICEConvertDiagnoser &Diagnoser;
5161 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005162
Douglas Gregorab41fe92012-05-04 22:38:52 +00005163 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5164 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005165
5166 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005167 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005168 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005169 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005170
5171 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005172 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173
Douglas Gregorc30614b2010-06-29 23:17:37 +00005174 // Look for a conversion to an integral or enumeration type.
5175 UnresolvedSet<4> ViableConversions;
5176 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005177 std::pair<CXXRecordDecl::conversion_iterator,
5178 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005179 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005180
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005181 bool HadMultipleCandidates
5182 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005183
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005184 for (CXXRecordDecl::conversion_iterator
5185 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005186 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005187 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5188 if (isIntegralOrEnumerationType(
5189 Conversion->getConversionType().getNonReferenceType(),
5190 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005191 if (Conversion->isExplicit())
5192 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5193 else
5194 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5195 }
Richard Smithf39aec12012-02-04 07:07:42 +00005196 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005197 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005198
Douglas Gregorc30614b2010-06-29 23:17:37 +00005199 switch (ViableConversions.size()) {
5200 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005201 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005202 DeclAccessPair Found = ExplicitConversions[0];
5203 CXXConversionDecl *Conversion
5204 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005205
Douglas Gregorc30614b2010-06-29 23:17:37 +00005206 // The user probably meant to invoke the given explicit
5207 // conversion; use it.
5208 QualType ConvTy
5209 = Conversion->getConversionType().getNonReferenceType();
5210 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005211 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005212
Douglas Gregorab41fe92012-05-04 22:38:52 +00005213 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005214 << FixItHint::CreateInsertion(From->getLocStart(),
5215 "static_cast<" + TypeStr + ">(")
5216 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5217 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005218 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005219
5220 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005221 // explicit conversion function.
5222 if (isSFINAEContext())
5223 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005224
Douglas Gregorc30614b2010-06-29 23:17:37 +00005225 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005226 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5227 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005228 if (Result.isInvalid())
5229 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005230 // Record usage of conversion in an implicit cast.
5231 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5232 CK_UserDefinedConversion,
5233 Result.get(), 0,
5234 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005235 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005236
Douglas Gregorc30614b2010-06-29 23:17:37 +00005237 // We'll complain below about a non-integral condition type.
5238 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005239
Douglas Gregorc30614b2010-06-29 23:17:37 +00005240 case 1: {
5241 // Apply this conversion.
5242 DeclAccessPair Found = ViableConversions[0];
5243 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005244
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005245 CXXConversionDecl *Conversion
5246 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5247 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005248 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005249 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005250 if (isSFINAEContext())
5251 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005252
Douglas Gregorab41fe92012-05-04 22:38:52 +00005253 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5254 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005256
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005257 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5258 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005259 if (Result.isInvalid())
5260 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005261 // Record usage of conversion in an implicit cast.
5262 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5263 CK_UserDefinedConversion,
5264 Result.get(), 0,
5265 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005266 break;
5267 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005268
Douglas Gregorc30614b2010-06-29 23:17:37 +00005269 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005270 if (Diagnoser.Suppress)
5271 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005272
Douglas Gregorab41fe92012-05-04 22:38:52 +00005273 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005274 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5275 CXXConversionDecl *Conv
5276 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5277 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005278 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005279 }
John McCall9ae2f072010-08-23 23:25:46 +00005280 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005282
Richard Smith282e7e62012-02-04 09:53:13 +00005283 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005284 !Diagnoser.Suppress) {
5285 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5286 << From->getSourceRange();
5287 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005288
Eli Friedmanceccab92012-01-26 00:26:18 +00005289 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005290}
5291
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005292/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005293/// candidate functions, using the given function call arguments. If
5294/// @p SuppressUserConversions, then don't allow user-defined
5295/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005296///
James Dennett699c9042012-06-15 07:13:21 +00005297/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005298/// based on an incomplete set of function arguments. This feature is used by
5299/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005300void
5301Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005302 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005303 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005304 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005305 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005306 bool PartialOverloading,
5307 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005308 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005309 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005310 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005311 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005312 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Douglas Gregor88a35142008-12-22 05:46:06 +00005314 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005315 if (!isa<CXXConstructorDecl>(Method)) {
5316 // If we get here, it's because we're calling a member function
5317 // that is named without a member access expression (e.g.,
5318 // "this->f") that was either written explicitly or created
5319 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005320 // function, e.g., X::f(). We use an empty type for the implied
5321 // object argument (C++ [over.call.func]p3), and the acting context
5322 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005323 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005324 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005325 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005326 return;
5327 }
5328 // We treat a constructor like a non-member function, since its object
5329 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005330 }
5331
Douglas Gregorfd476482009-11-13 23:59:09 +00005332 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005333 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005334
Douglas Gregor7edfb692009-11-23 12:27:39 +00005335 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005336 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005337
Douglas Gregor66724ea2009-11-14 01:20:54 +00005338 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5339 // C++ [class.copy]p3:
5340 // A member function template is never instantiated to perform the copy
5341 // of a class object to an object of its class type.
5342 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005343 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005344 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005345 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5346 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005347 return;
5348 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005350 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005351 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005352 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005353 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005354 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005355 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005356 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005357 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005358
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005359 unsigned NumArgsInProto = Proto->getNumArgs();
5360
5361 // (C++ 13.3.2p2): A candidate function having fewer than m
5362 // parameters is viable only if it has an ellipsis in its parameter
5363 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005364 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005365 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005366 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005367 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005368 return;
5369 }
5370
5371 // (C++ 13.3.2p2): A candidate function having more than m parameters
5372 // is viable only if the (m+1)st parameter has a default argument
5373 // (8.3.6). For the purposes of overload resolution, the
5374 // parameter list is truncated on the right, so that there are
5375 // exactly m parameters.
5376 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005377 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005378 // Not enough arguments.
5379 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005380 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005381 return;
5382 }
5383
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005384 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005385 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005386 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5387 if (CheckCUDATarget(Caller, Function)) {
5388 Candidate.Viable = false;
5389 Candidate.FailureKind = ovl_fail_bad_target;
5390 return;
5391 }
5392
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005393 // Determine the implicit conversion sequences for each of the
5394 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005395 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005396 if (ArgIdx < NumArgsInProto) {
5397 // (C++ 13.3.2p3): for F to be a viable function, there shall
5398 // exist for each argument an implicit conversion sequence
5399 // (13.3.3.1) that converts that argument to the corresponding
5400 // parameter of F.
5401 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005402 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005403 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005404 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005405 /*InOverloadResolution=*/true,
5406 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005407 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005408 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005409 if (Candidate.Conversions[ArgIdx].isBad()) {
5410 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005411 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005412 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005413 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005414 } else {
5415 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5416 // argument for which there is no corresponding parameter is
5417 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005418 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005419 }
5420 }
5421}
5422
Douglas Gregor063daf62009-03-13 18:40:31 +00005423/// \brief Add all of the function declarations in the given function set to
5424/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005425void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005426 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005427 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005428 bool SuppressUserConversions,
5429 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005430 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005431 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5432 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005433 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005434 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005435 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005436 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005437 Args.slice(1), CandidateSet,
5438 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005439 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005440 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005441 SuppressUserConversions);
5442 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005443 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005444 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5445 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005446 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005447 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005448 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005449 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005450 Args[0]->Classify(Context), Args.slice(1),
5451 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005452 else
John McCall9aa472c2010-03-19 07:35:19 +00005453 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005454 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005455 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005456 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005457 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005458}
5459
John McCall314be4e2009-11-17 07:50:12 +00005460/// AddMethodCandidate - Adds a named decl (which is some kind of
5461/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005462void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005463 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005464 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005465 Expr **Args, unsigned NumArgs,
5466 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005467 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005468 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005469 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005470
5471 if (isa<UsingShadowDecl>(Decl))
5472 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005473
John McCall314be4e2009-11-17 07:50:12 +00005474 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5475 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5476 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005477 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5478 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005479 ObjectType, ObjectClassification,
5480 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005481 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005482 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005483 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005484 ObjectType, ObjectClassification,
5485 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005486 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005487 }
5488}
5489
Douglas Gregor96176b32008-11-18 23:14:02 +00005490/// AddMethodCandidate - Adds the given C++ member function to the set
5491/// of candidate functions, using the given function call arguments
5492/// and the object argument (@c Object). For example, in a call
5493/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5494/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5495/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005496/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005497void
John McCall9aa472c2010-03-19 07:35:19 +00005498Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005499 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005500 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005501 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005502 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005503 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005504 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005505 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005506 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005507 assert(!isa<CXXConstructorDecl>(Method) &&
5508 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005509
Douglas Gregor3f396022009-09-28 04:47:19 +00005510 if (!CandidateSet.isNewCandidate(Method))
5511 return;
5512
Douglas Gregor7edfb692009-11-23 12:27:39 +00005513 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005514 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005515
Douglas Gregor96176b32008-11-18 23:14:02 +00005516 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005517 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005518 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005519 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005520 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005521 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005522 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005523
5524 unsigned NumArgsInProto = Proto->getNumArgs();
5525
5526 // (C++ 13.3.2p2): A candidate function having fewer than m
5527 // parameters is viable only if it has an ellipsis in its parameter
5528 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005529 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005530 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005531 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005532 return;
5533 }
5534
5535 // (C++ 13.3.2p2): A candidate function having more than m parameters
5536 // is viable only if the (m+1)st parameter has a default argument
5537 // (8.3.6). For the purposes of overload resolution, the
5538 // parameter list is truncated on the right, so that there are
5539 // exactly m parameters.
5540 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005541 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005542 // Not enough arguments.
5543 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005544 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005545 return;
5546 }
5547
5548 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005549
John McCall701c89e2009-12-03 04:06:58 +00005550 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005551 // The implicit object argument is ignored.
5552 Candidate.IgnoreObjectArgument = true;
5553 else {
5554 // Determine the implicit conversion sequence for the object
5555 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005556 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005557 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5558 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005559 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005560 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005561 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005562 return;
5563 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005564 }
5565
5566 // Determine the implicit conversion sequences for each of the
5567 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005568 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005569 if (ArgIdx < NumArgsInProto) {
5570 // (C++ 13.3.2p3): for F to be a viable function, there shall
5571 // exist for each argument an implicit conversion sequence
5572 // (13.3.3.1) that converts that argument to the corresponding
5573 // parameter of F.
5574 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005575 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005576 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005577 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005578 /*InOverloadResolution=*/true,
5579 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005580 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005581 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005582 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005583 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005584 break;
5585 }
5586 } else {
5587 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5588 // argument for which there is no corresponding parameter is
5589 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005590 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005591 }
5592 }
5593}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005594
Douglas Gregor6b906862009-08-21 00:16:32 +00005595/// \brief Add a C++ member function template as a candidate to the candidate
5596/// set, using template argument deduction to produce an appropriate member
5597/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005598void
Douglas Gregor6b906862009-08-21 00:16:32 +00005599Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005600 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005601 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005602 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005603 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005604 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005605 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005606 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005607 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005608 if (!CandidateSet.isNewCandidate(MethodTmpl))
5609 return;
5610
Douglas Gregor6b906862009-08-21 00:16:32 +00005611 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005612 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005613 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005614 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005615 // candidate functions in the usual way.113) A given name can refer to one
5616 // or more function templates and also to a set of overloaded non-template
5617 // functions. In such a case, the candidate functions generated from each
5618 // function template are combined with the set of non-template candidate
5619 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005620 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005621 FunctionDecl *Specialization = 0;
5622 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005623 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5624 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005625 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005626 Candidate.FoundDecl = FoundDecl;
5627 Candidate.Function = MethodTmpl->getTemplatedDecl();
5628 Candidate.Viable = false;
5629 Candidate.FailureKind = ovl_fail_bad_deduction;
5630 Candidate.IsSurrogate = false;
5631 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005632 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005633 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005634 Info);
5635 return;
5636 }
Mike Stump1eb44332009-09-09 15:08:12 +00005637
Douglas Gregor6b906862009-08-21 00:16:32 +00005638 // Add the function template specialization produced by template argument
5639 // deduction as a candidate.
5640 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005641 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005642 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005643 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005644 ActingContext, ObjectType, ObjectClassification, Args,
5645 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005646}
5647
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005648/// \brief Add a C++ function template specialization as a candidate
5649/// in the candidate set, using template argument deduction to produce
5650/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005651void
Douglas Gregore53060f2009-06-25 22:08:12 +00005652Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005653 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005654 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005655 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005656 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005657 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005658 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5659 return;
5660
Douglas Gregore53060f2009-06-25 22:08:12 +00005661 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005662 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005663 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005664 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005665 // candidate functions in the usual way.113) A given name can refer to one
5666 // or more function templates and also to a set of overloaded non-template
5667 // functions. In such a case, the candidate functions generated from each
5668 // function template are combined with the set of non-template candidate
5669 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005670 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005671 FunctionDecl *Specialization = 0;
5672 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005673 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5674 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005675 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005676 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005677 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5678 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005679 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005680 Candidate.IsSurrogate = false;
5681 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005682 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005683 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005684 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005685 return;
5686 }
Mike Stump1eb44332009-09-09 15:08:12 +00005687
Douglas Gregore53060f2009-06-25 22:08:12 +00005688 // Add the function template specialization produced by template argument
5689 // deduction as a candidate.
5690 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005691 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005692 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005693}
Mike Stump1eb44332009-09-09 15:08:12 +00005694
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005695/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005696/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005697/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005698/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005699/// (which may or may not be the same type as the type that the
5700/// conversion function produces).
5701void
5702Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005703 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005704 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005705 Expr *From, QualType ToType,
5706 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005707 assert(!Conversion->getDescribedFunctionTemplate() &&
5708 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005709 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005710 if (!CandidateSet.isNewCandidate(Conversion))
5711 return;
5712
Douglas Gregor7edfb692009-11-23 12:27:39 +00005713 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005714 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005715
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005716 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005717 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005718 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005719 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005720 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005721 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005722 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005723 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005724 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005725 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005726 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005727
Douglas Gregorbca39322010-08-19 15:37:02 +00005728 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005729 // For conversion functions, the function is considered to be a member of
5730 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005731 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005732 //
5733 // Determine the implicit conversion sequence for the implicit
5734 // object parameter.
5735 QualType ImplicitParamType = From->getType();
5736 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5737 ImplicitParamType = FromPtrType->getPointeeType();
5738 CXXRecordDecl *ConversionContext
5739 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005741 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005742 = TryObjectArgumentInitialization(*this, From->getType(),
5743 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005744 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005745
John McCall1d318332010-01-12 00:44:57 +00005746 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005747 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005748 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005749 return;
5750 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005751
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005752 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005753 // derived to base as such conversions are given Conversion Rank. They only
5754 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5755 QualType FromCanon
5756 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5757 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5758 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5759 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005760 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005761 return;
5762 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005763
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005764 // To determine what the conversion from the result of calling the
5765 // conversion function to the type we're eventually trying to
5766 // convert to (ToType), we need to synthesize a call to the
5767 // conversion function and attempt copy initialization from it. This
5768 // makes sure that we get the right semantics with respect to
5769 // lvalues/rvalues and the type. Fortunately, we can allocate this
5770 // call on the stack and we don't need its arguments to be
5771 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005772 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005773 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005774 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5775 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005776 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005777 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005778
Richard Smith87c1f1f2011-07-13 22:53:21 +00005779 QualType ConversionType = Conversion->getConversionType();
5780 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005781 Candidate.Viable = false;
5782 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5783 return;
5784 }
5785
Richard Smith87c1f1f2011-07-13 22:53:21 +00005786 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005787
Mike Stump1eb44332009-09-09 15:08:12 +00005788 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005789 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5790 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005791 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005792 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005793 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005794 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005795 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005796 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005797 /*InOverloadResolution=*/false,
5798 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005799
John McCall1d318332010-01-12 00:44:57 +00005800 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005801 case ImplicitConversionSequence::StandardConversion:
5802 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005803
Douglas Gregorc520c842010-04-12 23:42:09 +00005804 // C++ [over.ics.user]p3:
5805 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005806 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005807 // shall have exact match rank.
5808 if (Conversion->getPrimaryTemplate() &&
5809 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5810 Candidate.Viable = false;
5811 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005813
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005814 // C++0x [dcl.init.ref]p5:
5815 // In the second case, if the reference is an rvalue reference and
5816 // the second standard conversion sequence of the user-defined
5817 // conversion sequence includes an lvalue-to-rvalue conversion, the
5818 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005819 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005820 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5821 Candidate.Viable = false;
5822 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5823 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005824 break;
5825
5826 case ImplicitConversionSequence::BadConversion:
5827 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005828 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005829 break;
5830
5831 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005832 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005833 "Can only end up with a standard conversion sequence or failure");
5834 }
5835}
5836
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005837/// \brief Adds a conversion function template specialization
5838/// candidate to the overload set, using template argument deduction
5839/// to deduce the template arguments of the conversion function
5840/// template from the type that we are converting to (C++
5841/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005842void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005843Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005844 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005845 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005846 Expr *From, QualType ToType,
5847 OverloadCandidateSet &CandidateSet) {
5848 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5849 "Only conversion function templates permitted here");
5850
Douglas Gregor3f396022009-09-28 04:47:19 +00005851 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5852 return;
5853
Craig Topper93e45992012-09-19 02:26:47 +00005854 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005855 CXXConversionDecl *Specialization = 0;
5856 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005857 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005858 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005859 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005860 Candidate.FoundDecl = FoundDecl;
5861 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5862 Candidate.Viable = false;
5863 Candidate.FailureKind = ovl_fail_bad_deduction;
5864 Candidate.IsSurrogate = false;
5865 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005866 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005867 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005868 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005869 return;
5870 }
Mike Stump1eb44332009-09-09 15:08:12 +00005871
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005872 // Add the conversion function template specialization produced by
5873 // template argument deduction as a candidate.
5874 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005875 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005876 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005877}
5878
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005879/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5880/// converts the given @c Object to a function pointer via the
5881/// conversion function @c Conversion, and then attempts to call it
5882/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5883/// the type of function that we'll eventually be calling.
5884void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005885 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005886 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005887 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005888 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005889 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005890 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005891 if (!CandidateSet.isNewCandidate(Conversion))
5892 return;
5893
Douglas Gregor7edfb692009-11-23 12:27:39 +00005894 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005895 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005896
Ahmed Charles13a140c2012-02-25 11:00:22 +00005897 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005898 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005899 Candidate.Function = 0;
5900 Candidate.Surrogate = Conversion;
5901 Candidate.Viable = true;
5902 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005903 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005904 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005905
5906 // Determine the implicit conversion sequence for the implicit
5907 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005908 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005909 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005910 Object->Classify(Context),
5911 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005912 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005913 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005914 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005915 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005916 return;
5917 }
5918
5919 // The first conversion is actually a user-defined conversion whose
5920 // first conversion is ObjectInit's standard conversion (which is
5921 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005922 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005923 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005924 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005925 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005926 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005927 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005928 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005929 = Candidate.Conversions[0].UserDefined.Before;
5930 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5931
Mike Stump1eb44332009-09-09 15:08:12 +00005932 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005933 unsigned NumArgsInProto = Proto->getNumArgs();
5934
5935 // (C++ 13.3.2p2): A candidate function having fewer than m
5936 // parameters is viable only if it has an ellipsis in its parameter
5937 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005938 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005939 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005940 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005941 return;
5942 }
5943
5944 // Function types don't have any default arguments, so just check if
5945 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005946 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005947 // Not enough arguments.
5948 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005949 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005950 return;
5951 }
5952
5953 // Determine the implicit conversion sequences for each of the
5954 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005955 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005956 if (ArgIdx < NumArgsInProto) {
5957 // (C++ 13.3.2p3): for F to be a viable function, there shall
5958 // exist for each argument an implicit conversion sequence
5959 // (13.3.3.1) that converts that argument to the corresponding
5960 // parameter of F.
5961 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005962 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005963 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005964 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005965 /*InOverloadResolution=*/false,
5966 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005967 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005968 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005969 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005970 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005971 break;
5972 }
5973 } else {
5974 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5975 // argument for which there is no corresponding parameter is
5976 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005977 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005978 }
5979 }
5980}
5981
Douglas Gregor063daf62009-03-13 18:40:31 +00005982/// \brief Add overload candidates for overloaded operators that are
5983/// member functions.
5984///
5985/// Add the overloaded operator candidates that are member functions
5986/// for the operator Op that was used in an operator expression such
5987/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5988/// CandidateSet will store the added overload candidates. (C++
5989/// [over.match.oper]).
5990void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5991 SourceLocation OpLoc,
5992 Expr **Args, unsigned NumArgs,
5993 OverloadCandidateSet& CandidateSet,
5994 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005995 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5996
5997 // C++ [over.match.oper]p3:
5998 // For a unary operator @ with an operand of a type whose
5999 // cv-unqualified version is T1, and for a binary operator @ with
6000 // a left operand of a type whose cv-unqualified version is T1 and
6001 // a right operand of a type whose cv-unqualified version is T2,
6002 // three sets of candidate functions, designated member
6003 // candidates, non-member candidates and built-in candidates, are
6004 // constructed as follows:
6005 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006006
6007 // -- If T1 is a class type, the set of member candidates is the
6008 // result of the qualified lookup of T1::operator@
6009 // (13.3.1.1.1); otherwise, the set of member candidates is
6010 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006011 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006012 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00006013 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006014 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006015
John McCalla24dc2e2009-11-17 02:14:36 +00006016 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6017 LookupQualifiedName(Operators, T1Rec->getDecl());
6018 Operators.suppressDiagnostics();
6019
Mike Stump1eb44332009-09-09 15:08:12 +00006020 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006021 OperEnd = Operators.end();
6022 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006023 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006024 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006025 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006026 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006027 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006028 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006029}
6030
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006031/// AddBuiltinCandidate - Add a candidate for a built-in
6032/// operator. ResultTy and ParamTys are the result and parameter types
6033/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006034/// arguments being passed to the candidate. IsAssignmentOperator
6035/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006036/// operator. NumContextualBoolArguments is the number of arguments
6037/// (at the beginning of the argument list) that will be contextually
6038/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006039void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006040 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006041 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006042 bool IsAssignmentOperator,
6043 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006044 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006045 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006046
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006047 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006048 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006049 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006050 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006051 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006052 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006053 Candidate.BuiltinTypes.ResultTy = ResultTy;
6054 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6055 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6056
6057 // Determine the implicit conversion sequences for each of the
6058 // arguments.
6059 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006060 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006062 // C++ [over.match.oper]p4:
6063 // For the built-in assignment operators, conversions of the
6064 // left operand are restricted as follows:
6065 // -- no temporaries are introduced to hold the left operand, and
6066 // -- no user-defined conversions are applied to the left
6067 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006068 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006069 //
6070 // We block these conversions by turning off user-defined
6071 // conversions, since that is the only way that initialization of
6072 // a reference to a non-class type can occur from something that
6073 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006074 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006075 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006076 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006077 Candidate.Conversions[ArgIdx]
6078 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006079 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006080 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006081 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006082 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006083 /*InOverloadResolution=*/false,
6084 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006085 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006086 }
John McCall1d318332010-01-12 00:44:57 +00006087 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006088 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006089 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006090 break;
6091 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006092 }
6093}
6094
6095/// BuiltinCandidateTypeSet - A set of types that will be used for the
6096/// candidate operator functions for built-in operators (C++
6097/// [over.built]). The types are separated into pointer types and
6098/// enumeration types.
6099class BuiltinCandidateTypeSet {
6100 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006101 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006102
6103 /// PointerTypes - The set of pointer types that will be used in the
6104 /// built-in candidates.
6105 TypeSet PointerTypes;
6106
Sebastian Redl78eb8742009-04-19 21:53:20 +00006107 /// MemberPointerTypes - The set of member pointer types that will be
6108 /// used in the built-in candidates.
6109 TypeSet MemberPointerTypes;
6110
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006111 /// EnumerationTypes - The set of enumeration types that will be
6112 /// used in the built-in candidates.
6113 TypeSet EnumerationTypes;
6114
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006115 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006116 /// candidates.
6117 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006118
6119 /// \brief A flag indicating non-record types are viable candidates
6120 bool HasNonRecordTypes;
6121
6122 /// \brief A flag indicating whether either arithmetic or enumeration types
6123 /// were present in the candidate set.
6124 bool HasArithmeticOrEnumeralTypes;
6125
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006126 /// \brief A flag indicating whether the nullptr type was present in the
6127 /// candidate set.
6128 bool HasNullPtrType;
6129
Douglas Gregor5842ba92009-08-24 15:23:48 +00006130 /// Sema - The semantic analysis instance where we are building the
6131 /// candidate type set.
6132 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006133
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006134 /// Context - The AST context in which we will build the type sets.
6135 ASTContext &Context;
6136
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006137 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6138 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006139 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006140
6141public:
6142 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006143 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006144
Mike Stump1eb44332009-09-09 15:08:12 +00006145 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006146 : HasNonRecordTypes(false),
6147 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006148 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006149 SemaRef(SemaRef),
6150 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006151
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006152 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006153 SourceLocation Loc,
6154 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006155 bool AllowExplicitConversions,
6156 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006157
6158 /// pointer_begin - First pointer type found;
6159 iterator pointer_begin() { return PointerTypes.begin(); }
6160
Sebastian Redl78eb8742009-04-19 21:53:20 +00006161 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006162 iterator pointer_end() { return PointerTypes.end(); }
6163
Sebastian Redl78eb8742009-04-19 21:53:20 +00006164 /// member_pointer_begin - First member pointer type found;
6165 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6166
6167 /// member_pointer_end - Past the last member pointer type found;
6168 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6169
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006170 /// enumeration_begin - First enumeration type found;
6171 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6172
Sebastian Redl78eb8742009-04-19 21:53:20 +00006173 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006174 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006175
Douglas Gregor26bcf672010-05-19 03:21:00 +00006176 iterator vector_begin() { return VectorTypes.begin(); }
6177 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006178
6179 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6180 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006181 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006182};
6183
Sebastian Redl78eb8742009-04-19 21:53:20 +00006184/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006185/// the set of pointer types along with any more-qualified variants of
6186/// that type. For example, if @p Ty is "int const *", this routine
6187/// will add "int const *", "int const volatile *", "int const
6188/// restrict *", and "int const volatile restrict *" to the set of
6189/// pointer types. Returns true if the add of @p Ty itself succeeded,
6190/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006191///
6192/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006193bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006194BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6195 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006196
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006197 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006198 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006199 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006200
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006201 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006202 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006203 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006204 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006205 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6206 PointeeTy = PTy->getPointeeType();
6207 buildObjCPtr = true;
6208 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006209 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006210 }
6211
Sebastian Redla9efada2009-11-18 20:39:26 +00006212 // Don't add qualified variants of arrays. For one, they're not allowed
6213 // (the qualifier would sink to the element type), and for another, the
6214 // only overload situation where it matters is subscript or pointer +- int,
6215 // and those shouldn't have qualifier variants anyway.
6216 if (PointeeTy->isArrayType())
6217 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006218
John McCall0953e762009-09-24 19:53:00 +00006219 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006220 bool hasVolatile = VisibleQuals.hasVolatile();
6221 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006222
John McCall0953e762009-09-24 19:53:00 +00006223 // Iterate through all strict supersets of BaseCVR.
6224 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6225 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006226 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006227 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006228
6229 // Skip over restrict if no restrict found anywhere in the types, or if
6230 // the type cannot be restrict-qualified.
6231 if ((CVR & Qualifiers::Restrict) &&
6232 (!hasRestrict ||
6233 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6234 continue;
6235
6236 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006237 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006238
6239 // Build qualified pointer type.
6240 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006241 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006242 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006243 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006244 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6245
6246 // Insert qualified pointer type.
6247 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006248 }
6249
6250 return true;
6251}
6252
Sebastian Redl78eb8742009-04-19 21:53:20 +00006253/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6254/// to the set of pointer types along with any more-qualified variants of
6255/// that type. For example, if @p Ty is "int const *", this routine
6256/// will add "int const *", "int const volatile *", "int const
6257/// restrict *", and "int const volatile restrict *" to the set of
6258/// pointer types. Returns true if the add of @p Ty itself succeeded,
6259/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006260///
6261/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006262bool
6263BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6264 QualType Ty) {
6265 // Insert this type.
6266 if (!MemberPointerTypes.insert(Ty))
6267 return false;
6268
John McCall0953e762009-09-24 19:53:00 +00006269 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6270 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006271
John McCall0953e762009-09-24 19:53:00 +00006272 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006273 // Don't add qualified variants of arrays. For one, they're not allowed
6274 // (the qualifier would sink to the element type), and for another, the
6275 // only overload situation where it matters is subscript or pointer +- int,
6276 // and those shouldn't have qualifier variants anyway.
6277 if (PointeeTy->isArrayType())
6278 return true;
John McCall0953e762009-09-24 19:53:00 +00006279 const Type *ClassTy = PointerTy->getClass();
6280
6281 // Iterate through all strict supersets of the pointee type's CVR
6282 // qualifiers.
6283 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6284 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6285 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006286
John McCall0953e762009-09-24 19:53:00 +00006287 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006288 MemberPointerTypes.insert(
6289 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006290 }
6291
6292 return true;
6293}
6294
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006295/// AddTypesConvertedFrom - Add each of the types to which the type @p
6296/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006297/// primarily interested in pointer types and enumeration types. We also
6298/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006299/// AllowUserConversions is true if we should look at the conversion
6300/// functions of a class type, and AllowExplicitConversions if we
6301/// should also include the explicit conversion functions of a class
6302/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006303void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006304BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006305 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006306 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006307 bool AllowExplicitConversions,
6308 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006309 // Only deal with canonical types.
6310 Ty = Context.getCanonicalType(Ty);
6311
6312 // Look through reference types; they aren't part of the type of an
6313 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006314 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006315 Ty = RefTy->getPointeeType();
6316
John McCall3b657512011-01-19 10:06:00 +00006317 // If we're dealing with an array type, decay to the pointer.
6318 if (Ty->isArrayType())
6319 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6320
6321 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006322 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006323
Chandler Carruth6a577462010-12-13 01:44:01 +00006324 // Flag if we ever add a non-record type.
6325 const RecordType *TyRec = Ty->getAs<RecordType>();
6326 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6327
Chandler Carruth6a577462010-12-13 01:44:01 +00006328 // Flag if we encounter an arithmetic type.
6329 HasArithmeticOrEnumeralTypes =
6330 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6331
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006332 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6333 PointerTypes.insert(Ty);
6334 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006335 // Insert our type, and its more-qualified variants, into the set
6336 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006337 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006338 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006339 } else if (Ty->isMemberPointerType()) {
6340 // Member pointers are far easier, since the pointee can't be converted.
6341 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6342 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006343 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006344 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006345 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006346 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006347 // We treat vector types as arithmetic types in many contexts as an
6348 // extension.
6349 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006350 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006351 } else if (Ty->isNullPtrType()) {
6352 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006353 } else if (AllowUserConversions && TyRec) {
6354 // No conversion functions in incomplete types.
6355 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6356 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006357
Chandler Carruth6a577462010-12-13 01:44:01 +00006358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006359 std::pair<CXXRecordDecl::conversion_iterator,
6360 CXXRecordDecl::conversion_iterator>
6361 Conversions = ClassDecl->getVisibleConversionFunctions();
6362 for (CXXRecordDecl::conversion_iterator
6363 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006364 NamedDecl *D = I.getDecl();
6365 if (isa<UsingShadowDecl>(D))
6366 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006367
Chandler Carruth6a577462010-12-13 01:44:01 +00006368 // Skip conversion function templates; they don't tell us anything
6369 // about which builtin types we can convert to.
6370 if (isa<FunctionTemplateDecl>(D))
6371 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006372
Chandler Carruth6a577462010-12-13 01:44:01 +00006373 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6374 if (AllowExplicitConversions || !Conv->isExplicit()) {
6375 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6376 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006377 }
6378 }
6379 }
6380}
6381
Douglas Gregor19b7b152009-08-24 13:43:27 +00006382/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6383/// the volatile- and non-volatile-qualified assignment operators for the
6384/// given type to the candidate set.
6385static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6386 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006387 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006388 unsigned NumArgs,
6389 OverloadCandidateSet &CandidateSet) {
6390 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006391
Douglas Gregor19b7b152009-08-24 13:43:27 +00006392 // T& operator=(T&, T)
6393 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6394 ParamTypes[1] = T;
6395 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6396 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006397
Douglas Gregor19b7b152009-08-24 13:43:27 +00006398 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6399 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006400 ParamTypes[0]
6401 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006402 ParamTypes[1] = T;
6403 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006404 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006405 }
6406}
Mike Stump1eb44332009-09-09 15:08:12 +00006407
Sebastian Redl9994a342009-10-25 17:03:50 +00006408/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6409/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006410static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6411 Qualifiers VRQuals;
6412 const RecordType *TyRec;
6413 if (const MemberPointerType *RHSMPType =
6414 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006415 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006416 else
6417 TyRec = ArgExpr->getType()->getAs<RecordType>();
6418 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006419 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006420 VRQuals.addVolatile();
6421 VRQuals.addRestrict();
6422 return VRQuals;
6423 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006424
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006425 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006426 if (!ClassDecl->hasDefinition())
6427 return VRQuals;
6428
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006429 std::pair<CXXRecordDecl::conversion_iterator,
6430 CXXRecordDecl::conversion_iterator>
6431 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006432
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006433 for (CXXRecordDecl::conversion_iterator
6434 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006435 NamedDecl *D = I.getDecl();
6436 if (isa<UsingShadowDecl>(D))
6437 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6438 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006439 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6440 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6441 CanTy = ResTypeRef->getPointeeType();
6442 // Need to go down the pointer/mempointer chain and add qualifiers
6443 // as see them.
6444 bool done = false;
6445 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006446 if (CanTy.isRestrictQualified())
6447 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006448 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6449 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006450 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006451 CanTy->getAs<MemberPointerType>())
6452 CanTy = ResTypeMPtr->getPointeeType();
6453 else
6454 done = true;
6455 if (CanTy.isVolatileQualified())
6456 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006457 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6458 return VRQuals;
6459 }
6460 }
6461 }
6462 return VRQuals;
6463}
John McCall00071ec2010-11-13 05:51:15 +00006464
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006465namespace {
John McCall00071ec2010-11-13 05:51:15 +00006466
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006467/// \brief Helper class to manage the addition of builtin operator overload
6468/// candidates. It provides shared state and utility methods used throughout
6469/// the process, as well as a helper method to add each group of builtin
6470/// operator overloads from the standard to a candidate set.
6471class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006472 // Common instance state available to all overload candidate addition methods.
6473 Sema &S;
6474 Expr **Args;
6475 unsigned NumArgs;
6476 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006477 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006478 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006479 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006480
Chandler Carruth6d695582010-12-12 10:35:00 +00006481 // Define some constants used to index and iterate over the arithemetic types
6482 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006483 // The "promoted arithmetic types" are the arithmetic
6484 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006485 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006486 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006487 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006488 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006489 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006490 LastPromotedArithmeticType = 11;
6491 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006492
Chandler Carruth6d695582010-12-12 10:35:00 +00006493 /// \brief Get the canonical type for a given arithmetic type index.
6494 CanQualType getArithmeticType(unsigned index) {
6495 assert(index < NumArithmeticTypes);
6496 static CanQualType ASTContext::* const
6497 ArithmeticTypes[NumArithmeticTypes] = {
6498 // Start of promoted types.
6499 &ASTContext::FloatTy,
6500 &ASTContext::DoubleTy,
6501 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006502
Chandler Carruth6d695582010-12-12 10:35:00 +00006503 // Start of integral types.
6504 &ASTContext::IntTy,
6505 &ASTContext::LongTy,
6506 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006507 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006508 &ASTContext::UnsignedIntTy,
6509 &ASTContext::UnsignedLongTy,
6510 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006511 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006512 // End of promoted types.
6513
6514 &ASTContext::BoolTy,
6515 &ASTContext::CharTy,
6516 &ASTContext::WCharTy,
6517 &ASTContext::Char16Ty,
6518 &ASTContext::Char32Ty,
6519 &ASTContext::SignedCharTy,
6520 &ASTContext::ShortTy,
6521 &ASTContext::UnsignedCharTy,
6522 &ASTContext::UnsignedShortTy,
6523 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006524 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006525 };
6526 return S.Context.*ArithmeticTypes[index];
6527 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006528
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006529 /// \brief Gets the canonical type resulting from the usual arithemetic
6530 /// converions for the given arithmetic types.
6531 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6532 // Accelerator table for performing the usual arithmetic conversions.
6533 // The rules are basically:
6534 // - if either is floating-point, use the wider floating-point
6535 // - if same signedness, use the higher rank
6536 // - if same size, use unsigned of the higher rank
6537 // - use the larger type
6538 // These rules, together with the axiom that higher ranks are
6539 // never smaller, are sufficient to precompute all of these results
6540 // *except* when dealing with signed types of higher rank.
6541 // (we could precompute SLL x UI for all known platforms, but it's
6542 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006543 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006544 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006545 Dep=-1,
6546 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006547 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006548 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006549 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006550/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6551/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6552/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6553/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6554/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6555/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6556/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6557/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6558/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6559/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6560/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006561 };
6562
6563 assert(L < LastPromotedArithmeticType);
6564 assert(R < LastPromotedArithmeticType);
6565 int Idx = ConversionsTable[L][R];
6566
6567 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006568 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006569
6570 // Slow path: we need to compare widths.
6571 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006572 CanQualType LT = getArithmeticType(L),
6573 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006574 unsigned LW = S.Context.getIntWidth(LT),
6575 RW = S.Context.getIntWidth(RT);
6576
6577 // If they're different widths, use the signed type.
6578 if (LW > RW) return LT;
6579 else if (LW < RW) return RT;
6580
6581 // Otherwise, use the unsigned type of the signed type's rank.
6582 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6583 assert(L == SLL || R == SLL);
6584 return S.Context.UnsignedLongLongTy;
6585 }
6586
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006587 /// \brief Helper method to factor out the common pattern of adding overloads
6588 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006589 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006590 bool HasVolatile,
6591 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006592 QualType ParamTypes[2] = {
6593 S.Context.getLValueReferenceType(CandidateTy),
6594 S.Context.IntTy
6595 };
6596
6597 // Non-volatile version.
6598 if (NumArgs == 1)
6599 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6600 else
6601 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6602
6603 // Use a heuristic to reduce number of builtin candidates in the set:
6604 // add volatile version only if there are conversions to a volatile type.
6605 if (HasVolatile) {
6606 ParamTypes[0] =
6607 S.Context.getLValueReferenceType(
6608 S.Context.getVolatileType(CandidateTy));
6609 if (NumArgs == 1)
6610 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6611 else
6612 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6613 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006614
6615 // Add restrict version only if there are conversions to a restrict type
6616 // and our candidate type is a non-restrict-qualified pointer.
6617 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6618 !CandidateTy.isRestrictQualified()) {
6619 ParamTypes[0]
6620 = S.Context.getLValueReferenceType(
6621 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6622 if (NumArgs == 1)
6623 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6624 else
6625 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6626
6627 if (HasVolatile) {
6628 ParamTypes[0]
6629 = S.Context.getLValueReferenceType(
6630 S.Context.getCVRQualifiedType(CandidateTy,
6631 (Qualifiers::Volatile |
6632 Qualifiers::Restrict)));
6633 if (NumArgs == 1)
6634 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6635 CandidateSet);
6636 else
6637 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6638 }
6639 }
6640
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006641 }
6642
6643public:
6644 BuiltinOperatorOverloadBuilder(
6645 Sema &S, Expr **Args, unsigned NumArgs,
6646 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006647 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006648 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006649 OverloadCandidateSet &CandidateSet)
6650 : S(S), Args(Args), NumArgs(NumArgs),
6651 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006652 HasArithmeticOrEnumeralCandidateType(
6653 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006654 CandidateTypes(CandidateTypes),
6655 CandidateSet(CandidateSet) {
6656 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006657 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006658 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006659 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006660 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006661 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006662 assert(getArithmeticType(FirstPromotedArithmeticType)
6663 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006664 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006665 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006666 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006667 "Invalid last promoted arithmetic type");
6668 }
6669
6670 // C++ [over.built]p3:
6671 //
6672 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6673 // is either volatile or empty, there exist candidate operator
6674 // functions of the form
6675 //
6676 // VQ T& operator++(VQ T&);
6677 // T operator++(VQ T&, int);
6678 //
6679 // C++ [over.built]p4:
6680 //
6681 // For every pair (T, VQ), where T is an arithmetic type other
6682 // than bool, and VQ is either volatile or empty, there exist
6683 // candidate operator functions of the form
6684 //
6685 // VQ T& operator--(VQ T&);
6686 // T operator--(VQ T&, int);
6687 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006688 if (!HasArithmeticOrEnumeralCandidateType)
6689 return;
6690
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006691 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6692 Arith < NumArithmeticTypes; ++Arith) {
6693 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006694 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006695 VisibleTypeConversionsQuals.hasVolatile(),
6696 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006697 }
6698 }
6699
6700 // C++ [over.built]p5:
6701 //
6702 // For every pair (T, VQ), where T is a cv-qualified or
6703 // cv-unqualified object type, and VQ is either volatile or
6704 // empty, there exist candidate operator functions of the form
6705 //
6706 // T*VQ& operator++(T*VQ&);
6707 // T*VQ& operator--(T*VQ&);
6708 // T* operator++(T*VQ&, int);
6709 // T* operator--(T*VQ&, int);
6710 void addPlusPlusMinusMinusPointerOverloads() {
6711 for (BuiltinCandidateTypeSet::iterator
6712 Ptr = CandidateTypes[0].pointer_begin(),
6713 PtrEnd = CandidateTypes[0].pointer_end();
6714 Ptr != PtrEnd; ++Ptr) {
6715 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006716 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006717 continue;
6718
6719 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006720 (!(*Ptr).isVolatileQualified() &&
6721 VisibleTypeConversionsQuals.hasVolatile()),
6722 (!(*Ptr).isRestrictQualified() &&
6723 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006724 }
6725 }
6726
6727 // C++ [over.built]p6:
6728 // For every cv-qualified or cv-unqualified object type T, there
6729 // exist candidate operator functions of the form
6730 //
6731 // T& operator*(T*);
6732 //
6733 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006734 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006735 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006736 // T& operator*(T*);
6737 void addUnaryStarPointerOverloads() {
6738 for (BuiltinCandidateTypeSet::iterator
6739 Ptr = CandidateTypes[0].pointer_begin(),
6740 PtrEnd = CandidateTypes[0].pointer_end();
6741 Ptr != PtrEnd; ++Ptr) {
6742 QualType ParamTy = *Ptr;
6743 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006744 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6745 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006746
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006747 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6748 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6749 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006750
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006751 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6752 &ParamTy, Args, 1, CandidateSet);
6753 }
6754 }
6755
6756 // C++ [over.built]p9:
6757 // For every promoted arithmetic type T, there exist candidate
6758 // operator functions of the form
6759 //
6760 // T operator+(T);
6761 // T operator-(T);
6762 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006763 if (!HasArithmeticOrEnumeralCandidateType)
6764 return;
6765
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006766 for (unsigned Arith = FirstPromotedArithmeticType;
6767 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006768 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006769 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6770 }
6771
6772 // Extension: We also add these operators for vector types.
6773 for (BuiltinCandidateTypeSet::iterator
6774 Vec = CandidateTypes[0].vector_begin(),
6775 VecEnd = CandidateTypes[0].vector_end();
6776 Vec != VecEnd; ++Vec) {
6777 QualType VecTy = *Vec;
6778 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6779 }
6780 }
6781
6782 // C++ [over.built]p8:
6783 // For every type T, there exist candidate operator functions of
6784 // the form
6785 //
6786 // T* operator+(T*);
6787 void addUnaryPlusPointerOverloads() {
6788 for (BuiltinCandidateTypeSet::iterator
6789 Ptr = CandidateTypes[0].pointer_begin(),
6790 PtrEnd = CandidateTypes[0].pointer_end();
6791 Ptr != PtrEnd; ++Ptr) {
6792 QualType ParamTy = *Ptr;
6793 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6794 }
6795 }
6796
6797 // C++ [over.built]p10:
6798 // For every promoted integral type T, there exist candidate
6799 // operator functions of the form
6800 //
6801 // T operator~(T);
6802 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006803 if (!HasArithmeticOrEnumeralCandidateType)
6804 return;
6805
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006806 for (unsigned Int = FirstPromotedIntegralType;
6807 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006808 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006809 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6810 }
6811
6812 // Extension: We also add this operator for vector types.
6813 for (BuiltinCandidateTypeSet::iterator
6814 Vec = CandidateTypes[0].vector_begin(),
6815 VecEnd = CandidateTypes[0].vector_end();
6816 Vec != VecEnd; ++Vec) {
6817 QualType VecTy = *Vec;
6818 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6819 }
6820 }
6821
6822 // C++ [over.match.oper]p16:
6823 // For every pointer to member type T, there exist candidate operator
6824 // functions of the form
6825 //
6826 // bool operator==(T,T);
6827 // bool operator!=(T,T);
6828 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6829 /// Set of (canonical) types that we've already handled.
6830 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6831
6832 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6833 for (BuiltinCandidateTypeSet::iterator
6834 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6835 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6836 MemPtr != MemPtrEnd;
6837 ++MemPtr) {
6838 // Don't add the same builtin candidate twice.
6839 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6840 continue;
6841
6842 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6843 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6844 CandidateSet);
6845 }
6846 }
6847 }
6848
6849 // C++ [over.built]p15:
6850 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006851 // For every T, where T is an enumeration type, a pointer type, or
6852 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006853 //
6854 // bool operator<(T, T);
6855 // bool operator>(T, T);
6856 // bool operator<=(T, T);
6857 // bool operator>=(T, T);
6858 // bool operator==(T, T);
6859 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006860 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006861 // C++ [over.match.oper]p3:
6862 // [...]the built-in candidates include all of the candidate operator
6863 // functions defined in 13.6 that, compared to the given operator, [...]
6864 // do not have the same parameter-type-list as any non-template non-member
6865 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006866 //
Eli Friedman97c67392012-09-18 21:52:24 +00006867 // Note that in practice, this only affects enumeration types because there
6868 // aren't any built-in candidates of record type, and a user-defined operator
6869 // must have an operand of record or enumeration type. Also, the only other
6870 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006871 // cannot be overloaded for enumeration types, so this is the only place
6872 // where we must suppress candidates like this.
6873 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6874 UserDefinedBinaryOperators;
6875
6876 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6877 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6878 CandidateTypes[ArgIdx].enumeration_end()) {
6879 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6880 CEnd = CandidateSet.end();
6881 C != CEnd; ++C) {
6882 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6883 continue;
6884
Eli Friedman97c67392012-09-18 21:52:24 +00006885 if (C->Function->isFunctionTemplateSpecialization())
6886 continue;
6887
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006888 QualType FirstParamType =
6889 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6890 QualType SecondParamType =
6891 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6892
6893 // Skip if either parameter isn't of enumeral type.
6894 if (!FirstParamType->isEnumeralType() ||
6895 !SecondParamType->isEnumeralType())
6896 continue;
6897
6898 // Add this operator to the set of known user-defined operators.
6899 UserDefinedBinaryOperators.insert(
6900 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6901 S.Context.getCanonicalType(SecondParamType)));
6902 }
6903 }
6904 }
6905
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006906 /// Set of (canonical) types that we've already handled.
6907 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6908
6909 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6910 for (BuiltinCandidateTypeSet::iterator
6911 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6912 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6913 Ptr != PtrEnd; ++Ptr) {
6914 // Don't add the same builtin candidate twice.
6915 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6916 continue;
6917
6918 QualType ParamTypes[2] = { *Ptr, *Ptr };
6919 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6920 CandidateSet);
6921 }
6922 for (BuiltinCandidateTypeSet::iterator
6923 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6924 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6925 Enum != EnumEnd; ++Enum) {
6926 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6927
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006928 // Don't add the same builtin candidate twice, or if a user defined
6929 // candidate exists.
6930 if (!AddedTypes.insert(CanonType) ||
6931 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6932 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006933 continue;
6934
6935 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006936 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6937 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006938 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006939
6940 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6941 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6942 if (AddedTypes.insert(NullPtrTy) &&
6943 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6944 NullPtrTy))) {
6945 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6946 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6947 CandidateSet);
6948 }
6949 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006950 }
6951 }
6952
6953 // C++ [over.built]p13:
6954 //
6955 // For every cv-qualified or cv-unqualified object type T
6956 // there exist candidate operator functions of the form
6957 //
6958 // T* operator+(T*, ptrdiff_t);
6959 // T& operator[](T*, ptrdiff_t); [BELOW]
6960 // T* operator-(T*, ptrdiff_t);
6961 // T* operator+(ptrdiff_t, T*);
6962 // T& operator[](ptrdiff_t, T*); [BELOW]
6963 //
6964 // C++ [over.built]p14:
6965 //
6966 // For every T, where T is a pointer to object type, there
6967 // exist candidate operator functions of the form
6968 //
6969 // ptrdiff_t operator-(T, T);
6970 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6971 /// Set of (canonical) types that we've already handled.
6972 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6973
6974 for (int Arg = 0; Arg < 2; ++Arg) {
6975 QualType AsymetricParamTypes[2] = {
6976 S.Context.getPointerDiffType(),
6977 S.Context.getPointerDiffType(),
6978 };
6979 for (BuiltinCandidateTypeSet::iterator
6980 Ptr = CandidateTypes[Arg].pointer_begin(),
6981 PtrEnd = CandidateTypes[Arg].pointer_end();
6982 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006983 QualType PointeeTy = (*Ptr)->getPointeeType();
6984 if (!PointeeTy->isObjectType())
6985 continue;
6986
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006987 AsymetricParamTypes[Arg] = *Ptr;
6988 if (Arg == 0 || Op == OO_Plus) {
6989 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6990 // T* operator+(ptrdiff_t, T*);
6991 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6992 CandidateSet);
6993 }
6994 if (Op == OO_Minus) {
6995 // ptrdiff_t operator-(T, T);
6996 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6997 continue;
6998
6999 QualType ParamTypes[2] = { *Ptr, *Ptr };
7000 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7001 Args, 2, CandidateSet);
7002 }
7003 }
7004 }
7005 }
7006
7007 // C++ [over.built]p12:
7008 //
7009 // For every pair of promoted arithmetic types L and R, there
7010 // exist candidate operator functions of the form
7011 //
7012 // LR operator*(L, R);
7013 // LR operator/(L, R);
7014 // LR operator+(L, R);
7015 // LR operator-(L, R);
7016 // bool operator<(L, R);
7017 // bool operator>(L, R);
7018 // bool operator<=(L, R);
7019 // bool operator>=(L, R);
7020 // bool operator==(L, R);
7021 // bool operator!=(L, R);
7022 //
7023 // where LR is the result of the usual arithmetic conversions
7024 // between types L and R.
7025 //
7026 // C++ [over.built]p24:
7027 //
7028 // For every pair of promoted arithmetic types L and R, there exist
7029 // candidate operator functions of the form
7030 //
7031 // LR operator?(bool, L, R);
7032 //
7033 // where LR is the result of the usual arithmetic conversions
7034 // between types L and R.
7035 // Our candidates ignore the first parameter.
7036 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007037 if (!HasArithmeticOrEnumeralCandidateType)
7038 return;
7039
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007040 for (unsigned Left = FirstPromotedArithmeticType;
7041 Left < LastPromotedArithmeticType; ++Left) {
7042 for (unsigned Right = FirstPromotedArithmeticType;
7043 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007044 QualType LandR[2] = { getArithmeticType(Left),
7045 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007046 QualType Result =
7047 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007048 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007049 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7050 }
7051 }
7052
7053 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7054 // conditional operator for vector types.
7055 for (BuiltinCandidateTypeSet::iterator
7056 Vec1 = CandidateTypes[0].vector_begin(),
7057 Vec1End = CandidateTypes[0].vector_end();
7058 Vec1 != Vec1End; ++Vec1) {
7059 for (BuiltinCandidateTypeSet::iterator
7060 Vec2 = CandidateTypes[1].vector_begin(),
7061 Vec2End = CandidateTypes[1].vector_end();
7062 Vec2 != Vec2End; ++Vec2) {
7063 QualType LandR[2] = { *Vec1, *Vec2 };
7064 QualType Result = S.Context.BoolTy;
7065 if (!isComparison) {
7066 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7067 Result = *Vec1;
7068 else
7069 Result = *Vec2;
7070 }
7071
7072 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7073 }
7074 }
7075 }
7076
7077 // C++ [over.built]p17:
7078 //
7079 // For every pair of promoted integral types L and R, there
7080 // exist candidate operator functions of the form
7081 //
7082 // LR operator%(L, R);
7083 // LR operator&(L, R);
7084 // LR operator^(L, R);
7085 // LR operator|(L, R);
7086 // L operator<<(L, R);
7087 // L operator>>(L, R);
7088 //
7089 // where LR is the result of the usual arithmetic conversions
7090 // between types L and R.
7091 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007092 if (!HasArithmeticOrEnumeralCandidateType)
7093 return;
7094
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007095 for (unsigned Left = FirstPromotedIntegralType;
7096 Left < LastPromotedIntegralType; ++Left) {
7097 for (unsigned Right = FirstPromotedIntegralType;
7098 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007099 QualType LandR[2] = { getArithmeticType(Left),
7100 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007101 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7102 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007103 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007104 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7105 }
7106 }
7107 }
7108
7109 // C++ [over.built]p20:
7110 //
7111 // For every pair (T, VQ), where T is an enumeration or
7112 // pointer to member type and VQ is either volatile or
7113 // empty, there exist candidate operator functions of the form
7114 //
7115 // VQ T& operator=(VQ T&, T);
7116 void addAssignmentMemberPointerOrEnumeralOverloads() {
7117 /// Set of (canonical) types that we've already handled.
7118 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7119
7120 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7121 for (BuiltinCandidateTypeSet::iterator
7122 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7123 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7124 Enum != EnumEnd; ++Enum) {
7125 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7126 continue;
7127
7128 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7129 CandidateSet);
7130 }
7131
7132 for (BuiltinCandidateTypeSet::iterator
7133 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7134 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7135 MemPtr != MemPtrEnd; ++MemPtr) {
7136 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7137 continue;
7138
7139 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7140 CandidateSet);
7141 }
7142 }
7143 }
7144
7145 // C++ [over.built]p19:
7146 //
7147 // For every pair (T, VQ), where T is any type and VQ is either
7148 // volatile or empty, there exist candidate operator functions
7149 // of the form
7150 //
7151 // T*VQ& operator=(T*VQ&, T*);
7152 //
7153 // C++ [over.built]p21:
7154 //
7155 // For every pair (T, VQ), where T is a cv-qualified or
7156 // cv-unqualified object type and VQ is either volatile or
7157 // empty, there exist candidate operator functions of the form
7158 //
7159 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7160 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7161 void addAssignmentPointerOverloads(bool isEqualOp) {
7162 /// Set of (canonical) types that we've already handled.
7163 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7164
7165 for (BuiltinCandidateTypeSet::iterator
7166 Ptr = CandidateTypes[0].pointer_begin(),
7167 PtrEnd = CandidateTypes[0].pointer_end();
7168 Ptr != PtrEnd; ++Ptr) {
7169 // If this is operator=, keep track of the builtin candidates we added.
7170 if (isEqualOp)
7171 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007172 else if (!(*Ptr)->getPointeeType()->isObjectType())
7173 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007174
7175 // non-volatile version
7176 QualType ParamTypes[2] = {
7177 S.Context.getLValueReferenceType(*Ptr),
7178 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7179 };
7180 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7181 /*IsAssigmentOperator=*/ isEqualOp);
7182
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007183 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7184 VisibleTypeConversionsQuals.hasVolatile();
7185 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007186 // volatile version
7187 ParamTypes[0] =
7188 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7189 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7190 /*IsAssigmentOperator=*/isEqualOp);
7191 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007192
7193 if (!(*Ptr).isRestrictQualified() &&
7194 VisibleTypeConversionsQuals.hasRestrict()) {
7195 // restrict version
7196 ParamTypes[0]
7197 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7199 /*IsAssigmentOperator=*/isEqualOp);
7200
7201 if (NeedVolatile) {
7202 // volatile restrict version
7203 ParamTypes[0]
7204 = S.Context.getLValueReferenceType(
7205 S.Context.getCVRQualifiedType(*Ptr,
7206 (Qualifiers::Volatile |
7207 Qualifiers::Restrict)));
7208 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7209 CandidateSet,
7210 /*IsAssigmentOperator=*/isEqualOp);
7211 }
7212 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007213 }
7214
7215 if (isEqualOp) {
7216 for (BuiltinCandidateTypeSet::iterator
7217 Ptr = CandidateTypes[1].pointer_begin(),
7218 PtrEnd = CandidateTypes[1].pointer_end();
7219 Ptr != PtrEnd; ++Ptr) {
7220 // Make sure we don't add the same candidate twice.
7221 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7222 continue;
7223
Chandler Carruth6df868e2010-12-12 08:17:55 +00007224 QualType ParamTypes[2] = {
7225 S.Context.getLValueReferenceType(*Ptr),
7226 *Ptr,
7227 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007228
7229 // non-volatile version
7230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7231 /*IsAssigmentOperator=*/true);
7232
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007233 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7234 VisibleTypeConversionsQuals.hasVolatile();
7235 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007236 // volatile version
7237 ParamTypes[0] =
7238 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007239 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7240 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007241 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007242
7243 if (!(*Ptr).isRestrictQualified() &&
7244 VisibleTypeConversionsQuals.hasRestrict()) {
7245 // restrict version
7246 ParamTypes[0]
7247 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7248 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7249 CandidateSet, /*IsAssigmentOperator=*/true);
7250
7251 if (NeedVolatile) {
7252 // volatile restrict version
7253 ParamTypes[0]
7254 = S.Context.getLValueReferenceType(
7255 S.Context.getCVRQualifiedType(*Ptr,
7256 (Qualifiers::Volatile |
7257 Qualifiers::Restrict)));
7258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7259 CandidateSet, /*IsAssigmentOperator=*/true);
7260
7261 }
7262 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007263 }
7264 }
7265 }
7266
7267 // C++ [over.built]p18:
7268 //
7269 // For every triple (L, VQ, R), where L is an arithmetic type,
7270 // VQ is either volatile or empty, and R is a promoted
7271 // arithmetic type, there exist candidate operator functions of
7272 // the form
7273 //
7274 // VQ L& operator=(VQ L&, R);
7275 // VQ L& operator*=(VQ L&, R);
7276 // VQ L& operator/=(VQ L&, R);
7277 // VQ L& operator+=(VQ L&, R);
7278 // VQ L& operator-=(VQ L&, R);
7279 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007280 if (!HasArithmeticOrEnumeralCandidateType)
7281 return;
7282
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007283 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7284 for (unsigned Right = FirstPromotedArithmeticType;
7285 Right < LastPromotedArithmeticType; ++Right) {
7286 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007287 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007288
7289 // Add this built-in operator as a candidate (VQ is empty).
7290 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007291 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7293 /*IsAssigmentOperator=*/isEqualOp);
7294
7295 // Add this built-in operator as a candidate (VQ is 'volatile').
7296 if (VisibleTypeConversionsQuals.hasVolatile()) {
7297 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007298 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007299 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007300 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7301 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007302 /*IsAssigmentOperator=*/isEqualOp);
7303 }
7304 }
7305 }
7306
7307 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7308 for (BuiltinCandidateTypeSet::iterator
7309 Vec1 = CandidateTypes[0].vector_begin(),
7310 Vec1End = CandidateTypes[0].vector_end();
7311 Vec1 != Vec1End; ++Vec1) {
7312 for (BuiltinCandidateTypeSet::iterator
7313 Vec2 = CandidateTypes[1].vector_begin(),
7314 Vec2End = CandidateTypes[1].vector_end();
7315 Vec2 != Vec2End; ++Vec2) {
7316 QualType ParamTypes[2];
7317 ParamTypes[1] = *Vec2;
7318 // Add this built-in operator as a candidate (VQ is empty).
7319 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7321 /*IsAssigmentOperator=*/isEqualOp);
7322
7323 // Add this built-in operator as a candidate (VQ is 'volatile').
7324 if (VisibleTypeConversionsQuals.hasVolatile()) {
7325 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7326 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007327 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7328 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007329 /*IsAssigmentOperator=*/isEqualOp);
7330 }
7331 }
7332 }
7333 }
7334
7335 // C++ [over.built]p22:
7336 //
7337 // For every triple (L, VQ, R), where L is an integral type, VQ
7338 // is either volatile or empty, and R is a promoted integral
7339 // type, there exist candidate operator functions of the form
7340 //
7341 // VQ L& operator%=(VQ L&, R);
7342 // VQ L& operator<<=(VQ L&, R);
7343 // VQ L& operator>>=(VQ L&, R);
7344 // VQ L& operator&=(VQ L&, R);
7345 // VQ L& operator^=(VQ L&, R);
7346 // VQ L& operator|=(VQ L&, R);
7347 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007348 if (!HasArithmeticOrEnumeralCandidateType)
7349 return;
7350
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007351 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7352 for (unsigned Right = FirstPromotedIntegralType;
7353 Right < LastPromotedIntegralType; ++Right) {
7354 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007355 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007356
7357 // Add this built-in operator as a candidate (VQ is empty).
7358 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007359 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007360 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7361 if (VisibleTypeConversionsQuals.hasVolatile()) {
7362 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007363 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007364 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7365 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7366 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7367 CandidateSet);
7368 }
7369 }
7370 }
7371 }
7372
7373 // C++ [over.operator]p23:
7374 //
7375 // There also exist candidate operator functions of the form
7376 //
7377 // bool operator!(bool);
7378 // bool operator&&(bool, bool);
7379 // bool operator||(bool, bool);
7380 void addExclaimOverload() {
7381 QualType ParamTy = S.Context.BoolTy;
7382 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7383 /*IsAssignmentOperator=*/false,
7384 /*NumContextualBoolArguments=*/1);
7385 }
7386 void addAmpAmpOrPipePipeOverload() {
7387 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7388 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7389 /*IsAssignmentOperator=*/false,
7390 /*NumContextualBoolArguments=*/2);
7391 }
7392
7393 // C++ [over.built]p13:
7394 //
7395 // For every cv-qualified or cv-unqualified object type T there
7396 // exist candidate operator functions of the form
7397 //
7398 // T* operator+(T*, ptrdiff_t); [ABOVE]
7399 // T& operator[](T*, ptrdiff_t);
7400 // T* operator-(T*, ptrdiff_t); [ABOVE]
7401 // T* operator+(ptrdiff_t, T*); [ABOVE]
7402 // T& operator[](ptrdiff_t, T*);
7403 void addSubscriptOverloads() {
7404 for (BuiltinCandidateTypeSet::iterator
7405 Ptr = CandidateTypes[0].pointer_begin(),
7406 PtrEnd = CandidateTypes[0].pointer_end();
7407 Ptr != PtrEnd; ++Ptr) {
7408 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7409 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007410 if (!PointeeType->isObjectType())
7411 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007412
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007413 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7414
7415 // T& operator[](T*, ptrdiff_t)
7416 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7417 }
7418
7419 for (BuiltinCandidateTypeSet::iterator
7420 Ptr = CandidateTypes[1].pointer_begin(),
7421 PtrEnd = CandidateTypes[1].pointer_end();
7422 Ptr != PtrEnd; ++Ptr) {
7423 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7424 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007425 if (!PointeeType->isObjectType())
7426 continue;
7427
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007428 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7429
7430 // T& operator[](ptrdiff_t, T*)
7431 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7432 }
7433 }
7434
7435 // C++ [over.built]p11:
7436 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7437 // C1 is the same type as C2 or is a derived class of C2, T is an object
7438 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7439 // there exist candidate operator functions of the form
7440 //
7441 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7442 //
7443 // where CV12 is the union of CV1 and CV2.
7444 void addArrowStarOverloads() {
7445 for (BuiltinCandidateTypeSet::iterator
7446 Ptr = CandidateTypes[0].pointer_begin(),
7447 PtrEnd = CandidateTypes[0].pointer_end();
7448 Ptr != PtrEnd; ++Ptr) {
7449 QualType C1Ty = (*Ptr);
7450 QualType C1;
7451 QualifierCollector Q1;
7452 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7453 if (!isa<RecordType>(C1))
7454 continue;
7455 // heuristic to reduce number of builtin candidates in the set.
7456 // Add volatile/restrict version only if there are conversions to a
7457 // volatile/restrict type.
7458 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7459 continue;
7460 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7461 continue;
7462 for (BuiltinCandidateTypeSet::iterator
7463 MemPtr = CandidateTypes[1].member_pointer_begin(),
7464 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7465 MemPtr != MemPtrEnd; ++MemPtr) {
7466 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7467 QualType C2 = QualType(mptr->getClass(), 0);
7468 C2 = C2.getUnqualifiedType();
7469 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7470 break;
7471 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7472 // build CV12 T&
7473 QualType T = mptr->getPointeeType();
7474 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7475 T.isVolatileQualified())
7476 continue;
7477 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7478 T.isRestrictQualified())
7479 continue;
7480 T = Q1.apply(S.Context, T);
7481 QualType ResultTy = S.Context.getLValueReferenceType(T);
7482 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7483 }
7484 }
7485 }
7486
7487 // Note that we don't consider the first argument, since it has been
7488 // contextually converted to bool long ago. The candidates below are
7489 // therefore added as binary.
7490 //
7491 // C++ [over.built]p25:
7492 // For every type T, where T is a pointer, pointer-to-member, or scoped
7493 // enumeration type, there exist candidate operator functions of the form
7494 //
7495 // T operator?(bool, T, T);
7496 //
7497 void addConditionalOperatorOverloads() {
7498 /// Set of (canonical) types that we've already handled.
7499 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7500
7501 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7502 for (BuiltinCandidateTypeSet::iterator
7503 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7504 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7505 Ptr != PtrEnd; ++Ptr) {
7506 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7507 continue;
7508
7509 QualType ParamTypes[2] = { *Ptr, *Ptr };
7510 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7511 }
7512
7513 for (BuiltinCandidateTypeSet::iterator
7514 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7515 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7516 MemPtr != MemPtrEnd; ++MemPtr) {
7517 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7518 continue;
7519
7520 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7521 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7522 }
7523
Richard Smith80ad52f2013-01-02 11:42:31 +00007524 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007525 for (BuiltinCandidateTypeSet::iterator
7526 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7527 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7528 Enum != EnumEnd; ++Enum) {
7529 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7530 continue;
7531
7532 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7533 continue;
7534
7535 QualType ParamTypes[2] = { *Enum, *Enum };
7536 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7537 }
7538 }
7539 }
7540 }
7541};
7542
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007543} // end anonymous namespace
7544
7545/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7546/// operator overloads to the candidate set (C++ [over.built]), based
7547/// on the operator @p Op and the arguments given. For example, if the
7548/// operator is a binary '+', this routine might add "int
7549/// operator+(int, int)" to cover integer addition.
7550void
7551Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7552 SourceLocation OpLoc,
7553 Expr **Args, unsigned NumArgs,
7554 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007555 // Find all of the types that the arguments can convert to, but only
7556 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007557 // that make use of these types. Also record whether we encounter non-record
7558 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007559 Qualifiers VisibleTypeConversionsQuals;
7560 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007561 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7562 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007563
7564 bool HasNonRecordCandidateType = false;
7565 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007566 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007567 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7568 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7569 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7570 OpLoc,
7571 true,
7572 (Op == OO_Exclaim ||
7573 Op == OO_AmpAmp ||
7574 Op == OO_PipePipe),
7575 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007576 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7577 CandidateTypes[ArgIdx].hasNonRecordTypes();
7578 HasArithmeticOrEnumeralCandidateType =
7579 HasArithmeticOrEnumeralCandidateType ||
7580 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007581 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007582
Chandler Carruth6a577462010-12-13 01:44:01 +00007583 // Exit early when no non-record types have been added to the candidate set
7584 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007585 //
7586 // We can't exit early for !, ||, or &&, since there we have always have
7587 // 'bool' overloads.
7588 if (!HasNonRecordCandidateType &&
7589 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007590 return;
7591
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007592 // Setup an object to manage the common state for building overloads.
7593 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7594 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007595 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007596 CandidateTypes, CandidateSet);
7597
7598 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007599 switch (Op) {
7600 case OO_None:
7601 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007602 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007603
Chandler Carruthabb71842010-12-12 08:51:33 +00007604 case OO_New:
7605 case OO_Delete:
7606 case OO_Array_New:
7607 case OO_Array_Delete:
7608 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007609 llvm_unreachable(
7610 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007611
7612 case OO_Comma:
7613 case OO_Arrow:
7614 // C++ [over.match.oper]p3:
7615 // -- For the operator ',', the unary operator '&', or the
7616 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007617 break;
7618
7619 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007620 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007621 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007622 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007623
7624 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007625 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007626 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007627 } else {
7628 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7629 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7630 }
Douglas Gregor74253732008-11-19 15:42:04 +00007631 break;
7632
Chandler Carruthabb71842010-12-12 08:51:33 +00007633 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007634 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007635 OpBuilder.addUnaryStarPointerOverloads();
7636 else
7637 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7638 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007639
Chandler Carruthabb71842010-12-12 08:51:33 +00007640 case OO_Slash:
7641 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007642 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007643
7644 case OO_PlusPlus:
7645 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007646 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7647 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007648 break;
7649
Douglas Gregor19b7b152009-08-24 13:43:27 +00007650 case OO_EqualEqual:
7651 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007652 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007653 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007654
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007655 case OO_Less:
7656 case OO_Greater:
7657 case OO_LessEqual:
7658 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007659 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007660 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7661 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007662
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007663 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007664 case OO_Caret:
7665 case OO_Pipe:
7666 case OO_LessLess:
7667 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007668 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007669 break;
7670
Chandler Carruthabb71842010-12-12 08:51:33 +00007671 case OO_Amp: // '&' is either unary or binary
7672 if (NumArgs == 1)
7673 // C++ [over.match.oper]p3:
7674 // -- For the operator ',', the unary operator '&', or the
7675 // operator '->', the built-in candidates set is empty.
7676 break;
7677
7678 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7679 break;
7680
7681 case OO_Tilde:
7682 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7683 break;
7684
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007685 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007686 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007687 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007688
7689 case OO_PlusEqual:
7690 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007691 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007692 // Fall through.
7693
7694 case OO_StarEqual:
7695 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007696 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007697 break;
7698
7699 case OO_PercentEqual:
7700 case OO_LessLessEqual:
7701 case OO_GreaterGreaterEqual:
7702 case OO_AmpEqual:
7703 case OO_CaretEqual:
7704 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007705 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007706 break;
7707
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007708 case OO_Exclaim:
7709 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007710 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007711
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007712 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007713 case OO_PipePipe:
7714 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007715 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007716
7717 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007718 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007719 break;
7720
7721 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007722 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007723 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007724
7725 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007726 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007727 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7728 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007729 }
7730}
7731
Douglas Gregorfa047642009-02-04 00:32:51 +00007732/// \brief Add function candidates found via argument-dependent lookup
7733/// to the set of overloading candidates.
7734///
7735/// This routine performs argument-dependent name lookup based on the
7736/// given function name (which may also be an operator name) and adds
7737/// all of the overload candidates found by ADL to the overload
7738/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007739void
Douglas Gregorfa047642009-02-04 00:32:51 +00007740Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007741 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007742 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007743 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007744 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007745 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007746 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007747
John McCalla113e722010-01-26 06:04:06 +00007748 // FIXME: This approach for uniquing ADL results (and removing
7749 // redundant candidates from the set) relies on pointer-equality,
7750 // which means we need to key off the canonical decl. However,
7751 // always going back to the canonical decl might not get us the
7752 // right set of default arguments. What default arguments are
7753 // we supposed to consider on ADL candidates, anyway?
7754
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007755 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007756 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007757
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007758 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007759 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7760 CandEnd = CandidateSet.end();
7761 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007762 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007763 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007764 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007765 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007766 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007767
7768 // For each of the ADL candidates we found, add it to the overload
7769 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007770 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007771 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007772 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007773 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007774 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007775
Ahmed Charles13a140c2012-02-25 11:00:22 +00007776 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7777 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007778 } else
John McCall6e266892010-01-26 03:27:55 +00007779 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007780 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007781 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007782 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007783}
7784
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007785/// isBetterOverloadCandidate - Determines whether the first overload
7786/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007787bool
John McCall120d63c2010-08-24 20:38:10 +00007788isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007789 const OverloadCandidate &Cand1,
7790 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007791 SourceLocation Loc,
7792 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007793 // Define viable functions to be better candidates than non-viable
7794 // functions.
7795 if (!Cand2.Viable)
7796 return Cand1.Viable;
7797 else if (!Cand1.Viable)
7798 return false;
7799
Douglas Gregor88a35142008-12-22 05:46:06 +00007800 // C++ [over.match.best]p1:
7801 //
7802 // -- if F is a static member function, ICS1(F) is defined such
7803 // that ICS1(F) is neither better nor worse than ICS1(G) for
7804 // any function G, and, symmetrically, ICS1(G) is neither
7805 // better nor worse than ICS1(F).
7806 unsigned StartArg = 0;
7807 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7808 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007809
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007810 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007811 // A viable function F1 is defined to be a better function than another
7812 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007813 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007814 unsigned NumArgs = Cand1.NumConversions;
7815 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007816 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007817 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007818 switch (CompareImplicitConversionSequences(S,
7819 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007820 Cand2.Conversions[ArgIdx])) {
7821 case ImplicitConversionSequence::Better:
7822 // Cand1 has a better conversion sequence.
7823 HasBetterConversion = true;
7824 break;
7825
7826 case ImplicitConversionSequence::Worse:
7827 // Cand1 can't be better than Cand2.
7828 return false;
7829
7830 case ImplicitConversionSequence::Indistinguishable:
7831 // Do nothing.
7832 break;
7833 }
7834 }
7835
Mike Stump1eb44332009-09-09 15:08:12 +00007836 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007837 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007838 if (HasBetterConversion)
7839 return true;
7840
Mike Stump1eb44332009-09-09 15:08:12 +00007841 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007842 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007843 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007844 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7845 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007846
7847 // -- F1 and F2 are function template specializations, and the function
7848 // template for F1 is more specialized than the template for F2
7849 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007850 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007851 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007852 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007853 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007854 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7855 Cand2.Function->getPrimaryTemplate(),
7856 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007857 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007858 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007859 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007860 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007861 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007862
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007863 // -- the context is an initialization by user-defined conversion
7864 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7865 // from the return type of F1 to the destination type (i.e.,
7866 // the type of the entity being initialized) is a better
7867 // conversion sequence than the standard conversion sequence
7868 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007869 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007870 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007871 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007872 // First check whether we prefer one of the conversion functions over the
7873 // other. This only distinguishes the results in non-standard, extension
7874 // cases such as the conversion from a lambda closure type to a function
7875 // pointer or block.
7876 ImplicitConversionSequence::CompareKind FuncResult
7877 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7878 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7879 return FuncResult;
7880
John McCall120d63c2010-08-24 20:38:10 +00007881 switch (CompareStandardConversionSequences(S,
7882 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007883 Cand2.FinalConversion)) {
7884 case ImplicitConversionSequence::Better:
7885 // Cand1 has a better conversion sequence.
7886 return true;
7887
7888 case ImplicitConversionSequence::Worse:
7889 // Cand1 can't be better than Cand2.
7890 return false;
7891
7892 case ImplicitConversionSequence::Indistinguishable:
7893 // Do nothing
7894 break;
7895 }
7896 }
7897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007898 return false;
7899}
7900
Mike Stump1eb44332009-09-09 15:08:12 +00007901/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007902/// within an overload candidate set.
7903///
James Dennettefce31f2012-06-22 08:10:18 +00007904/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007905/// which overload resolution occurs.
7906///
James Dennettefce31f2012-06-22 08:10:18 +00007907/// \param Best If overload resolution was successful or found a deleted
7908/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007909///
7910/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007911OverloadingResult
7912OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007913 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007914 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007915 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007916 Best = end();
7917 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7918 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007919 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007920 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007921 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007922 }
7923
7924 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007925 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007926 return OR_No_Viable_Function;
7927
7928 // Make sure that this function is better than every other viable
7929 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007930 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007931 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007932 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007933 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007934 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007935 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007936 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007937 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007938 }
Mike Stump1eb44332009-09-09 15:08:12 +00007939
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007940 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007941 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007942 (Best->Function->isDeleted() ||
7943 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007944 return OR_Deleted;
7945
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007946 return OR_Success;
7947}
7948
John McCall3c80f572010-01-12 02:15:36 +00007949namespace {
7950
7951enum OverloadCandidateKind {
7952 oc_function,
7953 oc_method,
7954 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007955 oc_function_template,
7956 oc_method_template,
7957 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007958 oc_implicit_default_constructor,
7959 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007960 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007961 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007962 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007963 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007964};
7965
John McCall220ccbf2010-01-13 00:25:19 +00007966OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7967 FunctionDecl *Fn,
7968 std::string &Description) {
7969 bool isTemplate = false;
7970
7971 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7972 isTemplate = true;
7973 Description = S.getTemplateArgumentBindingsText(
7974 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7975 }
John McCallb1622a12010-01-06 09:43:14 +00007976
7977 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007978 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007979 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007980
Sebastian Redlf677ea32011-02-05 19:23:19 +00007981 if (Ctor->getInheritedConstructor())
7982 return oc_implicit_inherited_constructor;
7983
Sean Hunt82713172011-05-25 23:16:36 +00007984 if (Ctor->isDefaultConstructor())
7985 return oc_implicit_default_constructor;
7986
7987 if (Ctor->isMoveConstructor())
7988 return oc_implicit_move_constructor;
7989
7990 assert(Ctor->isCopyConstructor() &&
7991 "unexpected sort of implicit constructor");
7992 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007993 }
7994
7995 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7996 // This actually gets spelled 'candidate function' for now, but
7997 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007998 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007999 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008000
Sean Hunt82713172011-05-25 23:16:36 +00008001 if (Meth->isMoveAssignmentOperator())
8002 return oc_implicit_move_assignment;
8003
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008004 if (Meth->isCopyAssignmentOperator())
8005 return oc_implicit_copy_assignment;
8006
8007 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8008 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008009 }
8010
John McCall220ccbf2010-01-13 00:25:19 +00008011 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008012}
8013
Sebastian Redlf677ea32011-02-05 19:23:19 +00008014void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8015 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8016 if (!Ctor) return;
8017
8018 Ctor = Ctor->getInheritedConstructor();
8019 if (!Ctor) return;
8020
8021 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8022}
8023
John McCall3c80f572010-01-12 02:15:36 +00008024} // end anonymous namespace
8025
8026// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008027void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008028 std::string FnDesc;
8029 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008030 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8031 << (unsigned) K << FnDesc;
8032 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8033 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008034 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008035}
8036
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008037//Notes the location of all overload candidates designated through
8038// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008039void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008040 assert(OverloadedExpr->getType() == Context.OverloadTy);
8041
8042 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8043 OverloadExpr *OvlExpr = Ovl.Expression;
8044
8045 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8046 IEnd = OvlExpr->decls_end();
8047 I != IEnd; ++I) {
8048 if (FunctionTemplateDecl *FunTmpl =
8049 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008050 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008051 } else if (FunctionDecl *Fun
8052 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008053 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008054 }
8055 }
8056}
8057
John McCall1d318332010-01-12 00:44:57 +00008058/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8059/// "lead" diagnostic; it will be given two arguments, the source and
8060/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008061void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8062 Sema &S,
8063 SourceLocation CaretLoc,
8064 const PartialDiagnostic &PDiag) const {
8065 S.Diag(CaretLoc, PDiag)
8066 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008067 // FIXME: The note limiting machinery is borrowed from
8068 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8069 // refactoring here.
8070 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8071 unsigned CandsShown = 0;
8072 AmbiguousConversionSequence::const_iterator I, E;
8073 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8074 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8075 break;
8076 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008077 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008078 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008079 if (I != E)
8080 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008081}
8082
John McCall1d318332010-01-12 00:44:57 +00008083namespace {
8084
John McCalladbb8f82010-01-13 09:16:55 +00008085void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8086 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8087 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008088 assert(Cand->Function && "for now, candidate must be a function");
8089 FunctionDecl *Fn = Cand->Function;
8090
8091 // There's a conversion slot for the object argument if this is a
8092 // non-constructor method. Note that 'I' corresponds the
8093 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008094 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008095 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008096 if (I == 0)
8097 isObjectArgument = true;
8098 else
8099 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008100 }
8101
John McCall220ccbf2010-01-13 00:25:19 +00008102 std::string FnDesc;
8103 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8104
John McCalladbb8f82010-01-13 09:16:55 +00008105 Expr *FromExpr = Conv.Bad.FromExpr;
8106 QualType FromTy = Conv.Bad.getFromType();
8107 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008108
John McCall5920dbb2010-02-02 02:42:52 +00008109 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008110 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008111 Expr *E = FromExpr->IgnoreParens();
8112 if (isa<UnaryOperator>(E))
8113 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008114 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008115
8116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8117 << (unsigned) FnKind << FnDesc
8118 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8119 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008120 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008121 return;
8122 }
8123
John McCall258b2032010-01-23 08:10:49 +00008124 // Do some hand-waving analysis to see if the non-viability is due
8125 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008126 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8127 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8128 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8129 CToTy = RT->getPointeeType();
8130 else {
8131 // TODO: detect and diagnose the full richness of const mismatches.
8132 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8133 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8134 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8135 }
8136
8137 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8138 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008139 Qualifiers FromQs = CFromTy.getQualifiers();
8140 Qualifiers ToQs = CToTy.getQualifiers();
8141
8142 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8143 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8144 << (unsigned) FnKind << FnDesc
8145 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8146 << FromTy
8147 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8148 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008149 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008150 return;
8151 }
8152
John McCallf85e1932011-06-15 23:02:42 +00008153 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008155 << (unsigned) FnKind << FnDesc
8156 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8157 << FromTy
8158 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8159 << (unsigned) isObjectArgument << I+1;
8160 MaybeEmitInheritedConstructorNote(S, Fn);
8161 return;
8162 }
8163
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008164 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8166 << (unsigned) FnKind << FnDesc
8167 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8168 << FromTy
8169 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8170 << (unsigned) isObjectArgument << I+1;
8171 MaybeEmitInheritedConstructorNote(S, Fn);
8172 return;
8173 }
8174
John McCall651f3ee2010-01-14 03:28:57 +00008175 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8176 assert(CVR && "unexpected qualifiers mismatch");
8177
8178 if (isObjectArgument) {
8179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8180 << (unsigned) FnKind << FnDesc
8181 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8182 << FromTy << (CVR - 1);
8183 } else {
8184 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8185 << (unsigned) FnKind << FnDesc
8186 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8187 << FromTy << (CVR - 1) << I+1;
8188 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008189 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008190 return;
8191 }
8192
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008193 // Special diagnostic for failure to convert an initializer list, since
8194 // telling the user that it has type void is not useful.
8195 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8197 << (unsigned) FnKind << FnDesc
8198 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8199 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8200 MaybeEmitInheritedConstructorNote(S, Fn);
8201 return;
8202 }
8203
John McCall258b2032010-01-23 08:10:49 +00008204 // Diagnose references or pointers to incomplete types differently,
8205 // since it's far from impossible that the incompleteness triggered
8206 // the failure.
8207 QualType TempFromTy = FromTy.getNonReferenceType();
8208 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8209 TempFromTy = PTy->getPointeeType();
8210 if (TempFromTy->isIncompleteType()) {
8211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8212 << (unsigned) FnKind << FnDesc
8213 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8214 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008215 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008216 return;
8217 }
8218
Douglas Gregor85789812010-06-30 23:01:39 +00008219 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008220 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008221 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8222 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8223 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8224 FromPtrTy->getPointeeType()) &&
8225 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8226 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008227 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008228 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008229 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008230 }
8231 } else if (const ObjCObjectPointerType *FromPtrTy
8232 = FromTy->getAs<ObjCObjectPointerType>()) {
8233 if (const ObjCObjectPointerType *ToPtrTy
8234 = ToTy->getAs<ObjCObjectPointerType>())
8235 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8236 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8237 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8238 FromPtrTy->getPointeeType()) &&
8239 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008240 BaseToDerivedConversion = 2;
8241 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008242 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8243 !FromTy->isIncompleteType() &&
8244 !ToRefTy->getPointeeType()->isIncompleteType() &&
8245 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8246 BaseToDerivedConversion = 3;
8247 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8248 ToTy.getNonReferenceType().getCanonicalType() ==
8249 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8251 << (unsigned) FnKind << FnDesc
8252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8253 << (unsigned) isObjectArgument << I + 1;
8254 MaybeEmitInheritedConstructorNote(S, Fn);
8255 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008256 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008258
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008259 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008260 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008261 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008262 << (unsigned) FnKind << FnDesc
8263 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008264 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008265 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008266 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008267 return;
8268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008269
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008270 if (isa<ObjCObjectPointerType>(CFromTy) &&
8271 isa<PointerType>(CToTy)) {
8272 Qualifiers FromQs = CFromTy.getQualifiers();
8273 Qualifiers ToQs = CToTy.getQualifiers();
8274 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8275 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8276 << (unsigned) FnKind << FnDesc
8277 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8278 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8279 MaybeEmitInheritedConstructorNote(S, Fn);
8280 return;
8281 }
8282 }
8283
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008284 // Emit the generic diagnostic and, optionally, add the hints to it.
8285 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8286 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008287 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008288 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8289 << (unsigned) (Cand->Fix.Kind);
8290
8291 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008292 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8293 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008294 FDiag << *HI;
8295 S.Diag(Fn->getLocation(), FDiag);
8296
Sebastian Redlf677ea32011-02-05 19:23:19 +00008297 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008298}
8299
8300void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8301 unsigned NumFormalArgs) {
8302 // TODO: treat calls to a missing default constructor as a special case
8303
8304 FunctionDecl *Fn = Cand->Function;
8305 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8306
8307 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008308
Douglas Gregor439d3c32011-05-05 00:13:13 +00008309 // With invalid overloaded operators, it's possible that we think we
8310 // have an arity mismatch when it fact it looks like we have the
8311 // right number of arguments, because only overloaded operators have
8312 // the weird behavior of overloading member and non-member functions.
8313 // Just don't report anything.
8314 if (Fn->isInvalidDecl() &&
8315 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8316 return;
8317
John McCalladbb8f82010-01-13 09:16:55 +00008318 // at least / at most / exactly
8319 unsigned mode, modeCount;
8320 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008321 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8322 (Cand->FailureKind == ovl_fail_bad_deduction &&
8323 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008324 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008325 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008326 mode = 0; // "at least"
8327 else
8328 mode = 2; // "exactly"
8329 modeCount = MinParams;
8330 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008331 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8332 (Cand->FailureKind == ovl_fail_bad_deduction &&
8333 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008334 if (MinParams != FnTy->getNumArgs())
8335 mode = 1; // "at most"
8336 else
8337 mode = 2; // "exactly"
8338 modeCount = FnTy->getNumArgs();
8339 }
8340
8341 std::string Description;
8342 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8343
Richard Smithf7b80562012-05-11 05:16:41 +00008344 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8346 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8347 << Fn->getParamDecl(0) << NumFormalArgs;
8348 else
8349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8350 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8351 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008352 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008353}
8354
John McCall342fec42010-02-01 18:53:26 +00008355/// Diagnose a failed template-argument deduction.
8356void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008357 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008358 FunctionDecl *Fn = Cand->Function; // pattern
8359
Douglas Gregora9333192010-05-08 17:41:32 +00008360 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008361 NamedDecl *ParamD;
8362 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8363 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8364 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008365 switch (Cand->DeductionFailure.Result) {
8366 case Sema::TDK_Success:
8367 llvm_unreachable("TDK_success while diagnosing bad deduction");
8368
8369 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008370 assert(ParamD && "no parameter found for incomplete deduction result");
8371 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8372 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008373 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008374 return;
8375 }
8376
John McCall57e97782010-08-05 09:05:08 +00008377 case Sema::TDK_Underqualified: {
8378 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8379 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8380
8381 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8382
8383 // Param will have been canonicalized, but it should just be a
8384 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008385 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008386 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008387 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008388 assert(S.Context.hasSameType(Param, NonCanonParam));
8389
8390 // Arg has also been canonicalized, but there's nothing we can do
8391 // about that. It also doesn't matter as much, because it won't
8392 // have any template parameters in it (because deduction isn't
8393 // done on dependent types).
8394 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8395
8396 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8397 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008398 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008399 return;
8400 }
8401
8402 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008403 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008404 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008405 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008406 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008407 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008408 which = 1;
8409 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008410 which = 2;
8411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008412
Douglas Gregora9333192010-05-08 17:41:32 +00008413 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008414 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008415 << *Cand->DeductionFailure.getFirstArg()
8416 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008417 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008418 return;
8419 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008420
Douglas Gregorf1a84452010-05-08 19:15:54 +00008421 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008422 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008423 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008424 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008425 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8426 << ParamD->getDeclName();
8427 else {
8428 int index = 0;
8429 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8430 index = TTP->getIndex();
8431 else if (NonTypeTemplateParmDecl *NTTP
8432 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8433 index = NTTP->getIndex();
8434 else
8435 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008436 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008437 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8438 << (index + 1);
8439 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008440 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008441 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008442
Douglas Gregora18592e2010-05-08 18:13:28 +00008443 case Sema::TDK_TooManyArguments:
8444 case Sema::TDK_TooFewArguments:
8445 DiagnoseArityMismatch(S, Cand, NumArgs);
8446 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008447
8448 case Sema::TDK_InstantiationDepth:
8449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008450 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008451 return;
8452
8453 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008454 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008455 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008456 if (TemplateArgumentList *Args =
8457 Cand->DeductionFailure.getTemplateArgumentList()) {
8458 TemplateArgString = " ";
8459 TemplateArgString += S.getTemplateArgumentBindingsText(
8460 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8461 }
8462
Richard Smith4493c0a2012-05-09 05:17:00 +00008463 // If this candidate was disabled by enable_if, say so.
8464 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8465 if (PDiag && PDiag->second.getDiagID() ==
8466 diag::err_typename_nested_not_found_enable_if) {
8467 // FIXME: Use the source range of the condition, and the fully-qualified
8468 // name of the enable_if template. These are both present in PDiag.
8469 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8470 << "'enable_if'" << TemplateArgString;
8471 return;
8472 }
8473
Richard Smithb8590f32012-05-07 09:03:25 +00008474 // Format the SFINAE diagnostic into the argument string.
8475 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8476 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008477 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008478 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008479 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008480 SFINAEArgString = ": ";
8481 R = SourceRange(PDiag->first, PDiag->first);
8482 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8483 }
8484
Douglas Gregorec20f462010-05-08 20:07:26 +00008485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008486 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008487 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008488 return;
8489 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008490
Richard Smith0efa62f2013-01-31 04:03:12 +00008491 case Sema::TDK_FailedOverloadResolution: {
8492 OverloadExpr::FindResult R =
8493 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8494 S.Diag(Fn->getLocation(),
8495 diag::note_ovl_candidate_failed_overload_resolution)
8496 << R.Expression->getName();
8497 return;
8498 }
8499
Richard Smith29805ca2013-01-31 05:19:49 +00008500 case Sema::TDK_NonDeducedMismatch:
8501 // FIXME: Provide a source location to indicate what we couldn't match.
8502 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8503 << *Cand->DeductionFailure.getFirstArg()
8504 << *Cand->DeductionFailure.getSecondArg();
8505 return;
8506
John McCall342fec42010-02-01 18:53:26 +00008507 // TODO: diagnose these individually, then kill off
8508 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008509 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008510 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008511 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008512 return;
8513 }
8514}
8515
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008516/// CUDA: diagnose an invalid call across targets.
8517void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8518 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8519 FunctionDecl *Callee = Cand->Function;
8520
8521 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8522 CalleeTarget = S.IdentifyCUDATarget(Callee);
8523
8524 std::string FnDesc;
8525 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8526
8527 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8528 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8529}
8530
John McCall342fec42010-02-01 18:53:26 +00008531/// Generates a 'note' diagnostic for an overload candidate. We've
8532/// already generated a primary error at the call site.
8533///
8534/// It really does need to be a single diagnostic with its caret
8535/// pointed at the candidate declaration. Yes, this creates some
8536/// major challenges of technical writing. Yes, this makes pointing
8537/// out problems with specific arguments quite awkward. It's still
8538/// better than generating twenty screens of text for every failed
8539/// overload.
8540///
8541/// It would be great to be able to express per-candidate problems
8542/// more richly for those diagnostic clients that cared, but we'd
8543/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008544void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008545 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008546 FunctionDecl *Fn = Cand->Function;
8547
John McCall81201622010-01-08 04:41:39 +00008548 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008549 if (Cand->Viable && (Fn->isDeleted() ||
8550 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008551 std::string FnDesc;
8552 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008553
8554 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008555 << FnKind << FnDesc
8556 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008557 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008558 return;
John McCall81201622010-01-08 04:41:39 +00008559 }
8560
John McCall220ccbf2010-01-13 00:25:19 +00008561 // We don't really have anything else to say about viable candidates.
8562 if (Cand->Viable) {
8563 S.NoteOverloadCandidate(Fn);
8564 return;
8565 }
John McCall1d318332010-01-12 00:44:57 +00008566
John McCalladbb8f82010-01-13 09:16:55 +00008567 switch (Cand->FailureKind) {
8568 case ovl_fail_too_many_arguments:
8569 case ovl_fail_too_few_arguments:
8570 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008571
John McCalladbb8f82010-01-13 09:16:55 +00008572 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008573 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008574
John McCall717e8912010-01-23 05:17:32 +00008575 case ovl_fail_trivial_conversion:
8576 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008577 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008578 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008579
John McCallb1bdc622010-02-25 01:37:24 +00008580 case ovl_fail_bad_conversion: {
8581 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008582 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008583 if (Cand->Conversions[I].isBad())
8584 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008585
John McCalladbb8f82010-01-13 09:16:55 +00008586 // FIXME: this currently happens when we're called from SemaInit
8587 // when user-conversion overload fails. Figure out how to handle
8588 // those conditions and diagnose them well.
8589 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008590 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008591
8592 case ovl_fail_bad_target:
8593 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008594 }
John McCalla1d7d622010-01-08 00:58:21 +00008595}
8596
8597void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8598 // Desugar the type of the surrogate down to a function type,
8599 // retaining as many typedefs as possible while still showing
8600 // the function type (and, therefore, its parameter types).
8601 QualType FnType = Cand->Surrogate->getConversionType();
8602 bool isLValueReference = false;
8603 bool isRValueReference = false;
8604 bool isPointer = false;
8605 if (const LValueReferenceType *FnTypeRef =
8606 FnType->getAs<LValueReferenceType>()) {
8607 FnType = FnTypeRef->getPointeeType();
8608 isLValueReference = true;
8609 } else if (const RValueReferenceType *FnTypeRef =
8610 FnType->getAs<RValueReferenceType>()) {
8611 FnType = FnTypeRef->getPointeeType();
8612 isRValueReference = true;
8613 }
8614 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8615 FnType = FnTypePtr->getPointeeType();
8616 isPointer = true;
8617 }
8618 // Desugar down to a function type.
8619 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8620 // Reconstruct the pointer/reference as appropriate.
8621 if (isPointer) FnType = S.Context.getPointerType(FnType);
8622 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8623 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8624
8625 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8626 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008627 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008628}
8629
8630void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008631 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008632 SourceLocation OpLoc,
8633 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008634 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008635 std::string TypeStr("operator");
8636 TypeStr += Opc;
8637 TypeStr += "(";
8638 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008639 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008640 TypeStr += ")";
8641 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8642 } else {
8643 TypeStr += ", ";
8644 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8645 TypeStr += ")";
8646 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8647 }
8648}
8649
8650void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8651 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008652 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008653 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8654 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008655 if (ICS.isBad()) break; // all meaningless after first invalid
8656 if (!ICS.isAmbiguous()) continue;
8657
John McCall120d63c2010-08-24 20:38:10 +00008658 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008659 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008660 }
8661}
8662
John McCall1b77e732010-01-15 23:32:50 +00008663SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8664 if (Cand->Function)
8665 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008666 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008667 return Cand->Surrogate->getLocation();
8668 return SourceLocation();
8669}
8670
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008671static unsigned
8672RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008673 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008674 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008675 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008676
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008677 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008678 case Sema::TDK_Incomplete:
8679 return 1;
8680
8681 case Sema::TDK_Underqualified:
8682 case Sema::TDK_Inconsistent:
8683 return 2;
8684
8685 case Sema::TDK_SubstitutionFailure:
8686 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008687 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008688 return 3;
8689
8690 case Sema::TDK_InstantiationDepth:
8691 case Sema::TDK_FailedOverloadResolution:
8692 return 4;
8693
8694 case Sema::TDK_InvalidExplicitArguments:
8695 return 5;
8696
8697 case Sema::TDK_TooManyArguments:
8698 case Sema::TDK_TooFewArguments:
8699 return 6;
8700 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008701 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008702}
8703
John McCallbf65c0b2010-01-12 00:48:53 +00008704struct CompareOverloadCandidatesForDisplay {
8705 Sema &S;
8706 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008707
8708 bool operator()(const OverloadCandidate *L,
8709 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008710 // Fast-path this check.
8711 if (L == R) return false;
8712
John McCall81201622010-01-08 04:41:39 +00008713 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008714 if (L->Viable) {
8715 if (!R->Viable) return true;
8716
8717 // TODO: introduce a tri-valued comparison for overload
8718 // candidates. Would be more worthwhile if we had a sort
8719 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008720 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8721 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008722 } else if (R->Viable)
8723 return false;
John McCall81201622010-01-08 04:41:39 +00008724
John McCall1b77e732010-01-15 23:32:50 +00008725 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008726
John McCall1b77e732010-01-15 23:32:50 +00008727 // Criteria by which we can sort non-viable candidates:
8728 if (!L->Viable) {
8729 // 1. Arity mismatches come after other candidates.
8730 if (L->FailureKind == ovl_fail_too_many_arguments ||
8731 L->FailureKind == ovl_fail_too_few_arguments)
8732 return false;
8733 if (R->FailureKind == ovl_fail_too_many_arguments ||
8734 R->FailureKind == ovl_fail_too_few_arguments)
8735 return true;
John McCall81201622010-01-08 04:41:39 +00008736
John McCall717e8912010-01-23 05:17:32 +00008737 // 2. Bad conversions come first and are ordered by the number
8738 // of bad conversions and quality of good conversions.
8739 if (L->FailureKind == ovl_fail_bad_conversion) {
8740 if (R->FailureKind != ovl_fail_bad_conversion)
8741 return true;
8742
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008743 // The conversion that can be fixed with a smaller number of changes,
8744 // comes first.
8745 unsigned numLFixes = L->Fix.NumConversionsFixed;
8746 unsigned numRFixes = R->Fix.NumConversionsFixed;
8747 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8748 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008749 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008750 if (numLFixes < numRFixes)
8751 return true;
8752 else
8753 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008754 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008755
John McCall717e8912010-01-23 05:17:32 +00008756 // If there's any ordering between the defined conversions...
8757 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008758 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008759
8760 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008761 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008762 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008763 switch (CompareImplicitConversionSequences(S,
8764 L->Conversions[I],
8765 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008766 case ImplicitConversionSequence::Better:
8767 leftBetter++;
8768 break;
8769
8770 case ImplicitConversionSequence::Worse:
8771 leftBetter--;
8772 break;
8773
8774 case ImplicitConversionSequence::Indistinguishable:
8775 break;
8776 }
8777 }
8778 if (leftBetter > 0) return true;
8779 if (leftBetter < 0) return false;
8780
8781 } else if (R->FailureKind == ovl_fail_bad_conversion)
8782 return false;
8783
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008784 if (L->FailureKind == ovl_fail_bad_deduction) {
8785 if (R->FailureKind != ovl_fail_bad_deduction)
8786 return true;
8787
8788 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8789 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008790 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008791 } else if (R->FailureKind == ovl_fail_bad_deduction)
8792 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008793
John McCall1b77e732010-01-15 23:32:50 +00008794 // TODO: others?
8795 }
8796
8797 // Sort everything else by location.
8798 SourceLocation LLoc = GetLocationForCandidate(L);
8799 SourceLocation RLoc = GetLocationForCandidate(R);
8800
8801 // Put candidates without locations (e.g. builtins) at the end.
8802 if (LLoc.isInvalid()) return false;
8803 if (RLoc.isInvalid()) return true;
8804
8805 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008806 }
8807};
8808
John McCall717e8912010-01-23 05:17:32 +00008809/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008810/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008811void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008812 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008813 assert(!Cand->Viable);
8814
8815 // Don't do anything on failures other than bad conversion.
8816 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8817
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008818 // We only want the FixIts if all the arguments can be corrected.
8819 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008820 // Use a implicit copy initialization to check conversion fixes.
8821 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008822
John McCall717e8912010-01-23 05:17:32 +00008823 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008824 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008825 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008826 while (true) {
8827 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8828 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008829 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008830 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008831 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008832 }
John McCall717e8912010-01-23 05:17:32 +00008833 }
8834
8835 if (ConvIdx == ConvCount)
8836 return;
8837
John McCallb1bdc622010-02-25 01:37:24 +00008838 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8839 "remaining conversion is initialized?");
8840
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008841 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008842 // operation somehow.
8843 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008844
8845 const FunctionProtoType* Proto;
8846 unsigned ArgIdx = ConvIdx;
8847
8848 if (Cand->IsSurrogate) {
8849 QualType ConvType
8850 = Cand->Surrogate->getConversionType().getNonReferenceType();
8851 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8852 ConvType = ConvPtrType->getPointeeType();
8853 Proto = ConvType->getAs<FunctionProtoType>();
8854 ArgIdx--;
8855 } else if (Cand->Function) {
8856 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8857 if (isa<CXXMethodDecl>(Cand->Function) &&
8858 !isa<CXXConstructorDecl>(Cand->Function))
8859 ArgIdx--;
8860 } else {
8861 // Builtin binary operator with a bad first conversion.
8862 assert(ConvCount <= 3);
8863 for (; ConvIdx != ConvCount; ++ConvIdx)
8864 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008865 = TryCopyInitialization(S, Args[ConvIdx],
8866 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008867 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008868 /*InOverloadResolution*/ true,
8869 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008870 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008871 return;
8872 }
8873
8874 // Fill in the rest of the conversions.
8875 unsigned NumArgsInProto = Proto->getNumArgs();
8876 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008877 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008878 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008879 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008880 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008881 /*InOverloadResolution=*/true,
8882 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008883 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008884 // Store the FixIt in the candidate if it exists.
8885 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008886 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008887 }
John McCall717e8912010-01-23 05:17:32 +00008888 else
8889 Cand->Conversions[ConvIdx].setEllipsis();
8890 }
8891}
8892
John McCalla1d7d622010-01-08 00:58:21 +00008893} // end anonymous namespace
8894
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008895/// PrintOverloadCandidates - When overload resolution fails, prints
8896/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008897/// set.
John McCall120d63c2010-08-24 20:38:10 +00008898void OverloadCandidateSet::NoteCandidates(Sema &S,
8899 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008900 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008901 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008902 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008903 // Sort the candidates by viability and position. Sorting directly would
8904 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008905 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008906 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8907 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008908 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008909 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008910 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008911 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008912 if (Cand->Function || Cand->IsSurrogate)
8913 Cands.push_back(Cand);
8914 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8915 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008916 }
8917 }
8918
John McCallbf65c0b2010-01-12 00:48:53 +00008919 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008920 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008921
John McCall1d318332010-01-12 00:44:57 +00008922 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008923
Chris Lattner5f9e2722011-07-23 10:55:15 +00008924 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008925 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008926 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008927 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8928 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008929
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008930 // Set an arbitrary limit on the number of candidate functions we'll spam
8931 // the user with. FIXME: This limit should depend on details of the
8932 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008933 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008934 break;
8935 }
8936 ++CandsShown;
8937
John McCalla1d7d622010-01-08 00:58:21 +00008938 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008939 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008940 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008941 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008942 else {
8943 assert(Cand->Viable &&
8944 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008945 // Generally we only see ambiguities including viable builtin
8946 // operators if overload resolution got screwed up by an
8947 // ambiguous user-defined conversion.
8948 //
8949 // FIXME: It's quite possible for different conversions to see
8950 // different ambiguities, though.
8951 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008952 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008953 ReportedAmbiguousConversions = true;
8954 }
John McCalla1d7d622010-01-08 00:58:21 +00008955
John McCall1d318332010-01-12 00:44:57 +00008956 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008957 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008958 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008959 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008960
8961 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008962 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008963}
8964
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008965// [PossiblyAFunctionType] --> [Return]
8966// NonFunctionType --> NonFunctionType
8967// R (A) --> R(A)
8968// R (*)(A) --> R (A)
8969// R (&)(A) --> R (A)
8970// R (S::*)(A) --> R (A)
8971QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8972 QualType Ret = PossiblyAFunctionType;
8973 if (const PointerType *ToTypePtr =
8974 PossiblyAFunctionType->getAs<PointerType>())
8975 Ret = ToTypePtr->getPointeeType();
8976 else if (const ReferenceType *ToTypeRef =
8977 PossiblyAFunctionType->getAs<ReferenceType>())
8978 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008979 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008980 PossiblyAFunctionType->getAs<MemberPointerType>())
8981 Ret = MemTypePtr->getPointeeType();
8982 Ret =
8983 Context.getCanonicalType(Ret).getUnqualifiedType();
8984 return Ret;
8985}
Douglas Gregor904eed32008-11-10 20:40:00 +00008986
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008987// A helper class to help with address of function resolution
8988// - allows us to avoid passing around all those ugly parameters
8989class AddressOfFunctionResolver
8990{
8991 Sema& S;
8992 Expr* SourceExpr;
8993 const QualType& TargetType;
8994 QualType TargetFunctionType; // Extracted function type from target type
8995
8996 bool Complain;
8997 //DeclAccessPair& ResultFunctionAccessPair;
8998 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008999
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009000 bool TargetTypeIsNonStaticMemberFunction;
9001 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009002
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009003 OverloadExpr::FindResult OvlExprInfo;
9004 OverloadExpr *OvlExpr;
9005 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009006 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009007
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009008public:
9009 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9010 const QualType& TargetType, bool Complain)
9011 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9012 Complain(Complain), Context(S.getASTContext()),
9013 TargetTypeIsNonStaticMemberFunction(
9014 !!TargetType->getAs<MemberPointerType>()),
9015 FoundNonTemplateFunction(false),
9016 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9017 OvlExpr(OvlExprInfo.Expression)
9018 {
9019 ExtractUnqualifiedFunctionTypeFromTargetType();
9020
9021 if (!TargetFunctionType->isFunctionType()) {
9022 if (OvlExpr->hasExplicitTemplateArgs()) {
9023 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009024 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009025 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009026
9027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9028 if (!Method->isStatic()) {
9029 // If the target type is a non-function type and the function
9030 // found is a non-static member function, pretend as if that was
9031 // the target, it's the only possible type to end up with.
9032 TargetTypeIsNonStaticMemberFunction = true;
9033
9034 // And skip adding the function if its not in the proper form.
9035 // We'll diagnose this due to an empty set of functions.
9036 if (!OvlExprInfo.HasFormOfMemberPointer)
9037 return;
9038 }
9039 }
9040
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009041 Matches.push_back(std::make_pair(dap,Fn));
9042 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009043 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009044 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009045 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009046
9047 if (OvlExpr->hasExplicitTemplateArgs())
9048 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009049
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009050 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9051 // C++ [over.over]p4:
9052 // If more than one function is selected, [...]
9053 if (Matches.size() > 1) {
9054 if (FoundNonTemplateFunction)
9055 EliminateAllTemplateMatches();
9056 else
9057 EliminateAllExceptMostSpecializedTemplate();
9058 }
9059 }
9060 }
9061
9062private:
9063 bool isTargetTypeAFunction() const {
9064 return TargetFunctionType->isFunctionType();
9065 }
9066
9067 // [ToType] [Return]
9068
9069 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9070 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9071 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9072 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9073 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9074 }
9075
9076 // return true if any matching specializations were found
9077 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9078 const DeclAccessPair& CurAccessFunPair) {
9079 if (CXXMethodDecl *Method
9080 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9081 // Skip non-static function templates when converting to pointer, and
9082 // static when converting to member pointer.
9083 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9084 return false;
9085 }
9086 else if (TargetTypeIsNonStaticMemberFunction)
9087 return false;
9088
9089 // C++ [over.over]p2:
9090 // If the name is a function template, template argument deduction is
9091 // done (14.8.2.2), and if the argument deduction succeeds, the
9092 // resulting template argument list is used to generate a single
9093 // function template specialization, which is added to the set of
9094 // overloaded functions considered.
9095 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009096 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009097 if (Sema::TemplateDeductionResult Result
9098 = S.DeduceTemplateArguments(FunctionTemplate,
9099 &OvlExplicitTemplateArgs,
9100 TargetFunctionType, Specialization,
9101 Info)) {
9102 // FIXME: make a note of the failed deduction for diagnostics.
9103 (void)Result;
9104 return false;
9105 }
9106
9107 // Template argument deduction ensures that we have an exact match.
9108 // This function template specicalization works.
9109 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9110 assert(TargetFunctionType
9111 == Context.getCanonicalType(Specialization->getType()));
9112 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9113 return true;
9114 }
9115
9116 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9117 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009118 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009119 // Skip non-static functions when converting to pointer, and static
9120 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009121 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9122 return false;
9123 }
9124 else if (TargetTypeIsNonStaticMemberFunction)
9125 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009126
Chandler Carruthbd647292009-12-29 06:17:27 +00009127 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009128 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009129 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9130 if (S.CheckCUDATarget(Caller, FunDecl))
9131 return false;
9132
Douglas Gregor43c79c22009-12-09 00:47:37 +00009133 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009134 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9135 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009136 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9137 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009138 Matches.push_back(std::make_pair(CurAccessFunPair,
9139 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009140 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009141 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009142 }
Mike Stump1eb44332009-09-09 15:08:12 +00009143 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009144
9145 return false;
9146 }
9147
9148 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9149 bool Ret = false;
9150
9151 // If the overload expression doesn't have the form of a pointer to
9152 // member, don't try to convert it to a pointer-to-member type.
9153 if (IsInvalidFormOfPointerToMemberFunction())
9154 return false;
9155
9156 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9157 E = OvlExpr->decls_end();
9158 I != E; ++I) {
9159 // Look through any using declarations to find the underlying function.
9160 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9161
9162 // C++ [over.over]p3:
9163 // Non-member functions and static member functions match
9164 // targets of type "pointer-to-function" or "reference-to-function."
9165 // Nonstatic member functions match targets of
9166 // type "pointer-to-member-function."
9167 // Note that according to DR 247, the containing class does not matter.
9168 if (FunctionTemplateDecl *FunctionTemplate
9169 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9170 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9171 Ret = true;
9172 }
9173 // If we have explicit template arguments supplied, skip non-templates.
9174 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9175 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9176 Ret = true;
9177 }
9178 assert(Ret || Matches.empty());
9179 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009180 }
9181
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009182 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009183 // [...] and any given function template specialization F1 is
9184 // eliminated if the set contains a second function template
9185 // specialization whose function template is more specialized
9186 // than the function template of F1 according to the partial
9187 // ordering rules of 14.5.5.2.
9188
9189 // The algorithm specified above is quadratic. We instead use a
9190 // two-pass algorithm (similar to the one used to identify the
9191 // best viable function in an overload set) that identifies the
9192 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009193
9194 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9195 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9196 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009197
John McCallc373d482010-01-27 01:50:18 +00009198 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009199 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9200 TPOC_Other, 0, SourceExpr->getLocStart(),
9201 S.PDiag(),
9202 S.PDiag(diag::err_addr_ovl_ambiguous)
9203 << Matches[0].second->getDeclName(),
9204 S.PDiag(diag::note_ovl_candidate)
9205 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009206 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009207
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009208 if (Result != MatchesCopy.end()) {
9209 // Make it the first and only element
9210 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9211 Matches[0].second = cast<FunctionDecl>(*Result);
9212 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009213 }
9214 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009215
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009216 void EliminateAllTemplateMatches() {
9217 // [...] any function template specializations in the set are
9218 // eliminated if the set also contains a non-template function, [...]
9219 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9220 if (Matches[I].second->getPrimaryTemplate() == 0)
9221 ++I;
9222 else {
9223 Matches[I] = Matches[--N];
9224 Matches.set_size(N);
9225 }
9226 }
9227 }
9228
9229public:
9230 void ComplainNoMatchesFound() const {
9231 assert(Matches.empty());
9232 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9233 << OvlExpr->getName() << TargetFunctionType
9234 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009235 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009236 }
9237
9238 bool IsInvalidFormOfPointerToMemberFunction() const {
9239 return TargetTypeIsNonStaticMemberFunction &&
9240 !OvlExprInfo.HasFormOfMemberPointer;
9241 }
9242
9243 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9244 // TODO: Should we condition this on whether any functions might
9245 // have matched, or is it more appropriate to do that in callers?
9246 // TODO: a fixit wouldn't hurt.
9247 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9248 << TargetType << OvlExpr->getSourceRange();
9249 }
9250
9251 void ComplainOfInvalidConversion() const {
9252 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9253 << OvlExpr->getName() << TargetType;
9254 }
9255
9256 void ComplainMultipleMatchesFound() const {
9257 assert(Matches.size() > 1);
9258 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9259 << OvlExpr->getName()
9260 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009261 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009262 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009263
9264 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9265
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009266 int getNumMatches() const { return Matches.size(); }
9267
9268 FunctionDecl* getMatchingFunctionDecl() const {
9269 if (Matches.size() != 1) return 0;
9270 return Matches[0].second;
9271 }
9272
9273 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9274 if (Matches.size() != 1) return 0;
9275 return &Matches[0].first;
9276 }
9277};
9278
9279/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9280/// an overloaded function (C++ [over.over]), where @p From is an
9281/// expression with overloaded function type and @p ToType is the type
9282/// we're trying to resolve to. For example:
9283///
9284/// @code
9285/// int f(double);
9286/// int f(int);
9287///
9288/// int (*pfd)(double) = f; // selects f(double)
9289/// @endcode
9290///
9291/// This routine returns the resulting FunctionDecl if it could be
9292/// resolved, and NULL otherwise. When @p Complain is true, this
9293/// routine will emit diagnostics if there is an error.
9294FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009295Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9296 QualType TargetType,
9297 bool Complain,
9298 DeclAccessPair &FoundResult,
9299 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009300 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009301
9302 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9303 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009304 int NumMatches = Resolver.getNumMatches();
9305 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009306 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009307 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9308 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9309 else
9310 Resolver.ComplainNoMatchesFound();
9311 }
9312 else if (NumMatches > 1 && Complain)
9313 Resolver.ComplainMultipleMatchesFound();
9314 else if (NumMatches == 1) {
9315 Fn = Resolver.getMatchingFunctionDecl();
9316 assert(Fn);
9317 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009318 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009319 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009320 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009321
9322 if (pHadMultipleCandidates)
9323 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009324 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009325}
9326
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009327/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009328/// resolve that overloaded function expression down to a single function.
9329///
9330/// This routine can only resolve template-ids that refer to a single function
9331/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009332/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009333/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009334FunctionDecl *
9335Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9336 bool Complain,
9337 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009338 // C++ [over.over]p1:
9339 // [...] [Note: any redundant set of parentheses surrounding the
9340 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009341 // C++ [over.over]p1:
9342 // [...] The overloaded function name can be preceded by the &
9343 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009344
Douglas Gregor4b52e252009-12-21 23:17:24 +00009345 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009346 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009347 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009348
9349 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009350 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009351
Douglas Gregor4b52e252009-12-21 23:17:24 +00009352 // Look through all of the overloaded functions, searching for one
9353 // whose type matches exactly.
9354 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009355 for (UnresolvedSetIterator I = ovl->decls_begin(),
9356 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009357 // C++0x [temp.arg.explicit]p3:
9358 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009359 // where deduction is not done, if a template argument list is
9360 // specified and it, along with any default template arguments,
9361 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009362 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009363 FunctionTemplateDecl *FunctionTemplate
9364 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009365
Douglas Gregor4b52e252009-12-21 23:17:24 +00009366 // C++ [over.over]p2:
9367 // If the name is a function template, template argument deduction is
9368 // done (14.8.2.2), and if the argument deduction succeeds, the
9369 // resulting template argument list is used to generate a single
9370 // function template specialization, which is added to the set of
9371 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009372 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009373 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009374 if (TemplateDeductionResult Result
9375 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9376 Specialization, Info)) {
9377 // FIXME: make a note of the failed deduction for diagnostics.
9378 (void)Result;
9379 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009380 }
9381
John McCall864c0412011-04-26 20:42:42 +00009382 assert(Specialization && "no specialization and no error?");
9383
Douglas Gregor4b52e252009-12-21 23:17:24 +00009384 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009385 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009386 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009387 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9388 << ovl->getName();
9389 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009390 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009391 return 0;
John McCall864c0412011-04-26 20:42:42 +00009392 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009393
John McCall864c0412011-04-26 20:42:42 +00009394 Matched = Specialization;
9395 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009396 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009397
Douglas Gregor4b52e252009-12-21 23:17:24 +00009398 return Matched;
9399}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009400
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009401
9402
9403
John McCall6dbba4f2011-10-11 23:14:30 +00009404// Resolve and fix an overloaded expression that can be resolved
9405// because it identifies a single function template specialization.
9406//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009407// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009408//
9409// Return true if it was logically possible to so resolve the
9410// expression, regardless of whether or not it succeeded. Always
9411// returns true if 'complain' is set.
9412bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9413 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9414 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009415 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009416 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009417 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009418
John McCall6dbba4f2011-10-11 23:14:30 +00009419 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009420
John McCall864c0412011-04-26 20:42:42 +00009421 DeclAccessPair found;
9422 ExprResult SingleFunctionExpression;
9423 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9424 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009425 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009426 SrcExpr = ExprError();
9427 return true;
9428 }
John McCall864c0412011-04-26 20:42:42 +00009429
9430 // It is only correct to resolve to an instance method if we're
9431 // resolving a form that's permitted to be a pointer to member.
9432 // Otherwise we'll end up making a bound member expression, which
9433 // is illegal in all the contexts we resolve like this.
9434 if (!ovl.HasFormOfMemberPointer &&
9435 isa<CXXMethodDecl>(fn) &&
9436 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009437 if (!complain) return false;
9438
9439 Diag(ovl.Expression->getExprLoc(),
9440 diag::err_bound_member_function)
9441 << 0 << ovl.Expression->getSourceRange();
9442
9443 // TODO: I believe we only end up here if there's a mix of
9444 // static and non-static candidates (otherwise the expression
9445 // would have 'bound member' type, not 'overload' type).
9446 // Ideally we would note which candidate was chosen and why
9447 // the static candidates were rejected.
9448 SrcExpr = ExprError();
9449 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009450 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009451
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009452 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009453 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009454 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009455
9456 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009457 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009458 SingleFunctionExpression =
9459 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009460 if (SingleFunctionExpression.isInvalid()) {
9461 SrcExpr = ExprError();
9462 return true;
9463 }
9464 }
John McCall864c0412011-04-26 20:42:42 +00009465 }
9466
9467 if (!SingleFunctionExpression.isUsable()) {
9468 if (complain) {
9469 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9470 << ovl.Expression->getName()
9471 << DestTypeForComplaining
9472 << OpRangeForComplaining
9473 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009474 NoteAllOverloadCandidates(SrcExpr.get());
9475
9476 SrcExpr = ExprError();
9477 return true;
9478 }
9479
9480 return false;
John McCall864c0412011-04-26 20:42:42 +00009481 }
9482
John McCall6dbba4f2011-10-11 23:14:30 +00009483 SrcExpr = SingleFunctionExpression;
9484 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009485}
9486
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009487/// \brief Add a single candidate to the overload set.
9488static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009489 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009490 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009491 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009492 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009493 bool PartialOverloading,
9494 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009495 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009496 if (isa<UsingShadowDecl>(Callee))
9497 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9498
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009499 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009500 if (ExplicitTemplateArgs) {
9501 assert(!KnownValid && "Explicit template arguments?");
9502 return;
9503 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009504 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9505 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009506 return;
John McCallba135432009-11-21 08:51:07 +00009507 }
9508
9509 if (FunctionTemplateDecl *FuncTemplate
9510 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009511 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009512 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009513 return;
9514 }
9515
Richard Smith2ced0442011-06-26 22:19:54 +00009516 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009517}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009518
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009519/// \brief Add the overload candidates named by callee and/or found by argument
9520/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009521void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009522 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009523 OverloadCandidateSet &CandidateSet,
9524 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009525
9526#ifndef NDEBUG
9527 // Verify that ArgumentDependentLookup is consistent with the rules
9528 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009529 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009530 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9531 // and let Y be the lookup set produced by argument dependent
9532 // lookup (defined as follows). If X contains
9533 //
9534 // -- a declaration of a class member, or
9535 //
9536 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009537 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009538 //
9539 // -- a declaration that is neither a function or a function
9540 // template
9541 //
9542 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009543
John McCall3b4294e2009-12-16 12:17:52 +00009544 if (ULE->requiresADL()) {
9545 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9546 E = ULE->decls_end(); I != E; ++I) {
9547 assert(!(*I)->getDeclContext()->isRecord());
9548 assert(isa<UsingShadowDecl>(*I) ||
9549 !(*I)->getDeclContext()->isFunctionOrMethod());
9550 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009551 }
9552 }
9553#endif
9554
John McCall3b4294e2009-12-16 12:17:52 +00009555 // It would be nice to avoid this copy.
9556 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009557 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009558 if (ULE->hasExplicitTemplateArgs()) {
9559 ULE->copyTemplateArgumentsInto(TABuffer);
9560 ExplicitTemplateArgs = &TABuffer;
9561 }
9562
9563 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9564 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009565 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9566 CandidateSet, PartialOverloading,
9567 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009568
John McCall3b4294e2009-12-16 12:17:52 +00009569 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009570 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009571 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009572 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009573 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009574}
John McCall578b69b2009-12-16 08:11:27 +00009575
Richard Smithf50e88a2011-06-05 22:42:48 +00009576/// Attempt to recover from an ill-formed use of a non-dependent name in a
9577/// template, where the non-dependent name was declared after the template
9578/// was defined. This is common in code written for a compilers which do not
9579/// correctly implement two-stage name lookup.
9580///
9581/// Returns true if a viable candidate was found and a diagnostic was issued.
9582static bool
9583DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9584 const CXXScopeSpec &SS, LookupResult &R,
9585 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009586 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009587 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9588 return false;
9589
9590 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009591 if (DC->isTransparentContext())
9592 continue;
9593
Richard Smithf50e88a2011-06-05 22:42:48 +00009594 SemaRef.LookupQualifiedName(R, DC);
9595
9596 if (!R.empty()) {
9597 R.suppressDiagnostics();
9598
9599 if (isa<CXXRecordDecl>(DC)) {
9600 // Don't diagnose names we find in classes; we get much better
9601 // diagnostics for these from DiagnoseEmptyLookup.
9602 R.clear();
9603 return false;
9604 }
9605
9606 OverloadCandidateSet Candidates(FnLoc);
9607 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9608 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009609 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009610 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009611
9612 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009613 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009614 // No viable functions. Don't bother the user with notes for functions
9615 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009616 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009617 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009618 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009619
9620 // Find the namespaces where ADL would have looked, and suggest
9621 // declaring the function there instead.
9622 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9623 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009624 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009625 AssociatedNamespaces,
9626 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009627 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009628 DeclContext *Std = SemaRef.getStdNamespace();
9629 for (Sema::AssociatedNamespaceSet::iterator
9630 it = AssociatedNamespaces.begin(),
9631 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009632 // Never suggest declaring a function within namespace 'std'.
9633 if (Std && Std->Encloses(*it))
9634 continue;
9635
9636 // Never suggest declaring a function within a namespace with a reserved
9637 // name, like __gnu_cxx.
9638 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9639 if (NS &&
9640 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9641 continue;
9642
9643 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009644 }
9645
9646 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9647 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009648 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009649 SemaRef.Diag(Best->Function->getLocation(),
9650 diag::note_not_found_by_two_phase_lookup)
9651 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009652 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009653 SemaRef.Diag(Best->Function->getLocation(),
9654 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009655 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009656 } else {
9657 // FIXME: It would be useful to list the associated namespaces here,
9658 // but the diagnostics infrastructure doesn't provide a way to produce
9659 // a localized representation of a list of items.
9660 SemaRef.Diag(Best->Function->getLocation(),
9661 diag::note_not_found_by_two_phase_lookup)
9662 << R.getLookupName() << 2;
9663 }
9664
9665 // Try to recover by calling this function.
9666 return true;
9667 }
9668
9669 R.clear();
9670 }
9671
9672 return false;
9673}
9674
9675/// Attempt to recover from ill-formed use of a non-dependent operator in a
9676/// template, where the non-dependent operator was declared after the template
9677/// was defined.
9678///
9679/// Returns true if a viable candidate was found and a diagnostic was issued.
9680static bool
9681DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9682 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009683 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009684 DeclarationName OpName =
9685 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9686 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9687 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009688 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009689}
9690
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009691namespace {
9692// Callback to limit the allowed keywords and to only accept typo corrections
9693// that are keywords or whose decls refer to functions (or template functions)
9694// that accept the given number of arguments.
9695class RecoveryCallCCC : public CorrectionCandidateCallback {
9696 public:
9697 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9698 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009699 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009700 WantRemainingKeywords = false;
9701 }
9702
9703 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9704 if (!candidate.getCorrectionDecl())
9705 return candidate.isKeyword();
9706
9707 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9708 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9709 FunctionDecl *FD = 0;
9710 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9711 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9712 FD = FTD->getTemplatedDecl();
9713 if (!HasExplicitTemplateArgs && !FD) {
9714 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9715 // If the Decl is neither a function nor a template function,
9716 // determine if it is a pointer or reference to a function. If so,
9717 // check against the number of arguments expected for the pointee.
9718 QualType ValType = cast<ValueDecl>(ND)->getType();
9719 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9720 ValType = ValType->getPointeeType();
9721 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9722 if (FPT->getNumArgs() == NumArgs)
9723 return true;
9724 }
9725 }
9726 if (FD && FD->getNumParams() >= NumArgs &&
9727 FD->getMinRequiredArguments() <= NumArgs)
9728 return true;
9729 }
9730 return false;
9731 }
9732
9733 private:
9734 unsigned NumArgs;
9735 bool HasExplicitTemplateArgs;
9736};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009737
9738// Callback that effectively disabled typo correction
9739class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9740 public:
9741 NoTypoCorrectionCCC() {
9742 WantTypeSpecifiers = false;
9743 WantExpressionKeywords = false;
9744 WantCXXNamedCasts = false;
9745 WantRemainingKeywords = false;
9746 }
9747
9748 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9749 return false;
9750 }
9751};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009752
9753class BuildRecoveryCallExprRAII {
9754 Sema &SemaRef;
9755public:
9756 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9757 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9758 SemaRef.IsBuildingRecoveryCallExpr = true;
9759 }
9760
9761 ~BuildRecoveryCallExprRAII() {
9762 SemaRef.IsBuildingRecoveryCallExpr = false;
9763 }
9764};
9765
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009766}
9767
John McCall578b69b2009-12-16 08:11:27 +00009768/// Attempts to recover from a call where no functions were found.
9769///
9770/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009771static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009772BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009773 UnresolvedLookupExpr *ULE,
9774 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009775 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009776 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009777 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009778 // Do not try to recover if it is already building a recovery call.
9779 // This stops infinite loops for template instantiations like
9780 //
9781 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9782 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9783 //
9784 if (SemaRef.IsBuildingRecoveryCallExpr)
9785 return ExprError();
9786 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009787
9788 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009789 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009790 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009791
John McCall3b4294e2009-12-16 12:17:52 +00009792 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009793 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009794 if (ULE->hasExplicitTemplateArgs()) {
9795 ULE->copyTemplateArgumentsInto(TABuffer);
9796 ExplicitTemplateArgs = &TABuffer;
9797 }
9798
John McCall578b69b2009-12-16 08:11:27 +00009799 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9800 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009801 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009802 NoTypoCorrectionCCC RejectAll;
9803 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9804 (CorrectionCandidateCallback*)&Validator :
9805 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009806 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009807 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009808 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009809 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009810 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009811 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009812
John McCall3b4294e2009-12-16 12:17:52 +00009813 assert(!R.empty() && "lookup results empty despite recovery");
9814
9815 // Build an implicit member call if appropriate. Just drop the
9816 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009817 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009818 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009819 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9820 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009821 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009822 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009823 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009824 else
9825 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9826
9827 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009828 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009829
9830 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009831 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009832 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009833 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009834 MultiExprArg(Args.data(), Args.size()),
9835 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009836}
Douglas Gregord7a95972010-06-08 17:35:15 +00009837
Sam Panzere1715b62012-08-21 00:52:01 +00009838/// \brief Constructs and populates an OverloadedCandidateSet from
9839/// the given function.
9840/// \returns true when an the ExprResult output parameter has been set.
9841bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9842 UnresolvedLookupExpr *ULE,
9843 Expr **Args, unsigned NumArgs,
9844 SourceLocation RParenLoc,
9845 OverloadCandidateSet *CandidateSet,
9846 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009847#ifndef NDEBUG
9848 if (ULE->requiresADL()) {
9849 // To do ADL, we must have found an unqualified name.
9850 assert(!ULE->getQualifier() && "qualified name with ADL");
9851
9852 // We don't perform ADL for implicit declarations of builtins.
9853 // Verify that this was correctly set up.
9854 FunctionDecl *F;
9855 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9856 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9857 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009858 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009859
John McCall3b4294e2009-12-16 12:17:52 +00009860 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009861 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009862 }
John McCall3b4294e2009-12-16 12:17:52 +00009863#endif
9864
John McCall5acb0c92011-10-17 18:40:02 +00009865 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009866 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9867 *Result = ExprError();
9868 return true;
9869 }
Douglas Gregor17330012009-02-04 15:01:18 +00009870
John McCall3b4294e2009-12-16 12:17:52 +00009871 // Add the functions denoted by the callee to the set of candidate
9872 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009873 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009874 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009875
9876 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009877 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9878 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009879 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009880 // In Microsoft mode, if we are inside a template class member function then
9881 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009882 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009883 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009884 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009885 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009886 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9887 llvm::makeArrayRef(Args, NumArgs),
9888 Context.DependentTy, VK_RValue,
9889 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009890 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009891 *Result = Owned(CE);
9892 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009893 }
Sam Panzere1715b62012-08-21 00:52:01 +00009894 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009895 }
John McCall578b69b2009-12-16 08:11:27 +00009896
John McCall5acb0c92011-10-17 18:40:02 +00009897 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009898 return false;
9899}
John McCall5acb0c92011-10-17 18:40:02 +00009900
Sam Panzere1715b62012-08-21 00:52:01 +00009901/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9902/// the completed call expression. If overload resolution fails, emits
9903/// diagnostics and returns ExprError()
9904static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9905 UnresolvedLookupExpr *ULE,
9906 SourceLocation LParenLoc,
9907 Expr **Args, unsigned NumArgs,
9908 SourceLocation RParenLoc,
9909 Expr *ExecConfig,
9910 OverloadCandidateSet *CandidateSet,
9911 OverloadCandidateSet::iterator *Best,
9912 OverloadingResult OverloadResult,
9913 bool AllowTypoCorrection) {
9914 if (CandidateSet->empty())
9915 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9916 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9917 RParenLoc, /*EmptyLookup=*/true,
9918 AllowTypoCorrection);
9919
9920 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009921 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009922 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +00009923 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9924 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9925 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9926 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9927 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009928 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009929
Richard Smithf50e88a2011-06-05 22:42:48 +00009930 case OR_No_Viable_Function: {
9931 // Try to recover by looking for viable functions which the user might
9932 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009933 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009934 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9935 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009936 /*EmptyLookup=*/false,
9937 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009938 if (!Recovery.isInvalid())
9939 return Recovery;
9940
Sam Panzere1715b62012-08-21 00:52:01 +00009941 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009942 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009943 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009944 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9945 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009946 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009947 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009948
9949 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009950 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009951 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009952 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9953 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009954 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009955
Sam Panzere1715b62012-08-21 00:52:01 +00009956 case OR_Deleted: {
9957 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9958 << (*Best)->Function->isDeleted()
9959 << ULE->getName()
9960 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9961 << Fn->getSourceRange();
9962 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9963 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009964
Sam Panzere1715b62012-08-21 00:52:01 +00009965 // We emitted an error for the unvailable/deleted function call but keep
9966 // the call in the AST.
9967 FunctionDecl *FDecl = (*Best)->Function;
9968 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9969 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9970 RParenLoc, ExecConfig);
9971 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009972 }
9973
Douglas Gregorff331c12010-07-25 18:17:45 +00009974 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009975 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009976}
9977
Sam Panzere1715b62012-08-21 00:52:01 +00009978/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9979/// (which eventually refers to the declaration Func) and the call
9980/// arguments Args/NumArgs, attempt to resolve the function call down
9981/// to a specific function. If overload resolution succeeds, returns
9982/// the call expression produced by overload resolution.
9983/// Otherwise, emits diagnostics and returns ExprError.
9984ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9985 UnresolvedLookupExpr *ULE,
9986 SourceLocation LParenLoc,
9987 Expr **Args, unsigned NumArgs,
9988 SourceLocation RParenLoc,
9989 Expr *ExecConfig,
9990 bool AllowTypoCorrection) {
9991 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9992 ExprResult result;
9993
9994 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9995 &CandidateSet, &result))
9996 return result;
9997
9998 OverloadCandidateSet::iterator Best;
9999 OverloadingResult OverloadResult =
10000 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10001
10002 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
10003 RParenLoc, ExecConfig, &CandidateSet,
10004 &Best, OverloadResult,
10005 AllowTypoCorrection);
10006}
10007
John McCall6e266892010-01-26 03:27:55 +000010008static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010009 return Functions.size() > 1 ||
10010 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10011}
10012
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010013/// \brief Create a unary operation that may resolve to an overloaded
10014/// operator.
10015///
10016/// \param OpLoc The location of the operator itself (e.g., '*').
10017///
10018/// \param OpcIn The UnaryOperator::Opcode that describes this
10019/// operator.
10020///
James Dennett40ae6662012-06-22 08:52:37 +000010021/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010022/// considered by overload resolution. The caller needs to build this
10023/// set based on the context using, e.g.,
10024/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10025/// set should not contain any member functions; those will be added
10026/// by CreateOverloadedUnaryOp().
10027///
James Dennett8da16872012-06-22 10:32:46 +000010028/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010029ExprResult
John McCall6e266892010-01-26 03:27:55 +000010030Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10031 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010032 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010033 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010034
10035 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10036 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10037 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010038 // TODO: provide better source location info.
10039 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010040
John McCall5acb0c92011-10-17 18:40:02 +000010041 if (checkPlaceholderForOverload(*this, Input))
10042 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010043
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010044 Expr *Args[2] = { Input, 0 };
10045 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010046
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010047 // For post-increment and post-decrement, add the implicit '0' as
10048 // the second argument, so that we know this is a post-increment or
10049 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010050 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010051 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010052 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10053 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010054 NumArgs = 2;
10055 }
10056
10057 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010058 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010059 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010060 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010061 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010062 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010063 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010064
John McCallc373d482010-01-27 01:50:18 +000010065 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010066 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010067 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010068 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010069 /*ADL*/ true, IsOverloaded(Fns),
10070 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010071 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010072 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010073 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010074 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010075 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010076 }
10077
10078 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010079 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010080
10081 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010082 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10083 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010084
10085 // Add operator candidates that are member functions.
10086 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10087
John McCall6e266892010-01-26 03:27:55 +000010088 // Add candidates from ADL.
10089 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010090 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010091 /*ExplicitTemplateArgs*/ 0,
10092 CandidateSet);
10093
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010094 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010095 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010096
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010097 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10098
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010099 // Perform overload resolution.
10100 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010101 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010102 case OR_Success: {
10103 // We found a built-in operator or an overloaded operator.
10104 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010105
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010106 if (FnDecl) {
10107 // We matched an overloaded operator. Build a call to that
10108 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010109
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010110 // Convert the arguments.
10111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010112 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010113
John Wiegley429bb272011-04-08 18:41:53 +000010114 ExprResult InputRes =
10115 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10116 Best->FoundDecl, Method);
10117 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010118 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010119 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010120 } else {
10121 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010122 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010123 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010124 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010125 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010126 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010127 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010128 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010129 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010130 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010131 }
10132
John McCallf89e55a2010-11-18 06:31:45 +000010133 // Determine the result type.
10134 QualType ResultTy = FnDecl->getResultType();
10135 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10136 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010137
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010138 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010139 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010140 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010141 if (FnExpr.isInvalid())
10142 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010143
Eli Friedman4c3b8962009-11-18 03:58:17 +000010144 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010145 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010146 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010147 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010148 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010149
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010150 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010151 FnDecl))
10152 return ExprError();
10153
John McCall9ae2f072010-08-23 23:25:46 +000010154 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010155 } else {
10156 // We matched a built-in operator. Convert the arguments, then
10157 // break out so that we will build the appropriate built-in
10158 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010159 ExprResult InputRes =
10160 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10161 Best->Conversions[0], AA_Passing);
10162 if (InputRes.isInvalid())
10163 return ExprError();
10164 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010165 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010166 }
John Wiegley429bb272011-04-08 18:41:53 +000010167 }
10168
10169 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010170 // This is an erroneous use of an operator which can be overloaded by
10171 // a non-member function. Check for non-member operators which were
10172 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010173 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10174 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010175 // FIXME: Recover by calling the found function.
10176 return ExprError();
10177
John Wiegley429bb272011-04-08 18:41:53 +000010178 // No viable function; fall through to handling this as a
10179 // built-in operator, which will produce an error message for us.
10180 break;
10181
10182 case OR_Ambiguous:
10183 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10184 << UnaryOperator::getOpcodeStr(Opc)
10185 << Input->getType()
10186 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010187 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10188 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010189 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10190 return ExprError();
10191
10192 case OR_Deleted:
10193 Diag(OpLoc, diag::err_ovl_deleted_oper)
10194 << Best->Function->isDeleted()
10195 << UnaryOperator::getOpcodeStr(Opc)
10196 << getDeletedOrUnavailableSuffix(Best->Function)
10197 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010198 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10199 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010200 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010201 return ExprError();
10202 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010203
10204 // Either we found no viable overloaded operator or we matched a
10205 // built-in operator. In either case, fall through to trying to
10206 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010207 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010208}
10209
Douglas Gregor063daf62009-03-13 18:40:31 +000010210/// \brief Create a binary operation that may resolve to an overloaded
10211/// operator.
10212///
10213/// \param OpLoc The location of the operator itself (e.g., '+').
10214///
10215/// \param OpcIn The BinaryOperator::Opcode that describes this
10216/// operator.
10217///
James Dennett40ae6662012-06-22 08:52:37 +000010218/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010219/// considered by overload resolution. The caller needs to build this
10220/// set based on the context using, e.g.,
10221/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10222/// set should not contain any member functions; those will be added
10223/// by CreateOverloadedBinOp().
10224///
10225/// \param LHS Left-hand argument.
10226/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010227ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010228Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010229 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010230 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010231 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010232 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010233 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010234
10235 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10236 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10237 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10238
10239 // If either side is type-dependent, create an appropriate dependent
10240 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010241 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010242 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010243 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010244 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010245 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010246 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010247 Context.DependentTy,
10248 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010249 OpLoc,
10250 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010251
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010252 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10253 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010254 VK_LValue,
10255 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010256 Context.DependentTy,
10257 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010258 OpLoc,
10259 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010260 }
John McCall6e266892010-01-26 03:27:55 +000010261
10262 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010263 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010264 // TODO: provide better source location info in DNLoc component.
10265 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010266 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010267 = UnresolvedLookupExpr::Create(Context, NamingClass,
10268 NestedNameSpecifierLoc(), OpNameInfo,
10269 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010270 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010271 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10272 Context.DependentTy, VK_RValue,
10273 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010274 }
10275
John McCall5acb0c92011-10-17 18:40:02 +000010276 // Always do placeholder-like conversions on the RHS.
10277 if (checkPlaceholderForOverload(*this, Args[1]))
10278 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010279
John McCall3c3b7f92011-10-25 17:37:35 +000010280 // Do placeholder-like conversion on the LHS; note that we should
10281 // not get here with a PseudoObject LHS.
10282 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010283 if (checkPlaceholderForOverload(*this, Args[0]))
10284 return ExprError();
10285
Sebastian Redl275c2b42009-11-18 23:10:33 +000010286 // If this is the assignment operator, we only perform overload resolution
10287 // if the left-hand side is a class or enumeration type. This is actually
10288 // a hack. The standard requires that we do overload resolution between the
10289 // various built-in candidates, but as DR507 points out, this can lead to
10290 // problems. So we do it this way, which pretty much follows what GCC does.
10291 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010292 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010293 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010294
John McCall0e800c92010-12-04 08:14:53 +000010295 // If this is the .* operator, which is not overloadable, just
10296 // create a built-in binary operator.
10297 if (Opc == BO_PtrMemD)
10298 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10299
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010300 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010301 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010302
10303 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010304 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010305
10306 // Add operator candidates that are member functions.
10307 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10308
John McCall6e266892010-01-26 03:27:55 +000010309 // Add candidates from ADL.
10310 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010311 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010312 /*ExplicitTemplateArgs*/ 0,
10313 CandidateSet);
10314
Douglas Gregor063daf62009-03-13 18:40:31 +000010315 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010316 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010317
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010318 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10319
Douglas Gregor063daf62009-03-13 18:40:31 +000010320 // Perform overload resolution.
10321 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010322 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010323 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010324 // We found a built-in operator or an overloaded operator.
10325 FunctionDecl *FnDecl = Best->Function;
10326
10327 if (FnDecl) {
10328 // We matched an overloaded operator. Build a call to that
10329 // operator.
10330
10331 // Convert the arguments.
10332 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010333 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010334 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010335
Chandler Carruth6df868e2010-12-12 08:17:55 +000010336 ExprResult Arg1 =
10337 PerformCopyInitialization(
10338 InitializedEntity::InitializeParameter(Context,
10339 FnDecl->getParamDecl(0)),
10340 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010341 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010342 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010343
John Wiegley429bb272011-04-08 18:41:53 +000010344 ExprResult Arg0 =
10345 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10346 Best->FoundDecl, Method);
10347 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010348 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010349 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010350 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010351 } else {
10352 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010353 ExprResult Arg0 = PerformCopyInitialization(
10354 InitializedEntity::InitializeParameter(Context,
10355 FnDecl->getParamDecl(0)),
10356 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010357 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010358 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010359
Chandler Carruth6df868e2010-12-12 08:17:55 +000010360 ExprResult Arg1 =
10361 PerformCopyInitialization(
10362 InitializedEntity::InitializeParameter(Context,
10363 FnDecl->getParamDecl(1)),
10364 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010365 if (Arg1.isInvalid())
10366 return ExprError();
10367 Args[0] = LHS = Arg0.takeAs<Expr>();
10368 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010369 }
10370
John McCallf89e55a2010-11-18 06:31:45 +000010371 // Determine the result type.
10372 QualType ResultTy = FnDecl->getResultType();
10373 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10374 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010375
10376 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010377 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010378 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010379 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010380 if (FnExpr.isInvalid())
10381 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010382
John McCall9ae2f072010-08-23 23:25:46 +000010383 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010384 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010385 Args, ResultTy, VK, OpLoc,
10386 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010387
10388 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010389 FnDecl))
10390 return ExprError();
10391
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010392 ArrayRef<const Expr *> ArgsArray(Args, 2);
10393 // Cut off the implicit 'this'.
10394 if (isa<CXXMethodDecl>(FnDecl))
10395 ArgsArray = ArgsArray.slice(1);
10396 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10397 TheCall->getSourceRange(), VariadicDoesNotApply);
10398
John McCall9ae2f072010-08-23 23:25:46 +000010399 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010400 } else {
10401 // We matched a built-in operator. Convert the arguments, then
10402 // break out so that we will build the appropriate built-in
10403 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010404 ExprResult ArgsRes0 =
10405 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10406 Best->Conversions[0], AA_Passing);
10407 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010408 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010409 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010410
John Wiegley429bb272011-04-08 18:41:53 +000010411 ExprResult ArgsRes1 =
10412 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10413 Best->Conversions[1], AA_Passing);
10414 if (ArgsRes1.isInvalid())
10415 return ExprError();
10416 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010417 break;
10418 }
10419 }
10420
Douglas Gregor33074752009-09-30 21:46:01 +000010421 case OR_No_Viable_Function: {
10422 // C++ [over.match.oper]p9:
10423 // If the operator is the operator , [...] and there are no
10424 // viable functions, then the operator is assumed to be the
10425 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010426 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010427 break;
10428
Chandler Carruth6df868e2010-12-12 08:17:55 +000010429 // For class as left operand for assignment or compound assigment
10430 // operator do not fall through to handling in built-in, but report that
10431 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010432 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010433 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010434 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010435 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10436 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010437 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010438 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010439 // This is an erroneous use of an operator which can be overloaded by
10440 // a non-member function. Check for non-member operators which were
10441 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010442 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010443 // FIXME: Recover by calling the found function.
10444 return ExprError();
10445
Douglas Gregor33074752009-09-30 21:46:01 +000010446 // No viable function; try to create a built-in operation, which will
10447 // produce an error. Then, show the non-viable candidates.
10448 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010449 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010450 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010451 "C++ binary operator overloading is missing candidates!");
10452 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010453 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010454 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010455 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010456 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010457
10458 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010459 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010460 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010461 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010462 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010463 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010464 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010465 return ExprError();
10466
10467 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010468 if (isImplicitlyDeleted(Best->Function)) {
10469 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10470 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010471 << Context.getRecordType(Method->getParent())
10472 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010473
Richard Smith0f46e642012-12-28 12:23:24 +000010474 // The user probably meant to call this special member. Just
10475 // explain why it's deleted.
10476 NoteDeletedFunction(Method);
10477 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010478 } else {
10479 Diag(OpLoc, diag::err_ovl_deleted_oper)
10480 << Best->Function->isDeleted()
10481 << BinaryOperator::getOpcodeStr(Opc)
10482 << getDeletedOrUnavailableSuffix(Best->Function)
10483 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10484 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010485 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010486 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010487 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010488 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010489
Douglas Gregor33074752009-09-30 21:46:01 +000010490 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010491 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010492}
10493
John McCall60d7b3a2010-08-24 06:29:42 +000010494ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010495Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10496 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010497 Expr *Base, Expr *Idx) {
10498 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010499 DeclarationName OpName =
10500 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10501
10502 // If either side is type-dependent, create an appropriate dependent
10503 // expression.
10504 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10505
John McCallc373d482010-01-27 01:50:18 +000010506 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010507 // CHECKME: no 'operator' keyword?
10508 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10509 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010510 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010511 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010512 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010513 /*ADL*/ true, /*Overloaded*/ false,
10514 UnresolvedSetIterator(),
10515 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010516 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010517
Sebastian Redlf322ed62009-10-29 20:17:01 +000010518 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010519 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010520 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010521 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010522 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010523 }
10524
John McCall5acb0c92011-10-17 18:40:02 +000010525 // Handle placeholders on both operands.
10526 if (checkPlaceholderForOverload(*this, Args[0]))
10527 return ExprError();
10528 if (checkPlaceholderForOverload(*this, Args[1]))
10529 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010530
Sebastian Redlf322ed62009-10-29 20:17:01 +000010531 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010532 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010533
10534 // Subscript can only be overloaded as a member function.
10535
10536 // Add operator candidates that are member functions.
10537 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10538
10539 // Add builtin operator candidates.
10540 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10541
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010542 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10543
Sebastian Redlf322ed62009-10-29 20:17:01 +000010544 // Perform overload resolution.
10545 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010546 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010547 case OR_Success: {
10548 // We found a built-in operator or an overloaded operator.
10549 FunctionDecl *FnDecl = Best->Function;
10550
10551 if (FnDecl) {
10552 // We matched an overloaded operator. Build a call to that
10553 // operator.
10554
John McCall9aa472c2010-03-19 07:35:19 +000010555 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010556
Sebastian Redlf322ed62009-10-29 20:17:01 +000010557 // Convert the arguments.
10558 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010559 ExprResult Arg0 =
10560 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10561 Best->FoundDecl, Method);
10562 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010563 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010564 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010565
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010566 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010567 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010568 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010569 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010570 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010571 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010572 Owned(Args[1]));
10573 if (InputInit.isInvalid())
10574 return ExprError();
10575
10576 Args[1] = InputInit.takeAs<Expr>();
10577
Sebastian Redlf322ed62009-10-29 20:17:01 +000010578 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010579 QualType ResultTy = FnDecl->getResultType();
10580 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10581 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010582
10583 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010584 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10585 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010586 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010587 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010588 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010589 OpLocInfo.getLoc(),
10590 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010591 if (FnExpr.isInvalid())
10592 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010593
John McCall9ae2f072010-08-23 23:25:46 +000010594 CXXOperatorCallExpr *TheCall =
10595 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010596 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010597 ResultTy, VK, RLoc,
10598 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010599
John McCall9ae2f072010-08-23 23:25:46 +000010600 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010601 FnDecl))
10602 return ExprError();
10603
John McCall9ae2f072010-08-23 23:25:46 +000010604 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010605 } else {
10606 // We matched a built-in operator. Convert the arguments, then
10607 // break out so that we will build the appropriate built-in
10608 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010609 ExprResult ArgsRes0 =
10610 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10611 Best->Conversions[0], AA_Passing);
10612 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010613 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010614 Args[0] = ArgsRes0.take();
10615
10616 ExprResult ArgsRes1 =
10617 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10618 Best->Conversions[1], AA_Passing);
10619 if (ArgsRes1.isInvalid())
10620 return ExprError();
10621 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010622
10623 break;
10624 }
10625 }
10626
10627 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010628 if (CandidateSet.empty())
10629 Diag(LLoc, diag::err_ovl_no_oper)
10630 << Args[0]->getType() << /*subscript*/ 0
10631 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10632 else
10633 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10634 << Args[0]->getType()
10635 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010636 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010637 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010638 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010639 }
10640
10641 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010642 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010643 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010644 << Args[0]->getType() << Args[1]->getType()
10645 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010646 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010647 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010648 return ExprError();
10649
10650 case OR_Deleted:
10651 Diag(LLoc, diag::err_ovl_deleted_oper)
10652 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010653 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010654 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010655 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010656 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010657 return ExprError();
10658 }
10659
10660 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010661 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010662}
10663
Douglas Gregor88a35142008-12-22 05:46:06 +000010664/// BuildCallToMemberFunction - Build a call to a member
10665/// function. MemExpr is the expression that refers to the member
10666/// function (and includes the object parameter), Args/NumArgs are the
10667/// arguments to the function call (not including the object
10668/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010669/// expression refers to a non-static member function or an overloaded
10670/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010671ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010672Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10673 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010674 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010675 assert(MemExprE->getType() == Context.BoundMemberTy ||
10676 MemExprE->getType() == Context.OverloadTy);
10677
Douglas Gregor88a35142008-12-22 05:46:06 +000010678 // Dig out the member expression. This holds both the object
10679 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010680 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010681
John McCall864c0412011-04-26 20:42:42 +000010682 // Determine whether this is a call to a pointer-to-member function.
10683 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10684 assert(op->getType() == Context.BoundMemberTy);
10685 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10686
10687 QualType fnType =
10688 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10689
10690 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10691 QualType resultType = proto->getCallResultType(Context);
10692 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10693
10694 // Check that the object type isn't more qualified than the
10695 // member function we're calling.
10696 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10697
10698 QualType objectType = op->getLHS()->getType();
10699 if (op->getOpcode() == BO_PtrMemI)
10700 objectType = objectType->castAs<PointerType>()->getPointeeType();
10701 Qualifiers objectQuals = objectType.getQualifiers();
10702
10703 Qualifiers difference = objectQuals - funcQuals;
10704 difference.removeObjCGCAttr();
10705 difference.removeAddressSpace();
10706 if (difference) {
10707 std::string qualsString = difference.getAsString();
10708 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10709 << fnType.getUnqualifiedType()
10710 << qualsString
10711 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10712 }
10713
10714 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010715 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10716 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010717 resultType, valueKind, RParenLoc);
10718
10719 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010720 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010721 call, 0))
10722 return ExprError();
10723
10724 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10725 return ExprError();
10726
10727 return MaybeBindToTemporary(call);
10728 }
10729
John McCall5acb0c92011-10-17 18:40:02 +000010730 UnbridgedCastsSet UnbridgedCasts;
10731 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10732 return ExprError();
10733
John McCall129e2df2009-11-30 22:42:35 +000010734 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010735 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010736 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010737 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010738 if (isa<MemberExpr>(NakedMemExpr)) {
10739 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010740 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010741 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010742 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010743 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010744 } else {
10745 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010746 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010747
John McCall701c89e2009-12-03 04:06:58 +000010748 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010749 Expr::Classification ObjectClassification
10750 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10751 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010752
Douglas Gregor88a35142008-12-22 05:46:06 +000010753 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010754 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010755
John McCallaa81e162009-12-01 22:10:20 +000010756 // FIXME: avoid copy.
10757 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10758 if (UnresExpr->hasExplicitTemplateArgs()) {
10759 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10760 TemplateArgs = &TemplateArgsBuffer;
10761 }
10762
John McCall129e2df2009-11-30 22:42:35 +000010763 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10764 E = UnresExpr->decls_end(); I != E; ++I) {
10765
John McCall701c89e2009-12-03 04:06:58 +000010766 NamedDecl *Func = *I;
10767 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10768 if (isa<UsingShadowDecl>(Func))
10769 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10770
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010771
Francois Pichetdbee3412011-01-18 05:04:39 +000010772 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010773 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010774 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10775 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010776 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010777 // If explicit template arguments were provided, we can't call a
10778 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010779 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010780 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010781
John McCall9aa472c2010-03-19 07:35:19 +000010782 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010783 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010784 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010785 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010786 } else {
John McCall129e2df2009-11-30 22:42:35 +000010787 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010788 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010789 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010790 llvm::makeArrayRef(Args, NumArgs),
10791 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010792 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010793 }
Douglas Gregordec06662009-08-21 18:42:58 +000010794 }
Mike Stump1eb44332009-09-09 15:08:12 +000010795
John McCall129e2df2009-11-30 22:42:35 +000010796 DeclarationName DeclName = UnresExpr->getMemberName();
10797
John McCall5acb0c92011-10-17 18:40:02 +000010798 UnbridgedCasts.restore();
10799
Douglas Gregor88a35142008-12-22 05:46:06 +000010800 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010801 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010802 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010803 case OR_Success:
10804 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010805 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010806 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010807 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010808 break;
10809
10810 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010811 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010812 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010813 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010814 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10815 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010816 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010817 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010818
10819 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010820 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010821 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010822 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10823 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010824 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010825 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010826
10827 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010828 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010829 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010830 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010831 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010832 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010833 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10834 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010835 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010836 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010837 }
10838
John McCall6bb80172010-03-30 21:47:33 +000010839 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010840
John McCallaa81e162009-12-01 22:10:20 +000010841 // If overload resolution picked a static member, build a
10842 // non-member call based on that function.
10843 if (Method->isStatic()) {
10844 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10845 Args, NumArgs, RParenLoc);
10846 }
10847
John McCall129e2df2009-11-30 22:42:35 +000010848 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010849 }
10850
John McCallf89e55a2010-11-18 06:31:45 +000010851 QualType ResultType = Method->getResultType();
10852 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10853 ResultType = ResultType.getNonLValueExprType(Context);
10854
Douglas Gregor88a35142008-12-22 05:46:06 +000010855 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010856 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010857 new (Context) CXXMemberCallExpr(Context, MemExprE,
10858 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010859 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010860
Anders Carlssoneed3e692009-10-10 00:06:20 +000010861 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010862 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010863 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010864 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010865
Douglas Gregor88a35142008-12-22 05:46:06 +000010866 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010867 // We only need to do this if there was actually an overload; otherwise
10868 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010869 if (!Method->isStatic()) {
10870 ExprResult ObjectArg =
10871 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10872 FoundDecl, Method);
10873 if (ObjectArg.isInvalid())
10874 return ExprError();
10875 MemExpr->setBase(ObjectArg.take());
10876 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010877
10878 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010879 const FunctionProtoType *Proto =
10880 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010881 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010882 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010883 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010884
Eli Friedmane61eb042012-02-18 04:48:30 +000010885 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10886
Richard Smith831421f2012-06-25 20:30:08 +000010887 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010888 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010889
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010890 if ((isa<CXXConstructorDecl>(CurContext) ||
10891 isa<CXXDestructorDecl>(CurContext)) &&
10892 TheCall->getMethodDecl()->isPure()) {
10893 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10894
Chandler Carruthae198062011-06-27 08:31:58 +000010895 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010896 Diag(MemExpr->getLocStart(),
10897 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10898 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10899 << MD->getParent()->getDeclName();
10900
10901 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010902 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010903 }
John McCall9ae2f072010-08-23 23:25:46 +000010904 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010905}
10906
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010907/// BuildCallToObjectOfClassType - Build a call to an object of class
10908/// type (C++ [over.call.object]), which can end up invoking an
10909/// overloaded function call operator (@c operator()) or performing a
10910/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010911ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010912Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010913 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010914 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010915 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010916 if (checkPlaceholderForOverload(*this, Obj))
10917 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010918 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010919
10920 UnbridgedCastsSet UnbridgedCasts;
10921 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10922 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010923
John Wiegley429bb272011-04-08 18:41:53 +000010924 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10925 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010926
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010927 // C++ [over.call.object]p1:
10928 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010929 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010930 // candidate functions includes at least the function call
10931 // operators of T. The function call operators of T are obtained by
10932 // ordinary lookup of the name operator() in the context of
10933 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010934 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010935 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010936
John Wiegley429bb272011-04-08 18:41:53 +000010937 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010938 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010939 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010940
John McCalla24dc2e2009-11-17 02:14:36 +000010941 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10942 LookupQualifiedName(R, Record->getDecl());
10943 R.suppressDiagnostics();
10944
Douglas Gregor593564b2009-11-15 07:48:03 +000010945 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010946 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010947 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10948 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010949 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010950 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010951
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010952 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010953 // In addition, for each (non-explicit in C++0x) conversion function
10954 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010955 //
10956 // operator conversion-type-id () cv-qualifier;
10957 //
10958 // where cv-qualifier is the same cv-qualification as, or a
10959 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010960 // denotes the type "pointer to function of (P1,...,Pn) returning
10961 // R", or the type "reference to pointer to function of
10962 // (P1,...,Pn) returning R", or the type "reference to function
10963 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010964 // is also considered as a candidate function. Similarly,
10965 // surrogate call functions are added to the set of candidate
10966 // functions for each conversion function declared in an
10967 // accessible base class provided the function is not hidden
10968 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010969 std::pair<CXXRecordDecl::conversion_iterator,
10970 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010971 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010972 for (CXXRecordDecl::conversion_iterator
10973 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010974 NamedDecl *D = *I;
10975 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10976 if (isa<UsingShadowDecl>(D))
10977 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010978
Douglas Gregor4a27d702009-10-21 06:18:39 +000010979 // Skip over templated conversion functions; they aren't
10980 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010981 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010982 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010983
John McCall701c89e2009-12-03 04:06:58 +000010984 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010985 if (!Conv->isExplicit()) {
10986 // Strip the reference type (if any) and then the pointer type (if
10987 // any) to get down to what might be a function type.
10988 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10989 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10990 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010991
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010992 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10993 {
10994 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010995 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10996 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010997 }
10998 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010999 }
Mike Stump1eb44332009-09-09 15:08:12 +000011000
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011001 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11002
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011003 // Perform overload resolution.
11004 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011005 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011006 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011007 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011008 // Overload resolution succeeded; we'll build the appropriate call
11009 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011010 break;
11011
11012 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011013 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011014 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011015 << Object.get()->getType() << /*call*/ 1
11016 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011017 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011018 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011019 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011020 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011021 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11022 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011023 break;
11024
11025 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011026 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011027 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011028 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011029 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11030 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011031 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011032
11033 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011034 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011035 diag::err_ovl_deleted_object_call)
11036 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011037 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011038 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011039 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011040 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11041 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011042 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011043 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011044
Douglas Gregorff331c12010-07-25 18:17:45 +000011045 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011046 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011047
John McCall5acb0c92011-10-17 18:40:02 +000011048 UnbridgedCasts.restore();
11049
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011050 if (Best->Function == 0) {
11051 // Since there is no function declaration, this is one of the
11052 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011053 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011054 = cast<CXXConversionDecl>(
11055 Best->Conversions[0].UserDefined.ConversionFunction);
11056
John Wiegley429bb272011-04-08 18:41:53 +000011057 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011058 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011059
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011060 // We selected one of the surrogate functions that converts the
11061 // object parameter to a function pointer. Perform the conversion
11062 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011063
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011064 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011065 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011066 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11067 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011068 if (Call.isInvalid())
11069 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011070 // Record usage of conversion in an implicit cast.
11071 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11072 CK_UserDefinedConversion,
11073 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011074
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011075 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011076 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011077 }
11078
John Wiegley429bb272011-04-08 18:41:53 +000011079 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011080
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011081 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11082 // that calls this method, using Object for the implicit object
11083 // parameter and passing along the remaining arguments.
11084 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011085
11086 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011087 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011088 return ExprError();
11089
Chandler Carruth6df868e2010-12-12 08:17:55 +000011090 const FunctionProtoType *Proto =
11091 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011092
11093 unsigned NumArgsInProto = Proto->getNumArgs();
11094 unsigned NumArgsToCheck = NumArgs;
11095
11096 // Build the full argument list for the method call (the
11097 // implicit object parameter is placed at the beginning of the
11098 // list).
11099 Expr **MethodArgs;
11100 if (NumArgs < NumArgsInProto) {
11101 NumArgsToCheck = NumArgsInProto;
11102 MethodArgs = new Expr*[NumArgsInProto + 1];
11103 } else {
11104 MethodArgs = new Expr*[NumArgs + 1];
11105 }
John Wiegley429bb272011-04-08 18:41:53 +000011106 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011107 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11108 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011109
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011110 DeclarationNameInfo OpLocInfo(
11111 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11112 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011113 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011114 HadMultipleCandidates,
11115 OpLocInfo.getLoc(),
11116 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011117 if (NewFn.isInvalid())
11118 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011119
11120 // Once we've built TheCall, all of the expressions are properly
11121 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011122 QualType ResultTy = Method->getResultType();
11123 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11124 ResultTy = ResultTy.getNonLValueExprType(Context);
11125
John McCall9ae2f072010-08-23 23:25:46 +000011126 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011127 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011128 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011129 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011130 delete [] MethodArgs;
11131
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011132 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011133 Method))
11134 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011135
Douglas Gregor518fda12009-01-13 05:10:00 +000011136 // We may have default arguments. If so, we need to allocate more
11137 // slots in the call for them.
11138 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011139 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011140 else if (NumArgs > NumArgsInProto)
11141 NumArgsToCheck = NumArgsInProto;
11142
Chris Lattner312531a2009-04-12 08:11:20 +000011143 bool IsError = false;
11144
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011145 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011146 ExprResult ObjRes =
11147 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11148 Best->FoundDecl, Method);
11149 if (ObjRes.isInvalid())
11150 IsError = true;
11151 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011152 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011153 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011154
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011155 // Check the argument types.
11156 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011157 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011158 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011159 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011160
Douglas Gregor518fda12009-01-13 05:10:00 +000011161 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011162
John McCall60d7b3a2010-08-24 06:29:42 +000011163 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011164 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011165 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011166 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011167 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011168
Anders Carlsson3faa4862010-01-29 18:43:53 +000011169 IsError |= InputInit.isInvalid();
11170 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011171 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011172 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011173 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11174 if (DefArg.isInvalid()) {
11175 IsError = true;
11176 break;
11177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011178
Douglas Gregord47c47d2009-11-09 19:27:57 +000011179 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011180 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011181
11182 TheCall->setArg(i + 1, Arg);
11183 }
11184
11185 // If this is a variadic call, handle args passed through "...".
11186 if (Proto->isVariadic()) {
11187 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011188 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011189 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11190 IsError |= Arg.isInvalid();
11191 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011192 }
11193 }
11194
Chris Lattner312531a2009-04-12 08:11:20 +000011195 if (IsError) return true;
11196
Eli Friedmane61eb042012-02-18 04:48:30 +000011197 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11198
Richard Smith831421f2012-06-25 20:30:08 +000011199 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011200 return true;
11201
John McCall182f7092010-08-24 06:09:16 +000011202 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011203}
11204
Douglas Gregor8ba10742008-11-20 16:27:02 +000011205/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011206/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011207/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011208ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011209Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011210 assert(Base->getType()->isRecordType() &&
11211 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011212
John McCall5acb0c92011-10-17 18:40:02 +000011213 if (checkPlaceholderForOverload(*this, Base))
11214 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011215
John McCall5769d612010-02-08 23:07:23 +000011216 SourceLocation Loc = Base->getExprLoc();
11217
Douglas Gregor8ba10742008-11-20 16:27:02 +000011218 // C++ [over.ref]p1:
11219 //
11220 // [...] An expression x->m is interpreted as (x.operator->())->m
11221 // for a class object x of type T if T::operator->() exists and if
11222 // the operator is selected as the best match function by the
11223 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011224 DeclarationName OpName =
11225 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011226 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011227 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011228
John McCall5769d612010-02-08 23:07:23 +000011229 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011230 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011231 return ExprError();
11232
John McCalla24dc2e2009-11-17 02:14:36 +000011233 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11234 LookupQualifiedName(R, BaseRecord->getDecl());
11235 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011236
11237 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011238 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011239 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11240 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011241 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011242
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011243 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11244
Douglas Gregor8ba10742008-11-20 16:27:02 +000011245 // Perform overload resolution.
11246 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011247 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011248 case OR_Success:
11249 // Overload resolution succeeded; we'll build the call below.
11250 break;
11251
11252 case OR_No_Viable_Function:
11253 if (CandidateSet.empty())
11254 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011255 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011256 else
11257 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011258 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011259 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011260 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011261
11262 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011263 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11264 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011265 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011266 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011267
11268 case OR_Deleted:
11269 Diag(OpLoc, diag::err_ovl_deleted_oper)
11270 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011271 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011272 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011273 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011274 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011275 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011276 }
11277
John McCall9aa472c2010-03-19 07:35:19 +000011278 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11279
Douglas Gregor8ba10742008-11-20 16:27:02 +000011280 // Convert the object parameter.
11281 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011282 ExprResult BaseResult =
11283 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11284 Best->FoundDecl, Method);
11285 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011286 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011287 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011288
Douglas Gregor8ba10742008-11-20 16:27:02 +000011289 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011290 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011291 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011292 if (FnExpr.isInvalid())
11293 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011294
John McCallf89e55a2010-11-18 06:31:45 +000011295 QualType ResultTy = Method->getResultType();
11296 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11297 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011298 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011299 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011300 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011301
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011302 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011303 Method))
11304 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011305
11306 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011307}
11308
Richard Smith36f5cfe2012-03-09 08:00:36 +000011309/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11310/// a literal operator described by the provided lookup results.
11311ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11312 DeclarationNameInfo &SuffixInfo,
11313 ArrayRef<Expr*> Args,
11314 SourceLocation LitEndLoc,
11315 TemplateArgumentListInfo *TemplateArgs) {
11316 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011317
Richard Smith36f5cfe2012-03-09 08:00:36 +000011318 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11319 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11320 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011321
Richard Smith36f5cfe2012-03-09 08:00:36 +000011322 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11323
Richard Smith36f5cfe2012-03-09 08:00:36 +000011324 // Perform overload resolution. This will usually be trivial, but might need
11325 // to perform substitutions for a literal operator template.
11326 OverloadCandidateSet::iterator Best;
11327 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11328 case OR_Success:
11329 case OR_Deleted:
11330 break;
11331
11332 case OR_No_Viable_Function:
11333 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11334 << R.getLookupName();
11335 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11336 return ExprError();
11337
11338 case OR_Ambiguous:
11339 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11340 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11341 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011342 }
11343
Richard Smith36f5cfe2012-03-09 08:00:36 +000011344 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011345 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11346 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011347 SuffixInfo.getLoc(),
11348 SuffixInfo.getInfo());
11349 if (Fn.isInvalid())
11350 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011351
11352 // Check the argument types. This should almost always be a no-op, except
11353 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011354 Expr *ConvArgs[2];
11355 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11356 ExprResult InputInit = PerformCopyInitialization(
11357 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11358 SourceLocation(), Args[ArgIdx]);
11359 if (InputInit.isInvalid())
11360 return true;
11361 ConvArgs[ArgIdx] = InputInit.take();
11362 }
11363
Richard Smith9fcce652012-03-07 08:35:16 +000011364 QualType ResultTy = FD->getResultType();
11365 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11366 ResultTy = ResultTy.getNonLValueExprType(Context);
11367
Richard Smith9fcce652012-03-07 08:35:16 +000011368 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011369 new (Context) UserDefinedLiteral(Context, Fn.take(),
11370 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011371 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11372
11373 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11374 return ExprError();
11375
Richard Smith831421f2012-06-25 20:30:08 +000011376 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011377 return ExprError();
11378
11379 return MaybeBindToTemporary(UDL);
11380}
11381
Sam Panzere1715b62012-08-21 00:52:01 +000011382/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11383/// given LookupResult is non-empty, it is assumed to describe a member which
11384/// will be invoked. Otherwise, the function will be found via argument
11385/// dependent lookup.
11386/// CallExpr is set to a valid expression and FRS_Success returned on success,
11387/// otherwise CallExpr is set to ExprError() and some non-success value
11388/// is returned.
11389Sema::ForRangeStatus
11390Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11391 SourceLocation RangeLoc, VarDecl *Decl,
11392 BeginEndFunction BEF,
11393 const DeclarationNameInfo &NameInfo,
11394 LookupResult &MemberLookup,
11395 OverloadCandidateSet *CandidateSet,
11396 Expr *Range, ExprResult *CallExpr) {
11397 CandidateSet->clear();
11398 if (!MemberLookup.empty()) {
11399 ExprResult MemberRef =
11400 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11401 /*IsPtr=*/false, CXXScopeSpec(),
11402 /*TemplateKWLoc=*/SourceLocation(),
11403 /*FirstQualifierInScope=*/0,
11404 MemberLookup,
11405 /*TemplateArgs=*/0);
11406 if (MemberRef.isInvalid()) {
11407 *CallExpr = ExprError();
11408 Diag(Range->getLocStart(), diag::note_in_for_range)
11409 << RangeLoc << BEF << Range->getType();
11410 return FRS_DiagnosticIssued;
11411 }
11412 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11413 if (CallExpr->isInvalid()) {
11414 *CallExpr = ExprError();
11415 Diag(Range->getLocStart(), diag::note_in_for_range)
11416 << RangeLoc << BEF << Range->getType();
11417 return FRS_DiagnosticIssued;
11418 }
11419 } else {
11420 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011421 UnresolvedLookupExpr *Fn =
11422 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11423 NestedNameSpecifierLoc(), NameInfo,
11424 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011425 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011426
11427 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11428 CandidateSet, CallExpr);
11429 if (CandidateSet->empty() || CandidateSetError) {
11430 *CallExpr = ExprError();
11431 return FRS_NoViableFunction;
11432 }
11433 OverloadCandidateSet::iterator Best;
11434 OverloadingResult OverloadResult =
11435 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11436
11437 if (OverloadResult == OR_No_Viable_Function) {
11438 *CallExpr = ExprError();
11439 return FRS_NoViableFunction;
11440 }
11441 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11442 Loc, 0, CandidateSet, &Best,
11443 OverloadResult,
11444 /*AllowTypoCorrection=*/false);
11445 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11446 *CallExpr = ExprError();
11447 Diag(Range->getLocStart(), diag::note_in_for_range)
11448 << RangeLoc << BEF << Range->getType();
11449 return FRS_DiagnosticIssued;
11450 }
11451 }
11452 return FRS_Success;
11453}
11454
11455
Douglas Gregor904eed32008-11-10 20:40:00 +000011456/// FixOverloadedFunctionReference - E is an expression that refers to
11457/// a C++ overloaded function (possibly with some parentheses and
11458/// perhaps a '&' around it). We have resolved the overloaded function
11459/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011460/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011461Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011462 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011463 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011464 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11465 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011466 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011467 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011468
Douglas Gregor699ee522009-11-20 19:42:02 +000011469 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011470 }
11471
Douglas Gregor699ee522009-11-20 19:42:02 +000011472 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011473 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11474 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011475 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011476 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011477 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011478 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011479 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011480 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011481
11482 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011483 ICE->getCastKind(),
11484 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011485 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011486 }
11487
Douglas Gregor699ee522009-11-20 19:42:02 +000011488 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011489 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011490 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011491 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11492 if (Method->isStatic()) {
11493 // Do nothing: static member functions aren't any different
11494 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011495 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011496 // Fix the sub expression, which really has to be an
11497 // UnresolvedLookupExpr holding an overloaded member function
11498 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011499 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11500 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011501 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011502 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011503
John McCallba135432009-11-21 08:51:07 +000011504 assert(isa<DeclRefExpr>(SubExpr)
11505 && "fixed to something other than a decl ref");
11506 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11507 && "fixed to a member ref with no nested name qualifier");
11508
11509 // We have taken the address of a pointer to member
11510 // function. Perform the computation here so that we get the
11511 // appropriate pointer to member type.
11512 QualType ClassType
11513 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11514 QualType MemPtrType
11515 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11516
John McCallf89e55a2010-11-18 06:31:45 +000011517 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11518 VK_RValue, OK_Ordinary,
11519 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011520 }
11521 }
John McCall6bb80172010-03-30 21:47:33 +000011522 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11523 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011524 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011525 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011526
John McCall2de56d12010-08-25 11:45:40 +000011527 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011528 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011529 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011530 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011531 }
John McCallba135432009-11-21 08:51:07 +000011532
11533 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011534 // FIXME: avoid copy.
11535 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011536 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011537 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11538 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011539 }
11540
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011541 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11542 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011543 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011544 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011545 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011546 ULE->getNameLoc(),
11547 Fn->getType(),
11548 VK_LValue,
11549 Found.getDecl(),
11550 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011551 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011552 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11553 return DRE;
John McCallba135432009-11-21 08:51:07 +000011554 }
11555
John McCall129e2df2009-11-30 22:42:35 +000011556 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011557 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011558 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11559 if (MemExpr->hasExplicitTemplateArgs()) {
11560 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11561 TemplateArgs = &TemplateArgsBuffer;
11562 }
John McCalld5532b62009-11-23 01:53:49 +000011563
John McCallaa81e162009-12-01 22:10:20 +000011564 Expr *Base;
11565
John McCallf89e55a2010-11-18 06:31:45 +000011566 // If we're filling in a static method where we used to have an
11567 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011568 if (MemExpr->isImplicitAccess()) {
11569 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011570 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11571 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011572 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011573 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011574 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011575 MemExpr->getMemberLoc(),
11576 Fn->getType(),
11577 VK_LValue,
11578 Found.getDecl(),
11579 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011580 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011581 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11582 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011583 } else {
11584 SourceLocation Loc = MemExpr->getMemberLoc();
11585 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011586 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011587 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011588 Base = new (Context) CXXThisExpr(Loc,
11589 MemExpr->getBaseType(),
11590 /*isImplicit=*/true);
11591 }
John McCallaa81e162009-12-01 22:10:20 +000011592 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011593 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011594
John McCallf5307512011-04-27 00:36:17 +000011595 ExprValueKind valueKind;
11596 QualType type;
11597 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11598 valueKind = VK_LValue;
11599 type = Fn->getType();
11600 } else {
11601 valueKind = VK_RValue;
11602 type = Context.BoundMemberTy;
11603 }
11604
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011605 MemberExpr *ME = MemberExpr::Create(Context, Base,
11606 MemExpr->isArrow(),
11607 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011608 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011609 Fn,
11610 Found,
11611 MemExpr->getMemberNameInfo(),
11612 TemplateArgs,
11613 type, valueKind, OK_Ordinary);
11614 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011615 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011616 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011617 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011618
John McCall3fa5cae2010-10-26 07:05:15 +000011619 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011620}
11621
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011622ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011623 DeclAccessPair Found,
11624 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011625 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011626}
11627
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011628} // end namespace clang