blob: 89d495ddc197f2e0251e7450ab4188d185f25d1e [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 =
John McCall78037ac2013-04-03 21:19:47 +0000923 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
924 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000925
John McCall51fa86f2009-12-02 08:47:38 +0000926 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000927 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
928 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
929 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
930 continue;
931 }
932
John McCall871b2e72009-12-09 03:35:25 +0000933 Match = *I;
934 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000935 }
John McCall51fa86f2009-12-02 08:47:38 +0000936 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000937 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
938 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
939 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
940 continue;
941 }
942
John McCall871b2e72009-12-09 03:35:25 +0000943 Match = *I;
944 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000945 }
John McCalld7945c62010-11-10 03:01:53 +0000946 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000947 // We can overload with these, which can show up when doing
948 // redeclaration checks for UsingDecls.
949 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000950 } else if (isa<TagDecl>(OldD)) {
951 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000952 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
953 // Optimistically assume that an unresolved using decl will
954 // overload; if it doesn't, we'll have to diagnose during
955 // template instantiation.
956 } else {
John McCall68263142009-11-18 22:49:29 +0000957 // (C++ 13p1):
958 // Only function declarations can be overloaded; object and type
959 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000960 Match = *I;
961 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000962 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000963 }
John McCall68263142009-11-18 22:49:29 +0000964
John McCall871b2e72009-12-09 03:35:25 +0000965 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000966}
967
Rafael Espindola78eeba82012-12-28 14:21:58 +0000968static bool canBeOverloaded(const FunctionDecl &D) {
969 if (D.getAttr<OverloadableAttr>())
970 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000971 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000972 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000973
974 // Main cannot be overloaded (basic.start.main).
975 if (D.isMain())
976 return false;
977
Rafael Espindola78eeba82012-12-28 14:21:58 +0000978 return true;
979}
980
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000981static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
982 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000983 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
984 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
985
986 // C++ [temp.fct]p2:
987 // A function template can be overloaded with other function templates
988 // and with normal (non-template) functions.
989 if ((OldTemplate == 0) != (NewTemplate == 0))
990 return true;
991
992 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000993 QualType OldQType = S.Context.getCanonicalType(Old->getType());
994 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000995
996 // Compare the signatures (C++ 1.3.10) of the two functions to
997 // determine whether they are overloads. If we find any mismatch
998 // in the signature, they are overloads.
999
1000 // If either of these functions is a K&R-style function (no
1001 // prototype), then we consider them to have matching signatures.
1002 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1003 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1004 return false;
1005
John McCallf4c73712011-01-19 06:33:43 +00001006 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1007 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001008
1009 // The signature of a function includes the types of its
1010 // parameters (C++ 1.3.10), which includes the presence or absence
1011 // of the ellipsis; see C++ DR 357).
1012 if (OldQType != NewQType &&
1013 (OldType->getNumArgs() != NewType->getNumArgs() ||
1014 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001015 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001016 return true;
1017
1018 // C++ [temp.over.link]p4:
1019 // The signature of a function template consists of its function
1020 // signature, its return type and its template parameter list. The names
1021 // of the template parameters are significant only for establishing the
1022 // relationship between the template parameters and the rest of the
1023 // signature.
1024 //
1025 // We check the return type and template parameter lists for function
1026 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001027 //
1028 // However, we don't consider either of these when deciding whether
1029 // a member introduced by a shadow declaration is hidden.
1030 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001031 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1032 OldTemplate->getTemplateParameters(),
1033 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001034 OldType->getResultType() != NewType->getResultType()))
1035 return true;
1036
1037 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001038 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001039 //
1040 // As part of this, also check whether one of the member functions
1041 // is static, in which case they are not overloads (C++
1042 // 13.1p2). While not part of the definition of the signature,
1043 // this check is important to determine whether these functions
1044 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001045 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1046 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001047 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001048 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1049 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1050 if (!UseUsingDeclRules &&
1051 (OldMethod->getRefQualifier() == RQ_None ||
1052 NewMethod->getRefQualifier() == RQ_None)) {
1053 // C++0x [over.load]p2:
1054 // - Member function declarations with the same name and the same
1055 // parameter-type-list as well as member function template
1056 // declarations with the same name, the same parameter-type-list, and
1057 // the same template parameter lists cannot be overloaded if any of
1058 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001059 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001060 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001061 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001062 }
1063 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001064 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001065
Richard Smith21c8fa82013-01-14 05:37:29 +00001066 // We may not have applied the implicit const for a constexpr member
1067 // function yet (because we haven't yet resolved whether this is a static
1068 // or non-static member function). Add it now, on the assumption that this
1069 // is a redeclaration of OldMethod.
1070 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001071 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001072 NewQuals |= Qualifiers::Const;
1073 if (OldMethod->getTypeQualifiers() != NewQuals)
1074 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076
John McCall68263142009-11-18 22:49:29 +00001077 // The signatures match; this is not an overload.
1078 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001079}
1080
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001081bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1082 bool UseUsingDeclRules) {
1083 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1084 return false;
1085
1086 // If both of the functions are extern "C", then they are not
1087 // overloads.
1088 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1089 return false;
1090
1091 return true;
1092}
1093
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001094/// \brief Checks availability of the function depending on the current
1095/// function context. Inside an unavailable function, unavailability is ignored.
1096///
1097/// \returns true if \arg FD is unavailable and current context is inside
1098/// an available function, false otherwise.
1099bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1100 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1101}
1102
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001103/// \brief Tries a user-defined conversion from From to ToType.
1104///
1105/// Produces an implicit conversion sequence for when a standard conversion
1106/// is not an option. See TryImplicitConversion for more information.
1107static ImplicitConversionSequence
1108TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1109 bool SuppressUserConversions,
1110 bool AllowExplicit,
1111 bool InOverloadResolution,
1112 bool CStyle,
1113 bool AllowObjCWritebackConversion) {
1114 ImplicitConversionSequence ICS;
1115
1116 if (SuppressUserConversions) {
1117 // We're not in the case above, so there is no conversion that
1118 // we can perform.
1119 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1120 return ICS;
1121 }
1122
1123 // Attempt user-defined conversion.
1124 OverloadCandidateSet Conversions(From->getExprLoc());
1125 OverloadingResult UserDefResult
1126 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1127 AllowExplicit);
1128
1129 if (UserDefResult == OR_Success) {
1130 ICS.setUserDefined();
1131 // C++ [over.ics.user]p4:
1132 // A conversion of an expression of class type to the same class
1133 // type is given Exact Match rank, and a conversion of an
1134 // expression of class type to a base class of that type is
1135 // given Conversion rank, in spite of the fact that a copy
1136 // constructor (i.e., a user-defined conversion function) is
1137 // called for those cases.
1138 if (CXXConstructorDecl *Constructor
1139 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1140 QualType FromCanon
1141 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1142 QualType ToCanon
1143 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1144 if (Constructor->isCopyConstructor() &&
1145 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1146 // Turn this into a "standard" conversion sequence, so that it
1147 // gets ranked with standard conversion sequences.
1148 ICS.setStandard();
1149 ICS.Standard.setAsIdentityConversion();
1150 ICS.Standard.setFromType(From->getType());
1151 ICS.Standard.setAllToTypes(ToType);
1152 ICS.Standard.CopyConstructor = Constructor;
1153 if (ToCanon != FromCanon)
1154 ICS.Standard.Second = ICK_Derived_To_Base;
1155 }
1156 }
1157
1158 // C++ [over.best.ics]p4:
1159 // However, when considering the argument of a user-defined
1160 // conversion function that is a candidate by 13.3.1.3 when
1161 // invoked for the copying of the temporary in the second step
1162 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1163 // 13.3.1.6 in all cases, only standard conversion sequences and
1164 // ellipsis conversion sequences are allowed.
1165 if (SuppressUserConversions && ICS.isUserDefined()) {
1166 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1167 }
1168 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1169 ICS.setAmbiguous();
1170 ICS.Ambiguous.setFromType(From->getType());
1171 ICS.Ambiguous.setToType(ToType);
1172 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1173 Cand != Conversions.end(); ++Cand)
1174 if (Cand->Viable)
1175 ICS.Ambiguous.addConversion(Cand->Function);
1176 } else {
1177 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1178 }
1179
1180 return ICS;
1181}
1182
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001183/// TryImplicitConversion - Attempt to perform an implicit conversion
1184/// from the given expression (Expr) to the given type (ToType). This
1185/// function returns an implicit conversion sequence that can be used
1186/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001187///
1188/// void f(float f);
1189/// void g(int i) { f(i); }
1190///
1191/// this routine would produce an implicit conversion sequence to
1192/// describe the initialization of f from i, which will be a standard
1193/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1194/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1195//
1196/// Note that this routine only determines how the conversion can be
1197/// performed; it does not actually perform the conversion. As such,
1198/// it will not produce any diagnostics if no conversion is available,
1199/// but will instead return an implicit conversion sequence of kind
1200/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001201///
1202/// If @p SuppressUserConversions, then user-defined conversions are
1203/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001204/// If @p AllowExplicit, then explicit user-defined conversions are
1205/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001206///
1207/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1208/// writeback conversion, which allows __autoreleasing id* parameters to
1209/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001210static ImplicitConversionSequence
1211TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1212 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001213 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001214 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001215 bool CStyle,
1216 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001217 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001218 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001219 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001220 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001221 return ICS;
1222 }
1223
David Blaikie4e4d0842012-03-11 07:00:24 +00001224 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001226 return ICS;
1227 }
1228
Douglas Gregor604eb652010-08-11 02:15:33 +00001229 // C++ [over.ics.user]p4:
1230 // A conversion of an expression of class type to the same class
1231 // type is given Exact Match rank, and a conversion of an
1232 // expression of class type to a base class of that type is
1233 // given Conversion rank, in spite of the fact that a copy/move
1234 // constructor (i.e., a user-defined conversion function) is
1235 // called for those cases.
1236 QualType FromType = From->getType();
1237 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001238 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1239 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001240 ICS.setStandard();
1241 ICS.Standard.setAsIdentityConversion();
1242 ICS.Standard.setFromType(FromType);
1243 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001245 // We don't actually check at this point whether there is a valid
1246 // copy/move constructor, since overloading just assumes that it
1247 // exists. When we actually perform initialization, we'll find the
1248 // appropriate constructor to copy the returned object, if needed.
1249 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001251 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001252 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001253 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001254
Douglas Gregor604eb652010-08-11 02:15:33 +00001255 return ICS;
1256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001258 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259 AllowExplicit, InOverloadResolution, CStyle,
1260 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001261}
1262
John McCallf85e1932011-06-15 23:02:42 +00001263ImplicitConversionSequence
1264Sema::TryImplicitConversion(Expr *From, QualType ToType,
1265 bool SuppressUserConversions,
1266 bool AllowExplicit,
1267 bool InOverloadResolution,
1268 bool CStyle,
1269 bool AllowObjCWritebackConversion) {
1270 return clang::TryImplicitConversion(*this, From, ToType,
1271 SuppressUserConversions, AllowExplicit,
1272 InOverloadResolution, CStyle,
1273 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001274}
1275
Douglas Gregor575c63a2010-04-16 22:27:05 +00001276/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001277/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001278/// converted expression. Flavor is the kind of conversion we're
1279/// performing, used in the error message. If @p AllowExplicit,
1280/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001281ExprResult
1282Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001283 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001284 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001285 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001286}
1287
John Wiegley429bb272011-04-08 18:41:53 +00001288ExprResult
1289Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001290 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001291 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001292 if (checkPlaceholderForOverload(*this, From))
1293 return ExprError();
1294
John McCallf85e1932011-06-15 23:02:42 +00001295 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1296 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001297 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001298 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001299
John McCall120d63c2010-08-24 20:38:10 +00001300 ICS = clang::TryImplicitConversion(*this, From, ToType,
1301 /*SuppressUserConversions=*/false,
1302 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001303 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001304 /*CStyle=*/false,
1305 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001306 return PerformImplicitConversion(From, ToType, ICS, Action);
1307}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001308
1309/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001310/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001311bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1312 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001313 if (Context.hasSameUnqualifiedType(FromType, ToType))
1314 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315
John McCall00ccbef2010-12-21 00:44:39 +00001316 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1317 // where F adds one of the following at most once:
1318 // - a pointer
1319 // - a member pointer
1320 // - a block pointer
1321 CanQualType CanTo = Context.getCanonicalType(ToType);
1322 CanQualType CanFrom = Context.getCanonicalType(FromType);
1323 Type::TypeClass TyClass = CanTo->getTypeClass();
1324 if (TyClass != CanFrom->getTypeClass()) return false;
1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1326 if (TyClass == Type::Pointer) {
1327 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1328 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1329 } else if (TyClass == Type::BlockPointer) {
1330 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1331 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1332 } else if (TyClass == Type::MemberPointer) {
1333 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1334 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1335 } else {
1336 return false;
1337 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001338
John McCall00ccbef2010-12-21 00:44:39 +00001339 TyClass = CanTo->getTypeClass();
1340 if (TyClass != CanFrom->getTypeClass()) return false;
1341 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1342 return false;
1343 }
1344
1345 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1346 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1347 if (!EInfo.getNoReturn()) return false;
1348
1349 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1350 assert(QualType(FromFn, 0).isCanonical());
1351 if (QualType(FromFn, 0) != CanTo) return false;
1352
1353 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001354 return true;
1355}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001357/// \brief Determine whether the conversion from FromType to ToType is a valid
1358/// vector conversion.
1359///
1360/// \param ICK Will be set to the vector conversion kind, if this is a vector
1361/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001362static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1363 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001364 // We need at least one of these types to be a vector type to have a vector
1365 // conversion.
1366 if (!ToType->isVectorType() && !FromType->isVectorType())
1367 return false;
1368
1369 // Identical types require no conversions.
1370 if (Context.hasSameUnqualifiedType(FromType, ToType))
1371 return false;
1372
1373 // There are no conversions between extended vector types, only identity.
1374 if (ToType->isExtVectorType()) {
1375 // There are no conversions between extended vector types other than the
1376 // identity conversion.
1377 if (FromType->isExtVectorType())
1378 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001380 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001381 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001382 ICK = ICK_Vector_Splat;
1383 return true;
1384 }
1385 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001386
1387 // We can perform the conversion between vector types in the following cases:
1388 // 1)vector types are equivalent AltiVec and GCC vector types
1389 // 2)lax vector conversions are permitted and the vector types are of the
1390 // same size
1391 if (ToType->isVectorType() && FromType->isVectorType()) {
1392 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001393 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001394 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001395 ICK = ICK_Vector_Conversion;
1396 return true;
1397 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001398 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001399
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001400 return false;
1401}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402
Douglas Gregor7d000652012-04-12 20:48:09 +00001403static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1404 bool InOverloadResolution,
1405 StandardConversionSequence &SCS,
1406 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001407
Douglas Gregor60d62c22008-10-31 16:23:19 +00001408/// IsStandardConversion - Determines whether there is a standard
1409/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1410/// expression From to the type ToType. Standard conversion sequences
1411/// only consider non-class types; for conversions that involve class
1412/// types, use TryImplicitConversion. If a conversion exists, SCS will
1413/// contain the standard conversion sequence required to perform this
1414/// conversion and this routine will return true. Otherwise, this
1415/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001416static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1417 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001418 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001419 bool CStyle,
1420 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001421 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001422
Douglas Gregor60d62c22008-10-31 16:23:19 +00001423 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001424 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001425 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001426 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001427 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001428 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001429
Douglas Gregorf9201e02009-02-11 23:02:49 +00001430 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001431 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001432 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001433 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001434 return false;
1435
Mike Stump1eb44332009-09-09 15:08:12 +00001436 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001437 }
1438
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001439 // The first conversion can be an lvalue-to-rvalue conversion,
1440 // array-to-pointer conversion, or function-to-pointer conversion
1441 // (C++ 4p1).
1442
John McCall120d63c2010-08-24 20:38:10 +00001443 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001444 DeclAccessPair AccessPair;
1445 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001447 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001448 // We were able to resolve the address of the overloaded function,
1449 // so we can convert to the type of that function.
1450 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001451
1452 // we can sometimes resolve &foo<int> regardless of ToType, so check
1453 // if the type matches (identity) or we are converting to bool
1454 if (!S.Context.hasSameUnqualifiedType(
1455 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1456 QualType resultTy;
1457 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001458 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001459 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1460 // otherwise, only a boolean conversion is standard
1461 if (!ToType->isBooleanType())
1462 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001464
Chandler Carruth90434232011-03-29 08:08:18 +00001465 // Check if the "from" expression is taking the address of an overloaded
1466 // function and recompute the FromType accordingly. Take advantage of the
1467 // fact that non-static member functions *must* have such an address-of
1468 // expression.
1469 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1470 if (Method && !Method->isStatic()) {
1471 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1472 "Non-unary operator on non-static member address");
1473 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1474 == UO_AddrOf &&
1475 "Non-address-of operator on non-static member address");
1476 const Type *ClassType
1477 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1478 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001479 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1480 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1481 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001482 "Non-address-of operator for overloaded function expression");
1483 FromType = S.Context.getPointerType(FromType);
1484 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001486 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001487 assert(S.Context.hasSameType(
1488 FromType,
1489 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001490 } else {
1491 return false;
1492 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001493 }
John McCall21480112011-08-30 00:57:29 +00001494 // Lvalue-to-rvalue conversion (C++11 4.1):
1495 // A glvalue (3.10) of a non-function, non-array type T can
1496 // be converted to a prvalue.
1497 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001498 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001499 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001500 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001501 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001502
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001503 // C11 6.3.2.1p2:
1504 // ... if the lvalue has atomic type, the value has the non-atomic version
1505 // of the type of the lvalue ...
1506 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1507 FromType = Atomic->getValueType();
1508
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509 // If T is a non-class type, the type of the rvalue is the
1510 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001511 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1512 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001513 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001514 } else if (FromType->isArrayType()) {
1515 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001516 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517
1518 // An lvalue or rvalue of type "array of N T" or "array of unknown
1519 // bound of T" can be converted to an rvalue of type "pointer to
1520 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001521 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001522
John McCall120d63c2010-08-24 20:38:10 +00001523 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001524 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001525 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001526
1527 // For the purpose of ranking in overload resolution
1528 // (13.3.3.1.1), this conversion is considered an
1529 // array-to-pointer conversion followed by a qualification
1530 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001531 SCS.Second = ICK_Identity;
1532 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001533 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001534 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001535 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001536 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001537 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001538 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001539 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001540
1541 // An lvalue of function type T can be converted to an rvalue of
1542 // type "pointer to T." The result is a pointer to the
1543 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001544 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001545 } else {
1546 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001547 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001548 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001549 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001550
1551 // The second conversion can be an integral promotion, floating
1552 // point promotion, integral conversion, floating point conversion,
1553 // floating-integral conversion, pointer conversion,
1554 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001555 // For overloading in C, this can also be a "compatible-type"
1556 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001557 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001558 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001559 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001560 // The unqualified versions of the types are the same: there's no
1561 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001562 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001563 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001564 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001565 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001566 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001567 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001568 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001569 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001570 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001571 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001572 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001573 SCS.Second = ICK_Complex_Promotion;
1574 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001575 } else if (ToType->isBooleanType() &&
1576 (FromType->isArithmeticType() ||
1577 FromType->isAnyPointerType() ||
1578 FromType->isBlockPointerType() ||
1579 FromType->isMemberPointerType() ||
1580 FromType->isNullPtrType())) {
1581 // Boolean conversions (C++ 4.12).
1582 SCS.Second = ICK_Boolean_Conversion;
1583 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001584 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001585 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001586 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001587 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001588 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001589 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001590 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001591 SCS.Second = ICK_Complex_Conversion;
1592 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001593 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1594 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001595 // Complex-real conversions (C99 6.3.1.7)
1596 SCS.Second = ICK_Complex_Real;
1597 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001598 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001599 // Floating point conversions (C++ 4.8).
1600 SCS.Second = ICK_Floating_Conversion;
1601 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001602 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001603 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001604 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001605 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001606 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001607 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001608 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001609 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001610 SCS.Second = ICK_Block_Pointer_Conversion;
1611 } else if (AllowObjCWritebackConversion &&
1612 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1613 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001614 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1615 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001616 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001617 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001618 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001619 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001620 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001621 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001622 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001623 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001624 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001625 SCS.Second = SecondICK;
1626 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001628 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001629 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001630 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001631 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001632 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001633 // Treat a conversion that strips "noreturn" as an identity conversion.
1634 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001635 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1636 InOverloadResolution,
1637 SCS, CStyle)) {
1638 SCS.Second = ICK_TransparentUnionConversion;
1639 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001640 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1641 CStyle)) {
1642 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001643 // appropriately.
1644 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001645 } else if (ToType->isEventT() &&
1646 From->isIntegerConstantExpr(S.getASTContext()) &&
1647 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1648 SCS.Second = ICK_Zero_Event_Conversion;
1649 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001650 } else {
1651 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001652 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001653 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001654 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001655
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001656 QualType CanonFrom;
1657 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001658 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001659 bool ObjCLifetimeConversion;
1660 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1661 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001662 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001663 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001664 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001665 CanonFrom = S.Context.getCanonicalType(FromType);
1666 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667 } else {
1668 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001669 SCS.Third = ICK_Identity;
1670
Mike Stump1eb44332009-09-09 15:08:12 +00001671 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001672 // [...] Any difference in top-level cv-qualification is
1673 // subsumed by the initialization itself and does not constitute
1674 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001675 CanonFrom = S.Context.getCanonicalType(FromType);
1676 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001678 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001679 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001680 FromType = ToType;
1681 CanonFrom = CanonTo;
1682 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001683 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001684 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001685
1686 // If we have not converted the argument type to the parameter type,
1687 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001688 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001689 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001690
Douglas Gregor60d62c22008-10-31 16:23:19 +00001691 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001692}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001693
1694static bool
1695IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1696 QualType &ToType,
1697 bool InOverloadResolution,
1698 StandardConversionSequence &SCS,
1699 bool CStyle) {
1700
1701 const RecordType *UT = ToType->getAsUnionType();
1702 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1703 return false;
1704 // The field to initialize within the transparent union.
1705 RecordDecl *UD = UT->getDecl();
1706 // It's compatible if the expression matches any of the fields.
1707 for (RecordDecl::field_iterator it = UD->field_begin(),
1708 itend = UD->field_end();
1709 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001710 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1711 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001712 ToType = it->getType();
1713 return true;
1714 }
1715 }
1716 return false;
1717}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001718
1719/// IsIntegralPromotion - Determines whether the conversion from the
1720/// expression From (whose potentially-adjusted type is FromType) to
1721/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1722/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001723bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001724 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001725 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001726 if (!To) {
1727 return false;
1728 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001729
1730 // An rvalue of type char, signed char, unsigned char, short int, or
1731 // unsigned short int can be converted to an rvalue of type int if
1732 // int can represent all the values of the source type; otherwise,
1733 // the source rvalue can be converted to an rvalue of type unsigned
1734 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001735 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1736 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001737 if (// We can promote any signed, promotable integer type to an int
1738 (FromType->isSignedIntegerType() ||
1739 // We can promote any unsigned integer type whose size is
1740 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001741 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001742 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001743 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001744 }
1745
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001746 return To->getKind() == BuiltinType::UInt;
1747 }
1748
Richard Smithe7ff9192012-09-13 21:18:54 +00001749 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001750 // A prvalue of an unscoped enumeration type whose underlying type is not
1751 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1752 // following types that can represent all the values of the enumeration
1753 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1754 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001755 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001756 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001757 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001758 // with lowest integer conversion rank (4.13) greater than the rank of long
1759 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001760 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001761 // C++11 [conv.prom]p4:
1762 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1763 // can be converted to a prvalue of its underlying type. Moreover, if
1764 // integral promotion can be applied to its underlying type, a prvalue of an
1765 // unscoped enumeration type whose underlying type is fixed can also be
1766 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001767 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1768 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1769 // provided for a scoped enumeration.
1770 if (FromEnumType->getDecl()->isScoped())
1771 return false;
1772
Richard Smithe7ff9192012-09-13 21:18:54 +00001773 // We can perform an integral promotion to the underlying type of the enum,
1774 // even if that's not the promoted type.
1775 if (FromEnumType->getDecl()->isFixed()) {
1776 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1777 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1778 IsIntegralPromotion(From, Underlying, ToType);
1779 }
1780
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001781 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001783 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001784 return Context.hasSameUnqualifiedType(ToType,
1785 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001786 }
John McCall842aef82009-12-09 09:09:27 +00001787
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001788 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001789 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1790 // to an rvalue a prvalue of the first of the following types that can
1791 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001792 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001793 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001794 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001796 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001797 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001798 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799 // Determine whether the type we're converting from is signed or
1800 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001801 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001803
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804 // The types we'll try to promote to, in the appropriate
1805 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001806 QualType PromoteTypes[6] = {
1807 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001808 Context.LongTy, Context.UnsignedLongTy ,
1809 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001810 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001811 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1813 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001814 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1816 // We found the type that we can promote to. If this is the
1817 // type we wanted, we have a promotion. Otherwise, no
1818 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001819 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001820 }
1821 }
1822 }
1823
1824 // An rvalue for an integral bit-field (9.6) can be converted to an
1825 // rvalue of type int if int can represent all the values of the
1826 // bit-field; otherwise, it can be converted to unsigned int if
1827 // unsigned int can represent all the values of the bit-field. If
1828 // the bit-field is larger yet, no integral promotion applies to
1829 // it. If the bit-field has an enumerated type, it is treated as any
1830 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001831 // FIXME: We should delay checking of bit-fields until we actually perform the
1832 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001833 using llvm::APSInt;
1834 if (From)
1835 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001836 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001837 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001838 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1839 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1840 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregor86f19402008-12-20 23:49:58 +00001842 // Are we promoting to an int from a bitfield that fits in an int?
1843 if (BitWidth < ToSize ||
1844 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1845 return To->getKind() == BuiltinType::Int;
1846 }
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Douglas Gregor86f19402008-12-20 23:49:58 +00001848 // Are we promoting to an unsigned int from an unsigned bitfield
1849 // that fits into an unsigned int?
1850 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1851 return To->getKind() == BuiltinType::UInt;
1852 }
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Douglas Gregor86f19402008-12-20 23:49:58 +00001854 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001855 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001858 // An rvalue of type bool can be converted to an rvalue of type int,
1859 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001860 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001861 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001862 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001863
1864 return false;
1865}
1866
1867/// IsFloatingPointPromotion - Determines whether the conversion from
1868/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1869/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001870bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001871 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1872 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001873 /// An rvalue of type float can be converted to an rvalue of type
1874 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001875 if (FromBuiltin->getKind() == BuiltinType::Float &&
1876 ToBuiltin->getKind() == BuiltinType::Double)
1877 return true;
1878
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001879 // C99 6.3.1.5p1:
1880 // When a float is promoted to double or long double, or a
1881 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001882 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001883 (FromBuiltin->getKind() == BuiltinType::Float ||
1884 FromBuiltin->getKind() == BuiltinType::Double) &&
1885 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1886 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001887
1888 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001889 if (!getLangOpts().NativeHalfType &&
1890 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001891 ToBuiltin->getKind() == BuiltinType::Float)
1892 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001893 }
1894
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001895 return false;
1896}
1897
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001898/// \brief Determine if a conversion is a complex promotion.
1899///
1900/// A complex promotion is defined as a complex -> complex conversion
1901/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001902/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001903bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001904 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001905 if (!FromComplex)
1906 return false;
1907
John McCall183700f2009-09-21 23:43:11 +00001908 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001909 if (!ToComplex)
1910 return false;
1911
1912 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001913 ToComplex->getElementType()) ||
1914 IsIntegralPromotion(0, FromComplex->getElementType(),
1915 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001916}
1917
Douglas Gregorcb7de522008-11-26 23:31:11 +00001918/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1919/// the pointer type FromPtr to a pointer to type ToPointee, with the
1920/// same type qualifiers as FromPtr has on its pointee type. ToType,
1921/// if non-empty, will be a pointer to ToType that may or may not have
1922/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001923///
Mike Stump1eb44332009-09-09 15:08:12 +00001924static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001925BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001926 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001927 ASTContext &Context,
1928 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001929 assert((FromPtr->getTypeClass() == Type::Pointer ||
1930 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1931 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001932
John McCallf85e1932011-06-15 23:02:42 +00001933 /// Conversions to 'id' subsume cv-qualifier conversions.
1934 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001935 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001936
1937 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001938 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001939 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001940 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001941
John McCallf85e1932011-06-15 23:02:42 +00001942 if (StripObjCLifetime)
1943 Quals.removeObjCLifetime();
1944
Mike Stump1eb44332009-09-09 15:08:12 +00001945 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001946 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001947 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001948 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001949 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001950
1951 // Build a pointer to ToPointee. It has the right qualifiers
1952 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001953 if (isa<ObjCObjectPointerType>(ToType))
1954 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001955 return Context.getPointerType(ToPointee);
1956 }
1957
1958 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001959 QualType QualifiedCanonToPointee
1960 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001961
Douglas Gregorda80f742010-12-01 21:43:58 +00001962 if (isa<ObjCObjectPointerType>(ToType))
1963 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1964 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001965}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001966
Mike Stump1eb44332009-09-09 15:08:12 +00001967static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001968 bool InOverloadResolution,
1969 ASTContext &Context) {
1970 // Handle value-dependent integral null pointer constants correctly.
1971 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1972 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001973 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001974 return !InOverloadResolution;
1975
Douglas Gregorce940492009-09-25 04:25:58 +00001976 return Expr->isNullPointerConstant(Context,
1977 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1978 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001979}
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001981/// IsPointerConversion - Determines whether the conversion of the
1982/// expression From, which has the (possibly adjusted) type FromType,
1983/// can be converted to the type ToType via a pointer conversion (C++
1984/// 4.10). If so, returns true and places the converted type (that
1985/// might differ from ToType in its cv-qualifiers at some level) into
1986/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001987///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001988/// This routine also supports conversions to and from block pointers
1989/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1990/// pointers to interfaces. FIXME: Once we've determined the
1991/// appropriate overloading rules for Objective-C, we may want to
1992/// split the Objective-C checks into a different routine; however,
1993/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001994/// conversions, so for now they live here. IncompatibleObjC will be
1995/// set if the conversion is an allowed Objective-C conversion that
1996/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001997bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001998 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001999 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002000 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002001 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002002 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2003 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002004 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002005
Mike Stump1eb44332009-09-09 15:08:12 +00002006 // Conversion from a null pointer constant to any Objective-C pointer type.
2007 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002008 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002009 ConvertedType = ToType;
2010 return true;
2011 }
2012
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002013 // Blocks: Block pointers can be converted to void*.
2014 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002015 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002016 ConvertedType = ToType;
2017 return true;
2018 }
2019 // Blocks: A null pointer constant can be converted to a block
2020 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002021 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002022 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002023 ConvertedType = ToType;
2024 return true;
2025 }
2026
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002027 // If the left-hand-side is nullptr_t, the right side can be a null
2028 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002029 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002030 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002031 ConvertedType = ToType;
2032 return true;
2033 }
2034
Ted Kremenek6217b802009-07-29 21:53:49 +00002035 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002036 if (!ToTypePtr)
2037 return false;
2038
2039 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002040 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002041 ConvertedType = ToType;
2042 return true;
2043 }
Sebastian Redl07779722008-10-31 14:43:28 +00002044
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002045 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002046 // , including objective-c pointers.
2047 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002048 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002049 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002050 ConvertedType = BuildSimilarlyQualifiedPointerType(
2051 FromType->getAs<ObjCObjectPointerType>(),
2052 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002053 ToType, Context);
2054 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002055 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002056 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002057 if (!FromTypePtr)
2058 return false;
2059
2060 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002061
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002062 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002063 // pointer conversion, so don't do all of the work below.
2064 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2065 return false;
2066
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002067 // An rvalue of type "pointer to cv T," where T is an object type,
2068 // can be converted to an rvalue of type "pointer to cv void" (C++
2069 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002070 if (FromPointeeType->isIncompleteOrObjectType() &&
2071 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002072 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002073 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002074 ToType, Context,
2075 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002076 return true;
2077 }
2078
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002079 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002080 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002081 ToPointeeType->isVoidType()) {
2082 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2083 ToPointeeType,
2084 ToType, Context);
2085 return true;
2086 }
2087
Douglas Gregorf9201e02009-02-11 23:02:49 +00002088 // When we're overloading in C, we allow a special kind of pointer
2089 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002090 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002091 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002092 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002093 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002094 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002095 return true;
2096 }
2097
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002098 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002099 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002100 // An rvalue of type "pointer to cv D," where D is a class type,
2101 // can be converted to an rvalue of type "pointer to cv B," where
2102 // B is a base class (clause 10) of D. If B is an inaccessible
2103 // (clause 11) or ambiguous (10.2) base class of D, a program that
2104 // necessitates this conversion is ill-formed. The result of the
2105 // conversion is a pointer to the base class sub-object of the
2106 // derived class object. The null pointer value is converted to
2107 // the null pointer value of the destination type.
2108 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002109 // Note that we do not check for ambiguity or inaccessibility
2110 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002111 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002112 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002113 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002114 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002115 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002116 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002117 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002118 ToType, Context);
2119 return true;
2120 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002121
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002122 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2123 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2124 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2125 ToPointeeType,
2126 ToType, Context);
2127 return true;
2128 }
2129
Douglas Gregorc7887512008-12-19 19:13:09 +00002130 return false;
2131}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002132
2133/// \brief Adopt the given qualifiers for the given type.
2134static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2135 Qualifiers TQs = T.getQualifiers();
2136
2137 // Check whether qualifiers already match.
2138 if (TQs == Qs)
2139 return T;
2140
2141 if (Qs.compatiblyIncludes(TQs))
2142 return Context.getQualifiedType(T, Qs);
2143
2144 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2145}
Douglas Gregorc7887512008-12-19 19:13:09 +00002146
2147/// isObjCPointerConversion - Determines whether this is an
2148/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2149/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002150bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002151 QualType& ConvertedType,
2152 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002153 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002154 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002155
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002156 // The set of qualifiers on the type we're converting from.
2157 Qualifiers FromQualifiers = FromType.getQualifiers();
2158
Steve Naroff14108da2009-07-10 23:34:53 +00002159 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002160 const ObjCObjectPointerType* ToObjCPtr =
2161 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002162 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002163 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002164
Steve Naroff14108da2009-07-10 23:34:53 +00002165 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002166 // If the pointee types are the same (ignoring qualifications),
2167 // then this is not a pointer conversion.
2168 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2169 FromObjCPtr->getPointeeType()))
2170 return false;
2171
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002172 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002173 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002174 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002175 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002176 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002177 return true;
2178 }
2179 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002180 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002181 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002182 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002183 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002184 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002185 return true;
2186 }
2187 // Objective C++: We're able to convert from a pointer to an
2188 // interface to a pointer to a different interface.
2189 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002190 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2191 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002192 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002193 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2194 FromObjCPtr->getPointeeType()))
2195 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002196 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002197 ToObjCPtr->getPointeeType(),
2198 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002199 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002200 return true;
2201 }
2202
2203 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2204 // Okay: this is some kind of implicit downcast of Objective-C
2205 // interfaces, which is permitted. However, we're going to
2206 // complain about it.
2207 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002209 ToObjCPtr->getPointeeType(),
2210 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002212 return true;
2213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214 }
Steve Naroff14108da2009-07-10 23:34:53 +00002215 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002216 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002217 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002218 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002220 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002221 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002222 // to a block pointer type.
2223 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002225 return true;
2226 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002227 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002228 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002229 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002230 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002231 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002232 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002233 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002234 return true;
2235 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002236 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002237 return false;
2238
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002239 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002240 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002241 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002242 else if (const BlockPointerType *FromBlockPtr =
2243 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002244 FromPointeeType = FromBlockPtr->getPointeeType();
2245 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002246 return false;
2247
Douglas Gregorc7887512008-12-19 19:13:09 +00002248 // If we have pointers to pointers, recursively check whether this
2249 // is an Objective-C conversion.
2250 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2251 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2252 IncompatibleObjC)) {
2253 // We always complain about this conversion.
2254 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002255 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002256 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002257 return true;
2258 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002259 // Allow conversion of pointee being objective-c pointer to another one;
2260 // as in I* to id.
2261 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2262 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2263 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2264 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002265
Douglas Gregorda80f742010-12-01 21:43:58 +00002266 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002268 return true;
2269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002270
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002271 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002272 // differences in the argument and result types are in Objective-C
2273 // pointer conversions. If so, we permit the conversion (but
2274 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002275 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002276 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002277 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002278 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002279 if (FromFunctionType && ToFunctionType) {
2280 // If the function types are exactly the same, this isn't an
2281 // Objective-C pointer conversion.
2282 if (Context.getCanonicalType(FromPointeeType)
2283 == Context.getCanonicalType(ToPointeeType))
2284 return false;
2285
2286 // Perform the quick checks that will tell us whether these
2287 // function types are obviously different.
2288 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2289 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2290 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2291 return false;
2292
2293 bool HasObjCConversion = false;
2294 if (Context.getCanonicalType(FromFunctionType->getResultType())
2295 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2296 // Okay, the types match exactly. Nothing to do.
2297 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2298 ToFunctionType->getResultType(),
2299 ConvertedType, IncompatibleObjC)) {
2300 // Okay, we have an Objective-C pointer conversion.
2301 HasObjCConversion = true;
2302 } else {
2303 // Function types are too different. Abort.
2304 return false;
2305 }
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Douglas Gregorc7887512008-12-19 19:13:09 +00002307 // Check argument types.
2308 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2309 ArgIdx != NumArgs; ++ArgIdx) {
2310 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2311 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2312 if (Context.getCanonicalType(FromArgType)
2313 == Context.getCanonicalType(ToArgType)) {
2314 // Okay, the types match exactly. Nothing to do.
2315 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2316 ConvertedType, IncompatibleObjC)) {
2317 // Okay, we have an Objective-C pointer conversion.
2318 HasObjCConversion = true;
2319 } else {
2320 // Argument types are too different. Abort.
2321 return false;
2322 }
2323 }
2324
2325 if (HasObjCConversion) {
2326 // We had an Objective-C conversion. Allow this pointer
2327 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002328 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002329 IncompatibleObjC = true;
2330 return true;
2331 }
2332 }
2333
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002334 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002335}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002336
John McCallf85e1932011-06-15 23:02:42 +00002337/// \brief Determine whether this is an Objective-C writeback conversion,
2338/// used for parameter passing when performing automatic reference counting.
2339///
2340/// \param FromType The type we're converting form.
2341///
2342/// \param ToType The type we're converting to.
2343///
2344/// \param ConvertedType The type that will be produced after applying
2345/// this conversion.
2346bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2347 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002348 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002349 Context.hasSameUnqualifiedType(FromType, ToType))
2350 return false;
2351
2352 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2353 QualType ToPointee;
2354 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2355 ToPointee = ToPointer->getPointeeType();
2356 else
2357 return false;
2358
2359 Qualifiers ToQuals = ToPointee.getQualifiers();
2360 if (!ToPointee->isObjCLifetimeType() ||
2361 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002362 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002363 return false;
2364
2365 // Argument must be a pointer to __strong to __weak.
2366 QualType FromPointee;
2367 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2368 FromPointee = FromPointer->getPointeeType();
2369 else
2370 return false;
2371
2372 Qualifiers FromQuals = FromPointee.getQualifiers();
2373 if (!FromPointee->isObjCLifetimeType() ||
2374 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2375 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2376 return false;
2377
2378 // Make sure that we have compatible qualifiers.
2379 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2380 if (!ToQuals.compatiblyIncludes(FromQuals))
2381 return false;
2382
2383 // Remove qualifiers from the pointee type we're converting from; they
2384 // aren't used in the compatibility check belong, and we'll be adding back
2385 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2386 FromPointee = FromPointee.getUnqualifiedType();
2387
2388 // The unqualified form of the pointee types must be compatible.
2389 ToPointee = ToPointee.getUnqualifiedType();
2390 bool IncompatibleObjC;
2391 if (Context.typesAreCompatible(FromPointee, ToPointee))
2392 FromPointee = ToPointee;
2393 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2394 IncompatibleObjC))
2395 return false;
2396
2397 /// \brief Construct the type we're converting to, which is a pointer to
2398 /// __autoreleasing pointee.
2399 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2400 ConvertedType = Context.getPointerType(FromPointee);
2401 return true;
2402}
2403
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002404bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2405 QualType& ConvertedType) {
2406 QualType ToPointeeType;
2407 if (const BlockPointerType *ToBlockPtr =
2408 ToType->getAs<BlockPointerType>())
2409 ToPointeeType = ToBlockPtr->getPointeeType();
2410 else
2411 return false;
2412
2413 QualType FromPointeeType;
2414 if (const BlockPointerType *FromBlockPtr =
2415 FromType->getAs<BlockPointerType>())
2416 FromPointeeType = FromBlockPtr->getPointeeType();
2417 else
2418 return false;
2419 // We have pointer to blocks, check whether the only
2420 // differences in the argument and result types are in Objective-C
2421 // pointer conversions. If so, we permit the conversion.
2422
2423 const FunctionProtoType *FromFunctionType
2424 = FromPointeeType->getAs<FunctionProtoType>();
2425 const FunctionProtoType *ToFunctionType
2426 = ToPointeeType->getAs<FunctionProtoType>();
2427
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002428 if (!FromFunctionType || !ToFunctionType)
2429 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002430
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002431 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002432 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002433
2434 // Perform the quick checks that will tell us whether these
2435 // function types are obviously different.
2436 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2437 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2438 return false;
2439
2440 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2441 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2442 if (FromEInfo != ToEInfo)
2443 return false;
2444
2445 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002446 if (Context.hasSameType(FromFunctionType->getResultType(),
2447 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002448 // Okay, the types match exactly. Nothing to do.
2449 } else {
2450 QualType RHS = FromFunctionType->getResultType();
2451 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002452 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002453 !RHS.hasQualifiers() && LHS.hasQualifiers())
2454 LHS = LHS.getUnqualifiedType();
2455
2456 if (Context.hasSameType(RHS,LHS)) {
2457 // OK exact match.
2458 } else if (isObjCPointerConversion(RHS, LHS,
2459 ConvertedType, IncompatibleObjC)) {
2460 if (IncompatibleObjC)
2461 return false;
2462 // Okay, we have an Objective-C pointer conversion.
2463 }
2464 else
2465 return false;
2466 }
2467
2468 // Check argument types.
2469 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2470 ArgIdx != NumArgs; ++ArgIdx) {
2471 IncompatibleObjC = false;
2472 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2473 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2474 if (Context.hasSameType(FromArgType, ToArgType)) {
2475 // Okay, the types match exactly. Nothing to do.
2476 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2477 ConvertedType, IncompatibleObjC)) {
2478 if (IncompatibleObjC)
2479 return false;
2480 // Okay, we have an Objective-C pointer conversion.
2481 } else
2482 // Argument types are too different. Abort.
2483 return false;
2484 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002485 if (LangOpts.ObjCAutoRefCount &&
2486 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2487 ToFunctionType))
2488 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002489
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002490 ConvertedType = ToType;
2491 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002492}
2493
Richard Trieu6efd4c52011-11-23 22:32:32 +00002494enum {
2495 ft_default,
2496 ft_different_class,
2497 ft_parameter_arity,
2498 ft_parameter_mismatch,
2499 ft_return_type,
2500 ft_qualifer_mismatch
2501};
2502
2503/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2504/// function types. Catches different number of parameter, mismatch in
2505/// parameter types, and different return types.
2506void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2507 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002508 // If either type is not valid, include no extra info.
2509 if (FromType.isNull() || ToType.isNull()) {
2510 PDiag << ft_default;
2511 return;
2512 }
2513
Richard Trieu6efd4c52011-11-23 22:32:32 +00002514 // Get the function type from the pointers.
2515 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2516 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2517 *ToMember = ToType->getAs<MemberPointerType>();
2518 if (FromMember->getClass() != ToMember->getClass()) {
2519 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2520 << QualType(FromMember->getClass(), 0);
2521 return;
2522 }
2523 FromType = FromMember->getPointeeType();
2524 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002525 }
2526
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002527 if (FromType->isPointerType())
2528 FromType = FromType->getPointeeType();
2529 if (ToType->isPointerType())
2530 ToType = ToType->getPointeeType();
2531
2532 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002533 FromType = FromType.getNonReferenceType();
2534 ToType = ToType.getNonReferenceType();
2535
Richard Trieu6efd4c52011-11-23 22:32:32 +00002536 // Don't print extra info for non-specialized template functions.
2537 if (FromType->isInstantiationDependentType() &&
2538 !FromType->getAs<TemplateSpecializationType>()) {
2539 PDiag << ft_default;
2540 return;
2541 }
2542
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002543 // No extra info for same types.
2544 if (Context.hasSameType(FromType, ToType)) {
2545 PDiag << ft_default;
2546 return;
2547 }
2548
Richard Trieu6efd4c52011-11-23 22:32:32 +00002549 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2550 *ToFunction = ToType->getAs<FunctionProtoType>();
2551
2552 // Both types need to be function types.
2553 if (!FromFunction || !ToFunction) {
2554 PDiag << ft_default;
2555 return;
2556 }
2557
2558 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2559 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2560 << FromFunction->getNumArgs();
2561 return;
2562 }
2563
2564 // Handle different parameter types.
2565 unsigned ArgPos;
2566 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2567 PDiag << ft_parameter_mismatch << ArgPos + 1
2568 << ToFunction->getArgType(ArgPos)
2569 << FromFunction->getArgType(ArgPos);
2570 return;
2571 }
2572
2573 // Handle different return type.
2574 if (!Context.hasSameType(FromFunction->getResultType(),
2575 ToFunction->getResultType())) {
2576 PDiag << ft_return_type << ToFunction->getResultType()
2577 << FromFunction->getResultType();
2578 return;
2579 }
2580
2581 unsigned FromQuals = FromFunction->getTypeQuals(),
2582 ToQuals = ToFunction->getTypeQuals();
2583 if (FromQuals != ToQuals) {
2584 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2585 return;
2586 }
2587
2588 // Unable to find a difference, so add no extra info.
2589 PDiag << ft_default;
2590}
2591
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002592/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002593/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002594/// they have same number of arguments. This routine assumes that Objective-C
2595/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002596/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002597/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002598bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002599 const FunctionProtoType *NewType,
2600 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002601 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002602 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2603 N = NewType->arg_type_begin(),
2604 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2605 if (!Context.hasSameType(*O, *N)) {
2606 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2607 return false;
2608 }
2609 }
2610 return true;
2611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002613 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2614 N = NewType->arg_type_begin(),
2615 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2616 QualType ToType = (*O);
2617 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002618 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002619 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2620 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002621 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2622 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2623 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2624 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002625 continue;
2626 }
John McCallc12c5bb2010-05-15 11:32:37 +00002627 else if (const ObjCObjectPointerType *PTTo =
2628 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002629 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002630 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002631 if (Context.hasSameUnqualifiedType(
2632 PTTo->getObjectType()->getBaseType(),
2633 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002634 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002635 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002636 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002637 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002638 }
2639 }
2640 return true;
2641}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002642
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002643/// CheckPointerConversion - Check the pointer conversion from the
2644/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002645/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002646/// conversions for which IsPointerConversion has already returned
2647/// true. It returns true and produces a diagnostic if there was an
2648/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002649bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002650 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002651 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002652 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002653 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002654 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002655
John McCalldaa8e4e2010-11-15 09:13:47 +00002656 Kind = CK_BitCast;
2657
David Blaikie50800fc2012-08-08 17:33:31 +00002658 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2659 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2660 Expr::NPCK_ZeroExpression) {
2661 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2662 DiagRuntimeBehavior(From->getExprLoc(), From,
2663 PDiag(diag::warn_impcast_bool_to_null_pointer)
2664 << ToType << From->getSourceRange());
2665 else if (!isUnevaluatedContext())
2666 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2667 << ToType << From->getSourceRange();
2668 }
John McCall1d9b3b22011-09-09 05:25:32 +00002669 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2670 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002671 QualType FromPointeeType = FromPtrType->getPointeeType(),
2672 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002673
Douglas Gregor5fccd362010-03-03 23:55:11 +00002674 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2675 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002676 // We must have a derived-to-base conversion. Check an
2677 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002678 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2679 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002680 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002681 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002682 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002683
Anders Carlsson61faec12009-09-12 04:46:44 +00002684 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002685 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002686 }
2687 }
John McCall1d9b3b22011-09-09 05:25:32 +00002688 } else if (const ObjCObjectPointerType *ToPtrType =
2689 ToType->getAs<ObjCObjectPointerType>()) {
2690 if (const ObjCObjectPointerType *FromPtrType =
2691 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002692 // Objective-C++ conversions are always okay.
2693 // FIXME: We should have a different class of conversions for the
2694 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002695 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002696 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002697 } else if (FromType->isBlockPointerType()) {
2698 Kind = CK_BlockPointerToObjCPointerCast;
2699 } else {
2700 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002701 }
John McCall1d9b3b22011-09-09 05:25:32 +00002702 } else if (ToType->isBlockPointerType()) {
2703 if (!FromType->isBlockPointerType())
2704 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002705 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002706
2707 // We shouldn't fall into this case unless it's valid for other
2708 // reasons.
2709 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2710 Kind = CK_NullToPointer;
2711
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002712 return false;
2713}
2714
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002715/// IsMemberPointerConversion - Determines whether the conversion of the
2716/// expression From, which has the (possibly adjusted) type FromType, can be
2717/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2718/// If so, returns true and places the converted type (that might differ from
2719/// ToType in its cv-qualifiers at some level) into ConvertedType.
2720bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002721 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002722 bool InOverloadResolution,
2723 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002724 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002725 if (!ToTypePtr)
2726 return false;
2727
2728 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002729 if (From->isNullPointerConstant(Context,
2730 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2731 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002732 ConvertedType = ToType;
2733 return true;
2734 }
2735
2736 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002737 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002738 if (!FromTypePtr)
2739 return false;
2740
2741 // A pointer to member of B can be converted to a pointer to member of D,
2742 // where D is derived from B (C++ 4.11p2).
2743 QualType FromClass(FromTypePtr->getClass(), 0);
2744 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002745
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002746 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002747 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002748 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002749 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2750 ToClass.getTypePtr());
2751 return true;
2752 }
2753
2754 return false;
2755}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002756
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002757/// CheckMemberPointerConversion - Check the member pointer conversion from the
2758/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002759/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002760/// for which IsMemberPointerConversion has already returned true. It returns
2761/// true and produces a diagnostic if there was an error, or returns false
2762/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002763bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002764 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002765 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002766 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002767 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002768 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002769 if (!FromPtrType) {
2770 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002771 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002772 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002773 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002774 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002775 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002776 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002777
Ted Kremenek6217b802009-07-29 21:53:49 +00002778 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002779 assert(ToPtrType && "No member pointer cast has a target type "
2780 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002781
Sebastian Redl21593ac2009-01-28 18:33:18 +00002782 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2783 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002784
Sebastian Redl21593ac2009-01-28 18:33:18 +00002785 // FIXME: What about dependent types?
2786 assert(FromClass->isRecordType() && "Pointer into non-class.");
2787 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002788
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002789 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002790 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002791 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2792 assert(DerivationOkay &&
2793 "Should not have been called if derivation isn't OK.");
2794 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002795
Sebastian Redl21593ac2009-01-28 18:33:18 +00002796 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2797 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002798 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2799 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2800 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2801 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002802 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002803
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002804 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002805 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2806 << FromClass << ToClass << QualType(VBase, 0)
2807 << From->getSourceRange();
2808 return true;
2809 }
2810
John McCall6b2accb2010-02-10 09:31:12 +00002811 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002812 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2813 Paths.front(),
2814 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002815
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002816 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002817 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002818 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002819 return false;
2820}
2821
Douglas Gregor98cd5992008-10-21 23:43:52 +00002822/// IsQualificationConversion - Determines whether the conversion from
2823/// an rvalue of type FromType to ToType is a qualification conversion
2824/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002825///
2826/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2827/// when the qualification conversion involves a change in the Objective-C
2828/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002829bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002831 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002832 FromType = Context.getCanonicalType(FromType);
2833 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002834 ObjCLifetimeConversion = false;
2835
Douglas Gregor98cd5992008-10-21 23:43:52 +00002836 // If FromType and ToType are the same type, this is not a
2837 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002838 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002839 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002840
Douglas Gregor98cd5992008-10-21 23:43:52 +00002841 // (C++ 4.4p4):
2842 // A conversion can add cv-qualifiers at levels other than the first
2843 // in multi-level pointers, subject to the following rules: [...]
2844 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002845 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002846 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002847 // Within each iteration of the loop, we check the qualifiers to
2848 // determine if this still looks like a qualification
2849 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002850 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002851 // until there are no more pointers or pointers-to-members left to
2852 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002853 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002854
Douglas Gregor621c92a2011-04-25 18:40:17 +00002855 Qualifiers FromQuals = FromType.getQualifiers();
2856 Qualifiers ToQuals = ToType.getQualifiers();
2857
John McCallf85e1932011-06-15 23:02:42 +00002858 // Objective-C ARC:
2859 // Check Objective-C lifetime conversions.
2860 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2861 UnwrappedAnyPointer) {
2862 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2863 ObjCLifetimeConversion = true;
2864 FromQuals.removeObjCLifetime();
2865 ToQuals.removeObjCLifetime();
2866 } else {
2867 // Qualification conversions cannot cast between different
2868 // Objective-C lifetime qualifiers.
2869 return false;
2870 }
2871 }
2872
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002873 // Allow addition/removal of GC attributes but not changing GC attributes.
2874 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2875 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2876 FromQuals.removeObjCGCAttr();
2877 ToQuals.removeObjCGCAttr();
2878 }
2879
Douglas Gregor98cd5992008-10-21 23:43:52 +00002880 // -- for every j > 0, if const is in cv 1,j then const is in cv
2881 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002882 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002883 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Douglas Gregor98cd5992008-10-21 23:43:52 +00002885 // -- if the cv 1,j and cv 2,j are different, then const is in
2886 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002887 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002888 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002889 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Douglas Gregor98cd5992008-10-21 23:43:52 +00002891 // Keep track of whether all prior cv-qualifiers in the "to" type
2892 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002893 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002894 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002895 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002896
2897 // We are left with FromType and ToType being the pointee types
2898 // after unwrapping the original FromType and ToType the same number
2899 // of types. If we unwrapped any pointers, and if FromType and
2900 // ToType have the same unqualified type (since we checked
2901 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002902 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002903}
2904
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002905/// \brief - Determine whether this is a conversion from a scalar type to an
2906/// atomic type.
2907///
2908/// If successful, updates \c SCS's second and third steps in the conversion
2909/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002910static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2911 bool InOverloadResolution,
2912 StandardConversionSequence &SCS,
2913 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002914 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2915 if (!ToAtomic)
2916 return false;
2917
2918 StandardConversionSequence InnerSCS;
2919 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2920 InOverloadResolution, InnerSCS,
2921 CStyle, /*AllowObjCWritebackConversion=*/false))
2922 return false;
2923
2924 SCS.Second = InnerSCS.Second;
2925 SCS.setToType(1, InnerSCS.getToType(1));
2926 SCS.Third = InnerSCS.Third;
2927 SCS.QualificationIncludesObjCLifetime
2928 = InnerSCS.QualificationIncludesObjCLifetime;
2929 SCS.setToType(2, InnerSCS.getToType(2));
2930 return true;
2931}
2932
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002933static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2934 CXXConstructorDecl *Constructor,
2935 QualType Type) {
2936 const FunctionProtoType *CtorType =
2937 Constructor->getType()->getAs<FunctionProtoType>();
2938 if (CtorType->getNumArgs() > 0) {
2939 QualType FirstArg = CtorType->getArgType(0);
2940 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2941 return true;
2942 }
2943 return false;
2944}
2945
Sebastian Redl56a04282012-02-11 23:51:08 +00002946static OverloadingResult
2947IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2948 CXXRecordDecl *To,
2949 UserDefinedConversionSequence &User,
2950 OverloadCandidateSet &CandidateSet,
2951 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002952 DeclContext::lookup_result R = S.LookupConstructors(To);
2953 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002954 Con != ConEnd; ++Con) {
2955 NamedDecl *D = *Con;
2956 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2957
2958 // Find the constructor (which may be a template).
2959 CXXConstructorDecl *Constructor = 0;
2960 FunctionTemplateDecl *ConstructorTmpl
2961 = dyn_cast<FunctionTemplateDecl>(D);
2962 if (ConstructorTmpl)
2963 Constructor
2964 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2965 else
2966 Constructor = cast<CXXConstructorDecl>(D);
2967
2968 bool Usable = !Constructor->isInvalidDecl() &&
2969 S.isInitListConstructor(Constructor) &&
2970 (AllowExplicit || !Constructor->isExplicit());
2971 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002972 // If the first argument is (a reference to) the target type,
2973 // suppress conversions.
2974 bool SuppressUserConversions =
2975 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002976 if (ConstructorTmpl)
2977 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2978 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002979 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002980 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002981 else
2982 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002983 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002984 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002985 }
2986 }
2987
2988 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2989
2990 OverloadCandidateSet::iterator Best;
2991 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2992 case OR_Success: {
2993 // Record the standard conversion we used and the conversion function.
2994 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002995 QualType ThisType = Constructor->getThisType(S.Context);
2996 // Initializer lists don't have conversions as such.
2997 User.Before.setAsIdentityConversion();
2998 User.HadMultipleCandidates = HadMultipleCandidates;
2999 User.ConversionFunction = Constructor;
3000 User.FoundConversionFunction = Best->FoundDecl;
3001 User.After.setAsIdentityConversion();
3002 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3003 User.After.setAllToTypes(ToType);
3004 return OR_Success;
3005 }
3006
3007 case OR_No_Viable_Function:
3008 return OR_No_Viable_Function;
3009 case OR_Deleted:
3010 return OR_Deleted;
3011 case OR_Ambiguous:
3012 return OR_Ambiguous;
3013 }
3014
3015 llvm_unreachable("Invalid OverloadResult!");
3016}
3017
Douglas Gregor734d9862009-01-30 23:27:23 +00003018/// Determines whether there is a user-defined conversion sequence
3019/// (C++ [over.ics.user]) that converts expression From to the type
3020/// ToType. If such a conversion exists, User will contain the
3021/// user-defined conversion sequence that performs such a conversion
3022/// and this routine will return true. Otherwise, this routine returns
3023/// false and User is unspecified.
3024///
Douglas Gregor734d9862009-01-30 23:27:23 +00003025/// \param AllowExplicit true if the conversion should consider C++0x
3026/// "explicit" conversion functions as well as non-explicit conversion
3027/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003028static OverloadingResult
3029IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003030 UserDefinedConversionSequence &User,
3031 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003032 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003033 // Whether we will only visit constructors.
3034 bool ConstructorsOnly = false;
3035
3036 // If the type we are conversion to is a class type, enumerate its
3037 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003038 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003039 // C++ [over.match.ctor]p1:
3040 // When objects of class type are direct-initialized (8.5), or
3041 // copy-initialized from an expression of the same or a
3042 // derived class type (8.5), overload resolution selects the
3043 // constructor. [...] For copy-initialization, the candidate
3044 // functions are all the converting constructors (12.3.1) of
3045 // that class. The argument list is the expression-list within
3046 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003047 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003048 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003049 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003050 ConstructorsOnly = true;
3051
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003052 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003053 // RequireCompleteType may have returned true due to some invalid decl
3054 // during template instantiation, but ToType may be complete enough now
3055 // to try to recover.
3056 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003057 // We're not going to find any constructors.
3058 } else if (CXXRecordDecl *ToRecordDecl
3059 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003060
3061 Expr **Args = &From;
3062 unsigned NumArgs = 1;
3063 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003064 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003065 // But first, see if there is an init-list-contructor that will work.
3066 OverloadingResult Result = IsInitializerListConstructorConversion(
3067 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3068 if (Result != OR_No_Viable_Function)
3069 return Result;
3070 // Never mind.
3071 CandidateSet.clear();
3072
3073 // If we're list-initializing, we pass the individual elements as
3074 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003075 Args = InitList->getInits();
3076 NumArgs = InitList->getNumInits();
3077 ListInitializing = true;
3078 }
3079
David Blaikie3bc93e32012-12-19 00:45:41 +00003080 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3081 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003082 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003083 NamedDecl *D = *Con;
3084 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3085
Douglas Gregordec06662009-08-21 18:42:58 +00003086 // Find the constructor (which may be a template).
3087 CXXConstructorDecl *Constructor = 0;
3088 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003089 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003090 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003091 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003092 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3093 else
John McCall9aa472c2010-03-19 07:35:19 +00003094 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003095
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003096 bool Usable = !Constructor->isInvalidDecl();
3097 if (ListInitializing)
3098 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3099 else
3100 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3101 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003102 bool SuppressUserConversions = !ConstructorsOnly;
3103 if (SuppressUserConversions && ListInitializing) {
3104 SuppressUserConversions = false;
3105 if (NumArgs == 1) {
3106 // If the first argument is (a reference to) the target type,
3107 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003108 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3109 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003110 }
3111 }
Douglas Gregordec06662009-08-21 18:42:58 +00003112 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003113 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3114 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003115 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003116 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003117 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003118 // Allow one user-defined conversion when user specifies a
3119 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003120 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003121 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003122 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003123 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003124 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003125 }
3126 }
3127
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003128 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003129 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003130 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003131 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003132 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003133 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003134 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003135 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3136 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003137 std::pair<CXXRecordDecl::conversion_iterator,
3138 CXXRecordDecl::conversion_iterator>
3139 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3140 for (CXXRecordDecl::conversion_iterator
3141 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003142 DeclAccessPair FoundDecl = I.getPair();
3143 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003144 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3145 if (isa<UsingShadowDecl>(D))
3146 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3147
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003148 CXXConversionDecl *Conv;
3149 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003150 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3151 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003152 else
John McCall32daa422010-03-31 01:36:47 +00003153 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003154
3155 if (AllowExplicit || !Conv->isExplicit()) {
3156 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003157 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3158 ActingContext, From, ToType,
3159 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003160 else
John McCall120d63c2010-08-24 20:38:10 +00003161 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3162 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003163 }
3164 }
3165 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003166 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003167
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003168 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3169
Douglas Gregor60d62c22008-10-31 16:23:19 +00003170 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003171 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003172 case OR_Success:
3173 // Record the standard conversion we used and the conversion function.
3174 if (CXXConstructorDecl *Constructor
3175 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3176 // C++ [over.ics.user]p1:
3177 // If the user-defined conversion is specified by a
3178 // constructor (12.3.1), the initial standard conversion
3179 // sequence converts the source type to the type required by
3180 // the argument of the constructor.
3181 //
3182 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003183 if (isa<InitListExpr>(From)) {
3184 // Initializer lists don't have conversions as such.
3185 User.Before.setAsIdentityConversion();
3186 } else {
3187 if (Best->Conversions[0].isEllipsis())
3188 User.EllipsisConversion = true;
3189 else {
3190 User.Before = Best->Conversions[0].Standard;
3191 User.EllipsisConversion = false;
3192 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003193 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003194 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003195 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003196 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003197 User.After.setAsIdentityConversion();
3198 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3199 User.After.setAllToTypes(ToType);
3200 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003201 }
3202 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003203 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3204 // C++ [over.ics.user]p1:
3205 //
3206 // [...] If the user-defined conversion is specified by a
3207 // conversion function (12.3.2), the initial standard
3208 // conversion sequence converts the source type to the
3209 // implicit object parameter of the conversion function.
3210 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003211 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003212 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003213 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003214 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003215
John McCall120d63c2010-08-24 20:38:10 +00003216 // C++ [over.ics.user]p2:
3217 // The second standard conversion sequence converts the
3218 // result of the user-defined conversion to the target type
3219 // for the sequence. Since an implicit conversion sequence
3220 // is an initialization, the special rules for
3221 // initialization by user-defined conversion apply when
3222 // selecting the best user-defined conversion for a
3223 // user-defined conversion sequence (see 13.3.3 and
3224 // 13.3.3.1).
3225 User.After = Best->FinalConversion;
3226 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003227 }
David Blaikie7530c032012-01-17 06:56:22 +00003228 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003229
John McCall120d63c2010-08-24 20:38:10 +00003230 case OR_No_Viable_Function:
3231 return OR_No_Viable_Function;
3232 case OR_Deleted:
3233 // No conversion here! We're done.
3234 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235
John McCall120d63c2010-08-24 20:38:10 +00003236 case OR_Ambiguous:
3237 return OR_Ambiguous;
3238 }
3239
David Blaikie7530c032012-01-17 06:56:22 +00003240 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003241}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003242
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003243bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003244Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003245 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003246 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003247 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003248 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003249 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003250 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003251 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003252 diag::err_typecheck_ambiguous_condition)
3253 << From->getType() << ToType << From->getSourceRange();
3254 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003255 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003256 diag::err_typecheck_nonviable_condition)
3257 << From->getType() << ToType << From->getSourceRange();
3258 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003259 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003260 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003261 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003262}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003263
Douglas Gregorb734e242012-02-22 17:32:19 +00003264/// \brief Compare the user-defined conversion functions or constructors
3265/// of two user-defined conversion sequences to determine whether any ordering
3266/// is possible.
3267static ImplicitConversionSequence::CompareKind
3268compareConversionFunctions(Sema &S,
3269 FunctionDecl *Function1,
3270 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003271 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003272 return ImplicitConversionSequence::Indistinguishable;
3273
3274 // Objective-C++:
3275 // If both conversion functions are implicitly-declared conversions from
3276 // a lambda closure type to a function pointer and a block pointer,
3277 // respectively, always prefer the conversion to a function pointer,
3278 // because the function pointer is more lightweight and is more likely
3279 // to keep code working.
3280 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3281 if (!Conv1)
3282 return ImplicitConversionSequence::Indistinguishable;
3283
3284 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3285 if (!Conv2)
3286 return ImplicitConversionSequence::Indistinguishable;
3287
3288 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3289 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3290 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3291 if (Block1 != Block2)
3292 return Block1? ImplicitConversionSequence::Worse
3293 : ImplicitConversionSequence::Better;
3294 }
3295
3296 return ImplicitConversionSequence::Indistinguishable;
3297}
3298
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003299/// CompareImplicitConversionSequences - Compare two implicit
3300/// conversion sequences to determine whether one is better than the
3301/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003302static ImplicitConversionSequence::CompareKind
3303CompareImplicitConversionSequences(Sema &S,
3304 const ImplicitConversionSequence& ICS1,
3305 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003306{
3307 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3308 // conversion sequences (as defined in 13.3.3.1)
3309 // -- a standard conversion sequence (13.3.3.1.1) is a better
3310 // conversion sequence than a user-defined conversion sequence or
3311 // an ellipsis conversion sequence, and
3312 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3313 // conversion sequence than an ellipsis conversion sequence
3314 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003315 //
John McCall1d318332010-01-12 00:44:57 +00003316 // C++0x [over.best.ics]p10:
3317 // For the purpose of ranking implicit conversion sequences as
3318 // described in 13.3.3.2, the ambiguous conversion sequence is
3319 // treated as a user-defined sequence that is indistinguishable
3320 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003321 if (ICS1.getKindRank() < ICS2.getKindRank())
3322 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003323 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003324 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003325
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003326 // The following checks require both conversion sequences to be of
3327 // the same kind.
3328 if (ICS1.getKind() != ICS2.getKind())
3329 return ImplicitConversionSequence::Indistinguishable;
3330
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003331 ImplicitConversionSequence::CompareKind Result =
3332 ImplicitConversionSequence::Indistinguishable;
3333
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003334 // Two implicit conversion sequences of the same form are
3335 // indistinguishable conversion sequences unless one of the
3336 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003337 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003338 Result = CompareStandardConversionSequences(S,
3339 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003340 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003341 // User-defined conversion sequence U1 is a better conversion
3342 // sequence than another user-defined conversion sequence U2 if
3343 // they contain the same user-defined conversion function or
3344 // constructor and if the second standard conversion sequence of
3345 // U1 is better than the second standard conversion sequence of
3346 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003347 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003348 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003349 Result = CompareStandardConversionSequences(S,
3350 ICS1.UserDefined.After,
3351 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003352 else
3353 Result = compareConversionFunctions(S,
3354 ICS1.UserDefined.ConversionFunction,
3355 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003356 }
3357
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003358 // List-initialization sequence L1 is a better conversion sequence than
3359 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3360 // for some X and L2 does not.
3361 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003362 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003363 ICS1.isListInitializationSequence() &&
3364 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003365 if (ICS1.isStdInitializerListElement() &&
3366 !ICS2.isStdInitializerListElement())
3367 return ImplicitConversionSequence::Better;
3368 if (!ICS1.isStdInitializerListElement() &&
3369 ICS2.isStdInitializerListElement())
3370 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003371 }
3372
3373 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003374}
3375
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003376static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3377 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3378 Qualifiers Quals;
3379 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003381 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003383 return Context.hasSameUnqualifiedType(T1, T2);
3384}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
Douglas Gregorad323a82010-01-27 03:51:04 +00003386// Per 13.3.3.2p3, compare the given standard conversion sequences to
3387// determine if one is a proper subset of the other.
3388static ImplicitConversionSequence::CompareKind
3389compareStandardConversionSubsets(ASTContext &Context,
3390 const StandardConversionSequence& SCS1,
3391 const StandardConversionSequence& SCS2) {
3392 ImplicitConversionSequence::CompareKind Result
3393 = ImplicitConversionSequence::Indistinguishable;
3394
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003395 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003396 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003397 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3398 return ImplicitConversionSequence::Better;
3399 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3400 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401
Douglas Gregorad323a82010-01-27 03:51:04 +00003402 if (SCS1.Second != SCS2.Second) {
3403 if (SCS1.Second == ICK_Identity)
3404 Result = ImplicitConversionSequence::Better;
3405 else if (SCS2.Second == ICK_Identity)
3406 Result = ImplicitConversionSequence::Worse;
3407 else
3408 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003409 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003410 return ImplicitConversionSequence::Indistinguishable;
3411
3412 if (SCS1.Third == SCS2.Third) {
3413 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3414 : ImplicitConversionSequence::Indistinguishable;
3415 }
3416
3417 if (SCS1.Third == ICK_Identity)
3418 return Result == ImplicitConversionSequence::Worse
3419 ? ImplicitConversionSequence::Indistinguishable
3420 : ImplicitConversionSequence::Better;
3421
3422 if (SCS2.Third == ICK_Identity)
3423 return Result == ImplicitConversionSequence::Better
3424 ? ImplicitConversionSequence::Indistinguishable
3425 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003426
Douglas Gregorad323a82010-01-27 03:51:04 +00003427 return ImplicitConversionSequence::Indistinguishable;
3428}
3429
Douglas Gregor440a4832011-01-26 14:52:12 +00003430/// \brief Determine whether one of the given reference bindings is better
3431/// than the other based on what kind of bindings they are.
3432static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3433 const StandardConversionSequence &SCS2) {
3434 // C++0x [over.ics.rank]p3b4:
3435 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3436 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003437 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003438 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003439 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003440 // reference*.
3441 //
3442 // FIXME: Rvalue references. We're going rogue with the above edits,
3443 // because the semantics in the current C++0x working paper (N3225 at the
3444 // time of this writing) break the standard definition of std::forward
3445 // and std::reference_wrapper when dealing with references to functions.
3446 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003447 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3448 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3449 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003450
Douglas Gregor440a4832011-01-26 14:52:12 +00003451 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3452 SCS2.IsLvalueReference) ||
3453 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3454 !SCS2.IsLvalueReference);
3455}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003456
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003457/// CompareStandardConversionSequences - Compare two standard
3458/// conversion sequences to determine whether one is better than the
3459/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003460static ImplicitConversionSequence::CompareKind
3461CompareStandardConversionSequences(Sema &S,
3462 const StandardConversionSequence& SCS1,
3463 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003464{
3465 // Standard conversion sequence S1 is a better conversion sequence
3466 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3467
3468 // -- S1 is a proper subsequence of S2 (comparing the conversion
3469 // sequences in the canonical form defined by 13.3.3.1.1,
3470 // excluding any Lvalue Transformation; the identity conversion
3471 // sequence is considered to be a subsequence of any
3472 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003473 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003474 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003475 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003476
3477 // -- the rank of S1 is better than the rank of S2 (by the rules
3478 // defined below), or, if not that,
3479 ImplicitConversionRank Rank1 = SCS1.getRank();
3480 ImplicitConversionRank Rank2 = SCS2.getRank();
3481 if (Rank1 < Rank2)
3482 return ImplicitConversionSequence::Better;
3483 else if (Rank2 < Rank1)
3484 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003485
Douglas Gregor57373262008-10-22 14:17:15 +00003486 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3487 // are indistinguishable unless one of the following rules
3488 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Douglas Gregor57373262008-10-22 14:17:15 +00003490 // A conversion that is not a conversion of a pointer, or
3491 // pointer to member, to bool is better than another conversion
3492 // that is such a conversion.
3493 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3494 return SCS2.isPointerConversionToBool()
3495 ? ImplicitConversionSequence::Better
3496 : ImplicitConversionSequence::Worse;
3497
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003498 // C++ [over.ics.rank]p4b2:
3499 //
3500 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003501 // conversion of B* to A* is better than conversion of B* to
3502 // void*, and conversion of A* to void* is better than conversion
3503 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003504 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003505 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003506 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003507 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003508 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3509 // Exactly one of the conversion sequences is a conversion to
3510 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003511 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3512 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003513 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3514 // Neither conversion sequence converts to a void pointer; compare
3515 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003516 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003517 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003518 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003519 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3520 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003521 // Both conversion sequences are conversions to void
3522 // pointers. Compare the source types to determine if there's an
3523 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003524 QualType FromType1 = SCS1.getFromType();
3525 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003526
3527 // Adjust the types we're converting from via the array-to-pointer
3528 // conversion, if we need to.
3529 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003530 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003531 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003532 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003533
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003534 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3535 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003536
John McCall120d63c2010-08-24 20:38:10 +00003537 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003538 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003539 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003540 return ImplicitConversionSequence::Worse;
3541
3542 // Objective-C++: If one interface is more specific than the
3543 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003544 const ObjCObjectPointerType* FromObjCPtr1
3545 = FromType1->getAs<ObjCObjectPointerType>();
3546 const ObjCObjectPointerType* FromObjCPtr2
3547 = FromType2->getAs<ObjCObjectPointerType>();
3548 if (FromObjCPtr1 && FromObjCPtr2) {
3549 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3550 FromObjCPtr2);
3551 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3552 FromObjCPtr1);
3553 if (AssignLeft != AssignRight) {
3554 return AssignLeft? ImplicitConversionSequence::Better
3555 : ImplicitConversionSequence::Worse;
3556 }
Douglas Gregor01919692009-12-13 21:37:05 +00003557 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003558 }
Douglas Gregor57373262008-10-22 14:17:15 +00003559
3560 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3561 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003562 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003563 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003564 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003565
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003566 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003567 // Check for a better reference binding based on the kind of bindings.
3568 if (isBetterReferenceBindingKind(SCS1, SCS2))
3569 return ImplicitConversionSequence::Better;
3570 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3571 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003573 // C++ [over.ics.rank]p3b4:
3574 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3575 // which the references refer are the same type except for
3576 // top-level cv-qualifiers, and the type to which the reference
3577 // initialized by S2 refers is more cv-qualified than the type
3578 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003579 QualType T1 = SCS1.getToType(2);
3580 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003581 T1 = S.Context.getCanonicalType(T1);
3582 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003583 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003584 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3585 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003586 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003587 // Objective-C++ ARC: If the references refer to objects with different
3588 // lifetimes, prefer bindings that don't change lifetime.
3589 if (SCS1.ObjCLifetimeConversionBinding !=
3590 SCS2.ObjCLifetimeConversionBinding) {
3591 return SCS1.ObjCLifetimeConversionBinding
3592 ? ImplicitConversionSequence::Worse
3593 : ImplicitConversionSequence::Better;
3594 }
3595
Chandler Carruth6df868e2010-12-12 08:17:55 +00003596 // If the type is an array type, promote the element qualifiers to the
3597 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003598 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003599 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003600 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003601 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003602 if (T2.isMoreQualifiedThan(T1))
3603 return ImplicitConversionSequence::Better;
3604 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003605 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003606 }
3607 }
Douglas Gregor57373262008-10-22 14:17:15 +00003608
Francois Pichet1c98d622011-09-18 21:37:37 +00003609 // In Microsoft mode, prefer an integral conversion to a
3610 // floating-to-integral conversion if the integral conversion
3611 // is between types of the same size.
3612 // For example:
3613 // void f(float);
3614 // void f(int);
3615 // int main {
3616 // long a;
3617 // f(a);
3618 // }
3619 // Here, MSVC will call f(int) instead of generating a compile error
3620 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003621 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003622 SCS1.Second == ICK_Integral_Conversion &&
3623 SCS2.Second == ICK_Floating_Integral &&
3624 S.Context.getTypeSize(SCS1.getFromType()) ==
3625 S.Context.getTypeSize(SCS1.getToType(2)))
3626 return ImplicitConversionSequence::Better;
3627
Douglas Gregor57373262008-10-22 14:17:15 +00003628 return ImplicitConversionSequence::Indistinguishable;
3629}
3630
3631/// CompareQualificationConversions - Compares two standard conversion
3632/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003633/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3634ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003635CompareQualificationConversions(Sema &S,
3636 const StandardConversionSequence& SCS1,
3637 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003638 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003639 // -- S1 and S2 differ only in their qualification conversion and
3640 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3641 // cv-qualification signature of type T1 is a proper subset of
3642 // the cv-qualification signature of type T2, and S1 is not the
3643 // deprecated string literal array-to-pointer conversion (4.2).
3644 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3645 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3646 return ImplicitConversionSequence::Indistinguishable;
3647
3648 // FIXME: the example in the standard doesn't use a qualification
3649 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003650 QualType T1 = SCS1.getToType(2);
3651 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003652 T1 = S.Context.getCanonicalType(T1);
3653 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003654 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003655 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3656 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003657
3658 // If the types are the same, we won't learn anything by unwrapped
3659 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003660 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003661 return ImplicitConversionSequence::Indistinguishable;
3662
Chandler Carruth28e318c2009-12-29 07:16:59 +00003663 // If the type is an array type, promote the element qualifiers to the type
3664 // for comparison.
3665 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003666 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003667 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003668 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003669
Mike Stump1eb44332009-09-09 15:08:12 +00003670 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003671 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003672
3673 // Objective-C++ ARC:
3674 // Prefer qualification conversions not involving a change in lifetime
3675 // to qualification conversions that do not change lifetime.
3676 if (SCS1.QualificationIncludesObjCLifetime !=
3677 SCS2.QualificationIncludesObjCLifetime) {
3678 Result = SCS1.QualificationIncludesObjCLifetime
3679 ? ImplicitConversionSequence::Worse
3680 : ImplicitConversionSequence::Better;
3681 }
3682
John McCall120d63c2010-08-24 20:38:10 +00003683 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003684 // Within each iteration of the loop, we check the qualifiers to
3685 // determine if this still looks like a qualification
3686 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003687 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003688 // until there are no more pointers or pointers-to-members left
3689 // to unwrap. This essentially mimics what
3690 // IsQualificationConversion does, but here we're checking for a
3691 // strict subset of qualifiers.
3692 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3693 // The qualifiers are the same, so this doesn't tell us anything
3694 // about how the sequences rank.
3695 ;
3696 else if (T2.isMoreQualifiedThan(T1)) {
3697 // T1 has fewer qualifiers, so it could be the better sequence.
3698 if (Result == ImplicitConversionSequence::Worse)
3699 // Neither has qualifiers that are a subset of the other's
3700 // qualifiers.
3701 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Douglas Gregor57373262008-10-22 14:17:15 +00003703 Result = ImplicitConversionSequence::Better;
3704 } else if (T1.isMoreQualifiedThan(T2)) {
3705 // T2 has fewer qualifiers, so it could be the better sequence.
3706 if (Result == ImplicitConversionSequence::Better)
3707 // Neither has qualifiers that are a subset of the other's
3708 // qualifiers.
3709 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Douglas Gregor57373262008-10-22 14:17:15 +00003711 Result = ImplicitConversionSequence::Worse;
3712 } else {
3713 // Qualifiers are disjoint.
3714 return ImplicitConversionSequence::Indistinguishable;
3715 }
3716
3717 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003718 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003719 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003720 }
3721
Douglas Gregor57373262008-10-22 14:17:15 +00003722 // Check that the winning standard conversion sequence isn't using
3723 // the deprecated string literal array to pointer conversion.
3724 switch (Result) {
3725 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003726 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003727 Result = ImplicitConversionSequence::Indistinguishable;
3728 break;
3729
3730 case ImplicitConversionSequence::Indistinguishable:
3731 break;
3732
3733 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003734 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003735 Result = ImplicitConversionSequence::Indistinguishable;
3736 break;
3737 }
3738
3739 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003740}
3741
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003742/// CompareDerivedToBaseConversions - Compares two standard conversion
3743/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003744/// various kinds of derived-to-base conversions (C++
3745/// [over.ics.rank]p4b3). As part of these checks, we also look at
3746/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003747ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003748CompareDerivedToBaseConversions(Sema &S,
3749 const StandardConversionSequence& SCS1,
3750 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003751 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003752 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003753 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003754 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003755
3756 // Adjust the types we're converting from via the array-to-pointer
3757 // conversion, if we need to.
3758 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003759 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003760 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003761 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003762
3763 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003764 FromType1 = S.Context.getCanonicalType(FromType1);
3765 ToType1 = S.Context.getCanonicalType(ToType1);
3766 FromType2 = S.Context.getCanonicalType(FromType2);
3767 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003768
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003769 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003770 //
3771 // If class B is derived directly or indirectly from class A and
3772 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003773 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003774 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003775 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003776 SCS2.Second == ICK_Pointer_Conversion &&
3777 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3778 FromType1->isPointerType() && FromType2->isPointerType() &&
3779 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003780 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003781 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003782 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003783 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003784 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003785 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003786 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003787 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003788
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003789 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003790 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003791 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003792 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003793 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003794 return ImplicitConversionSequence::Worse;
3795 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003796
3797 // -- conversion of B* to A* is better than conversion of C* to A*,
3798 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003799 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003800 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003801 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003802 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003803 }
3804 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3805 SCS2.Second == ICK_Pointer_Conversion) {
3806 const ObjCObjectPointerType *FromPtr1
3807 = FromType1->getAs<ObjCObjectPointerType>();
3808 const ObjCObjectPointerType *FromPtr2
3809 = FromType2->getAs<ObjCObjectPointerType>();
3810 const ObjCObjectPointerType *ToPtr1
3811 = ToType1->getAs<ObjCObjectPointerType>();
3812 const ObjCObjectPointerType *ToPtr2
3813 = ToType2->getAs<ObjCObjectPointerType>();
3814
3815 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3816 // Apply the same conversion ranking rules for Objective-C pointer types
3817 // that we do for C++ pointers to class types. However, we employ the
3818 // Objective-C pseudo-subtyping relationship used for assignment of
3819 // Objective-C pointer types.
3820 bool FromAssignLeft
3821 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3822 bool FromAssignRight
3823 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3824 bool ToAssignLeft
3825 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3826 bool ToAssignRight
3827 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3828
3829 // A conversion to an a non-id object pointer type or qualified 'id'
3830 // type is better than a conversion to 'id'.
3831 if (ToPtr1->isObjCIdType() &&
3832 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3833 return ImplicitConversionSequence::Worse;
3834 if (ToPtr2->isObjCIdType() &&
3835 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3836 return ImplicitConversionSequence::Better;
3837
3838 // A conversion to a non-id object pointer type is better than a
3839 // conversion to a qualified 'id' type
3840 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3841 return ImplicitConversionSequence::Worse;
3842 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3843 return ImplicitConversionSequence::Better;
3844
3845 // A conversion to an a non-Class object pointer type or qualified 'Class'
3846 // type is better than a conversion to 'Class'.
3847 if (ToPtr1->isObjCClassType() &&
3848 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3849 return ImplicitConversionSequence::Worse;
3850 if (ToPtr2->isObjCClassType() &&
3851 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3852 return ImplicitConversionSequence::Better;
3853
3854 // A conversion to a non-Class object pointer type is better than a
3855 // conversion to a qualified 'Class' type.
3856 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3857 return ImplicitConversionSequence::Worse;
3858 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3859 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Douglas Gregor395cc372011-01-31 18:51:41 +00003861 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3862 if (S.Context.hasSameType(FromType1, FromType2) &&
3863 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3864 (ToAssignLeft != ToAssignRight))
3865 return ToAssignLeft? ImplicitConversionSequence::Worse
3866 : ImplicitConversionSequence::Better;
3867
3868 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3869 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3870 (FromAssignLeft != FromAssignRight))
3871 return FromAssignLeft? ImplicitConversionSequence::Better
3872 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003873 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003874 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003875
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003876 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003877 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3878 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3879 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003881 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003882 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003883 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003885 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003886 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003887 ToType2->getAs<MemberPointerType>();
3888 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3889 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3890 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3891 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3892 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3893 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3894 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3895 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003896 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003897 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003898 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003899 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003900 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003901 return ImplicitConversionSequence::Better;
3902 }
3903 // conversion of B::* to C::* is better than conversion of A::* to C::*
3904 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003905 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003906 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003907 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003908 return ImplicitConversionSequence::Worse;
3909 }
3910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003912 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003913 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003914 // -- binding of an expression of type C to a reference of type
3915 // B& is better than binding an expression of type C to a
3916 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003917 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3918 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3919 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003920 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003921 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003922 return ImplicitConversionSequence::Worse;
3923 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003924
Douglas Gregor225c41e2008-11-03 19:09:14 +00003925 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003926 // -- binding of an expression of type B to a reference of type
3927 // A& is better than binding an expression of type C to a
3928 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003929 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3930 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3931 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003932 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003933 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003934 return ImplicitConversionSequence::Worse;
3935 }
3936 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003937
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003938 return ImplicitConversionSequence::Indistinguishable;
3939}
3940
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003941/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3942/// C++ class.
3943static bool isTypeValid(QualType T) {
3944 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3945 return !Record->isInvalidDecl();
3946
3947 return true;
3948}
3949
Douglas Gregorabe183d2010-04-13 16:31:36 +00003950/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3951/// determine whether they are reference-related,
3952/// reference-compatible, reference-compatible with added
3953/// qualification, or incompatible, for use in C++ initialization by
3954/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3955/// type, and the first type (T1) is the pointee type of the reference
3956/// type being initialized.
3957Sema::ReferenceCompareResult
3958Sema::CompareReferenceRelationship(SourceLocation Loc,
3959 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003960 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003961 bool &ObjCConversion,
3962 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003963 assert(!OrigT1->isReferenceType() &&
3964 "T1 must be the pointee type of the reference type");
3965 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3966
3967 QualType T1 = Context.getCanonicalType(OrigT1);
3968 QualType T2 = Context.getCanonicalType(OrigT2);
3969 Qualifiers T1Quals, T2Quals;
3970 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3971 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3972
3973 // C++ [dcl.init.ref]p4:
3974 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3975 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3976 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003977 DerivedToBase = false;
3978 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003979 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003980 if (UnqualT1 == UnqualT2) {
3981 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003982 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003983 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3984 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003985 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003986 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3987 UnqualT2->isObjCObjectOrInterfaceType() &&
3988 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3989 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003990 else
3991 return Ref_Incompatible;
3992
3993 // At this point, we know that T1 and T2 are reference-related (at
3994 // least).
3995
3996 // If the type is an array type, promote the element qualifiers to the type
3997 // for comparison.
3998 if (isa<ArrayType>(T1) && T1Quals)
3999 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4000 if (isa<ArrayType>(T2) && T2Quals)
4001 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4002
4003 // C++ [dcl.init.ref]p4:
4004 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4005 // reference-related to T2 and cv1 is the same cv-qualification
4006 // as, or greater cv-qualification than, cv2. For purposes of
4007 // overload resolution, cases for which cv1 is greater
4008 // cv-qualification than cv2 are identified as
4009 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004010 //
4011 // Note that we also require equivalence of Objective-C GC and address-space
4012 // qualifiers when performing these computations, so that e.g., an int in
4013 // address space 1 is not reference-compatible with an int in address
4014 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00004015 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4016 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4017 T1Quals.removeObjCLifetime();
4018 T2Quals.removeObjCLifetime();
4019 ObjCLifetimeConversion = true;
4020 }
4021
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004022 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004023 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004024 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004025 return Ref_Compatible_With_Added_Qualification;
4026 else
4027 return Ref_Related;
4028}
4029
Douglas Gregor604eb652010-08-11 02:15:33 +00004030/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004031/// with DeclType. Return true if something definite is found.
4032static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004033FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4034 QualType DeclType, SourceLocation DeclLoc,
4035 Expr *Init, QualType T2, bool AllowRvalues,
4036 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004037 assert(T2->isRecordType() && "Can only find conversions of record types.");
4038 CXXRecordDecl *T2RecordDecl
4039 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4040
4041 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004042 std::pair<CXXRecordDecl::conversion_iterator,
4043 CXXRecordDecl::conversion_iterator>
4044 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4045 for (CXXRecordDecl::conversion_iterator
4046 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004047 NamedDecl *D = *I;
4048 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4049 if (isa<UsingShadowDecl>(D))
4050 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4051
4052 FunctionTemplateDecl *ConvTemplate
4053 = dyn_cast<FunctionTemplateDecl>(D);
4054 CXXConversionDecl *Conv;
4055 if (ConvTemplate)
4056 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4057 else
4058 Conv = cast<CXXConversionDecl>(D);
4059
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004060 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004061 // explicit conversions, skip it.
4062 if (!AllowExplicit && Conv->isExplicit())
4063 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064
Douglas Gregor604eb652010-08-11 02:15:33 +00004065 if (AllowRvalues) {
4066 bool DerivedToBase = false;
4067 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004068 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004069
4070 // If we are initializing an rvalue reference, don't permit conversion
4071 // functions that return lvalues.
4072 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4073 const ReferenceType *RefType
4074 = Conv->getConversionType()->getAs<LValueReferenceType>();
4075 if (RefType && !RefType->getPointeeType()->isFunctionType())
4076 continue;
4077 }
4078
Douglas Gregor604eb652010-08-11 02:15:33 +00004079 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004080 S.CompareReferenceRelationship(
4081 DeclLoc,
4082 Conv->getConversionType().getNonReferenceType()
4083 .getUnqualifiedType(),
4084 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004085 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004086 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004087 continue;
4088 } else {
4089 // If the conversion function doesn't return a reference type,
4090 // it can't be considered for this conversion. An rvalue reference
4091 // is only acceptable if its referencee is a function type.
4092
4093 const ReferenceType *RefType =
4094 Conv->getConversionType()->getAs<ReferenceType>();
4095 if (!RefType ||
4096 (!RefType->isLValueReferenceType() &&
4097 !RefType->getPointeeType()->isFunctionType()))
4098 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004099 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004100
Douglas Gregor604eb652010-08-11 02:15:33 +00004101 if (ConvTemplate)
4102 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004103 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004104 else
4105 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004106 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004107 }
4108
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004109 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4110
Sebastian Redl4680bf22010-06-30 18:13:39 +00004111 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004112 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004113 case OR_Success:
4114 // C++ [over.ics.ref]p1:
4115 //
4116 // [...] If the parameter binds directly to the result of
4117 // applying a conversion function to the argument
4118 // expression, the implicit conversion sequence is a
4119 // user-defined conversion sequence (13.3.3.1.2), with the
4120 // second standard conversion sequence either an identity
4121 // conversion or, if the conversion function returns an
4122 // entity of a type that is a derived class of the parameter
4123 // type, a derived-to-base Conversion.
4124 if (!Best->FinalConversion.DirectBinding)
4125 return false;
4126
4127 ICS.setUserDefined();
4128 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4129 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004130 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004131 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004132 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004133 ICS.UserDefined.EllipsisConversion = false;
4134 assert(ICS.UserDefined.After.ReferenceBinding &&
4135 ICS.UserDefined.After.DirectBinding &&
4136 "Expected a direct reference binding!");
4137 return true;
4138
4139 case OR_Ambiguous:
4140 ICS.setAmbiguous();
4141 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4142 Cand != CandidateSet.end(); ++Cand)
4143 if (Cand->Viable)
4144 ICS.Ambiguous.addConversion(Cand->Function);
4145 return true;
4146
4147 case OR_No_Viable_Function:
4148 case OR_Deleted:
4149 // There was no suitable conversion, or we found a deleted
4150 // conversion; continue with other checks.
4151 return false;
4152 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004153
David Blaikie7530c032012-01-17 06:56:22 +00004154 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004155}
4156
Douglas Gregorabe183d2010-04-13 16:31:36 +00004157/// \brief Compute an implicit conversion sequence for reference
4158/// initialization.
4159static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004160TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004161 SourceLocation DeclLoc,
4162 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004163 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004164 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4165
4166 // Most paths end in a failed conversion.
4167 ImplicitConversionSequence ICS;
4168 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4169
4170 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4171 QualType T2 = Init->getType();
4172
4173 // If the initializer is the address of an overloaded function, try
4174 // to resolve the overloaded function. If all goes well, T2 is the
4175 // type of the resulting function.
4176 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4177 DeclAccessPair Found;
4178 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4179 false, Found))
4180 T2 = Fn->getType();
4181 }
4182
4183 // Compute some basic properties of the types and the initializer.
4184 bool isRValRef = DeclType->isRValueReferenceType();
4185 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004186 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004187 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004188 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004189 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004190 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004191 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004192
Douglas Gregorabe183d2010-04-13 16:31:36 +00004193
Sebastian Redl4680bf22010-06-30 18:13:39 +00004194 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004195 // A reference to type "cv1 T1" is initialized by an expression
4196 // of type "cv2 T2" as follows:
4197
Sebastian Redl4680bf22010-06-30 18:13:39 +00004198 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004199 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004200 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4201 // reference-compatible with "cv2 T2," or
4202 //
4203 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4204 if (InitCategory.isLValue() &&
4205 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004206 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004207 // When a parameter of reference type binds directly (8.5.3)
4208 // to an argument expression, the implicit conversion sequence
4209 // is the identity conversion, unless the argument expression
4210 // has a type that is a derived class of the parameter type,
4211 // in which case the implicit conversion sequence is a
4212 // derived-to-base Conversion (13.3.3.1).
4213 ICS.setStandard();
4214 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004215 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4216 : ObjCConversion? ICK_Compatible_Conversion
4217 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004218 ICS.Standard.Third = ICK_Identity;
4219 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4220 ICS.Standard.setToType(0, T2);
4221 ICS.Standard.setToType(1, T1);
4222 ICS.Standard.setToType(2, T1);
4223 ICS.Standard.ReferenceBinding = true;
4224 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004225 ICS.Standard.IsLvalueReference = !isRValRef;
4226 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4227 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004228 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004229 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004230 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004231
Sebastian Redl4680bf22010-06-30 18:13:39 +00004232 // Nothing more to do: the inaccessibility/ambiguity check for
4233 // derived-to-base conversions is suppressed when we're
4234 // computing the implicit conversion sequence (C++
4235 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004236 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004237 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004238
Sebastian Redl4680bf22010-06-30 18:13:39 +00004239 // -- has a class type (i.e., T2 is a class type), where T1 is
4240 // not reference-related to T2, and can be implicitly
4241 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4242 // is reference-compatible with "cv3 T3" 92) (this
4243 // conversion is selected by enumerating the applicable
4244 // conversion functions (13.3.1.6) and choosing the best
4245 // one through overload resolution (13.3)),
4246 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004247 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004248 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004249 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4250 Init, T2, /*AllowRvalues=*/false,
4251 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004252 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004253 }
4254 }
4255
Sebastian Redl4680bf22010-06-30 18:13:39 +00004256 // -- Otherwise, the reference shall be an lvalue reference to a
4257 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004258 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004259 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004260 // We actually handle one oddity of C++ [over.ics.ref] at this
4261 // point, which is that, due to p2 (which short-circuits reference
4262 // binding by only attempting a simple conversion for non-direct
4263 // bindings) and p3's strange wording, we allow a const volatile
4264 // reference to bind to an rvalue. Hence the check for the presence
4265 // of "const" rather than checking for "const" being the only
4266 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004267 // This is also the point where rvalue references and lvalue inits no longer
4268 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004269 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004270 return ICS;
4271
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004272 // -- If the initializer expression
4273 //
4274 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004275 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004276 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4277 (InitCategory.isXValue() ||
4278 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4279 (InitCategory.isLValue() && T2->isFunctionType()))) {
4280 ICS.setStandard();
4281 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004282 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004283 : ObjCConversion? ICK_Compatible_Conversion
4284 : ICK_Identity;
4285 ICS.Standard.Third = ICK_Identity;
4286 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4287 ICS.Standard.setToType(0, T2);
4288 ICS.Standard.setToType(1, T1);
4289 ICS.Standard.setToType(2, T1);
4290 ICS.Standard.ReferenceBinding = true;
4291 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4292 // binding unless we're binding to a class prvalue.
4293 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4294 // allow the use of rvalue references in C++98/03 for the benefit of
4295 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004296 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004297 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004298 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004299 ICS.Standard.IsLvalueReference = !isRValRef;
4300 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004302 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004303 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004304 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004307
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004308 // -- has a class type (i.e., T2 is a class type), where T1 is not
4309 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004310 // an xvalue, class prvalue, or function lvalue of type
4311 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004312 // "cv3 T3",
4313 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004315 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004317 // class subobject).
4318 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004320 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4321 Init, T2, /*AllowRvalues=*/true,
4322 AllowExplicit)) {
4323 // In the second case, if the reference is an rvalue reference
4324 // and the second standard conversion sequence of the
4325 // user-defined conversion sequence includes an lvalue-to-rvalue
4326 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004328 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4329 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4330
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004331 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004333
Douglas Gregorabe183d2010-04-13 16:31:36 +00004334 // -- Otherwise, a temporary of type "cv1 T1" is created and
4335 // initialized from the initializer expression using the
4336 // rules for a non-reference copy initialization (8.5). The
4337 // reference is then bound to the temporary. If T1 is
4338 // reference-related to T2, cv1 must be the same
4339 // cv-qualification as, or greater cv-qualification than,
4340 // cv2; otherwise, the program is ill-formed.
4341 if (RefRelationship == Sema::Ref_Related) {
4342 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4343 // we would be reference-compatible or reference-compatible with
4344 // added qualification. But that wasn't the case, so the reference
4345 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004346 //
4347 // Note that we only want to check address spaces and cvr-qualifiers here.
4348 // ObjC GC and lifetime qualifiers aren't important.
4349 Qualifiers T1Quals = T1.getQualifiers();
4350 Qualifiers T2Quals = T2.getQualifiers();
4351 T1Quals.removeObjCGCAttr();
4352 T1Quals.removeObjCLifetime();
4353 T2Quals.removeObjCGCAttr();
4354 T2Quals.removeObjCLifetime();
4355 if (!T1Quals.compatiblyIncludes(T2Quals))
4356 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004357 }
4358
4359 // If at least one of the types is a class type, the types are not
4360 // related, and we aren't allowed any user conversions, the
4361 // reference binding fails. This case is important for breaking
4362 // recursion, since TryImplicitConversion below will attempt to
4363 // create a temporary through the use of a copy constructor.
4364 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4365 (T1->isRecordType() || T2->isRecordType()))
4366 return ICS;
4367
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004368 // If T1 is reference-related to T2 and the reference is an rvalue
4369 // reference, the initializer expression shall not be an lvalue.
4370 if (RefRelationship >= Sema::Ref_Related &&
4371 isRValRef && Init->Classify(S.Context).isLValue())
4372 return ICS;
4373
Douglas Gregorabe183d2010-04-13 16:31:36 +00004374 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004375 // When a parameter of reference type is not bound directly to
4376 // an argument expression, the conversion sequence is the one
4377 // required to convert the argument expression to the
4378 // underlying type of the reference according to
4379 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4380 // to copy-initializing a temporary of the underlying type with
4381 // the argument expression. Any difference in top-level
4382 // cv-qualification is subsumed by the initialization itself
4383 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004384 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4385 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004386 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004387 /*CStyle=*/false,
4388 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004389
4390 // Of course, that's still a reference binding.
4391 if (ICS.isStandard()) {
4392 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004393 ICS.Standard.IsLvalueReference = !isRValRef;
4394 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4395 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004396 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004397 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004398 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004399 // Don't allow rvalue references to bind to lvalues.
4400 if (DeclType->isRValueReferenceType()) {
4401 if (const ReferenceType *RefType
4402 = ICS.UserDefined.ConversionFunction->getResultType()
4403 ->getAs<LValueReferenceType>()) {
4404 if (!RefType->getPointeeType()->isFunctionType()) {
4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4406 DeclType);
4407 return ICS;
4408 }
4409 }
4410 }
4411
Douglas Gregorabe183d2010-04-13 16:31:36 +00004412 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004413 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4414 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4415 ICS.UserDefined.After.BindsToRvalue = true;
4416 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4417 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004418 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004419
Douglas Gregorabe183d2010-04-13 16:31:36 +00004420 return ICS;
4421}
4422
Sebastian Redl5405b812011-10-16 18:19:34 +00004423static ImplicitConversionSequence
4424TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4425 bool SuppressUserConversions,
4426 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004427 bool AllowObjCWritebackConversion,
4428 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004429
4430/// TryListConversion - Try to copy-initialize a value of type ToType from the
4431/// initializer list From.
4432static ImplicitConversionSequence
4433TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4434 bool SuppressUserConversions,
4435 bool InOverloadResolution,
4436 bool AllowObjCWritebackConversion) {
4437 // C++11 [over.ics.list]p1:
4438 // When an argument is an initializer list, it is not an expression and
4439 // special rules apply for converting it to a parameter type.
4440
4441 ImplicitConversionSequence Result;
4442 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004443 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004444
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004445 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004446 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004447 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004448 return Result;
4449
Sebastian Redl5405b812011-10-16 18:19:34 +00004450 // C++11 [over.ics.list]p2:
4451 // If the parameter type is std::initializer_list<X> or "array of X" and
4452 // all the elements can be implicitly converted to X, the implicit
4453 // conversion sequence is the worst conversion necessary to convert an
4454 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004455 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004456 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004457 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004458 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004459 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004460 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004461 if (!X.isNull()) {
4462 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4463 Expr *Init = From->getInit(i);
4464 ImplicitConversionSequence ICS =
4465 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4466 InOverloadResolution,
4467 AllowObjCWritebackConversion);
4468 // If a single element isn't convertible, fail.
4469 if (ICS.isBad()) {
4470 Result = ICS;
4471 break;
4472 }
4473 // Otherwise, look for the worst conversion.
4474 if (Result.isBad() ||
4475 CompareImplicitConversionSequences(S, ICS, Result) ==
4476 ImplicitConversionSequence::Worse)
4477 Result = ICS;
4478 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004479
4480 // For an empty list, we won't have computed any conversion sequence.
4481 // Introduce the identity conversion sequence.
4482 if (From->getNumInits() == 0) {
4483 Result.setStandard();
4484 Result.Standard.setAsIdentityConversion();
4485 Result.Standard.setFromType(ToType);
4486 Result.Standard.setAllToTypes(ToType);
4487 }
4488
Sebastian Redlfe592282012-01-17 22:49:48 +00004489 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004490 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004491 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004492 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004493
4494 // C++11 [over.ics.list]p3:
4495 // Otherwise, if the parameter is a non-aggregate class X and overload
4496 // resolution chooses a single best constructor [...] the implicit
4497 // conversion sequence is a user-defined conversion sequence. If multiple
4498 // constructors are viable but none is better than the others, the
4499 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004500 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4501 // This function can deal with initializer lists.
4502 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4503 /*AllowExplicit=*/false,
4504 InOverloadResolution, /*CStyle=*/false,
4505 AllowObjCWritebackConversion);
4506 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004507 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004508 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004509
4510 // C++11 [over.ics.list]p4:
4511 // Otherwise, if the parameter has an aggregate type which can be
4512 // initialized from the initializer list [...] the implicit conversion
4513 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004514 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004515 // Type is an aggregate, argument is an init list. At this point it comes
4516 // down to checking whether the initialization works.
4517 // FIXME: Find out whether this parameter is consumed or not.
4518 InitializedEntity Entity =
4519 InitializedEntity::InitializeParameter(S.Context, ToType,
4520 /*Consumed=*/false);
4521 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4522 Result.setUserDefined();
4523 Result.UserDefined.Before.setAsIdentityConversion();
4524 // Initializer lists don't have a type.
4525 Result.UserDefined.Before.setFromType(QualType());
4526 Result.UserDefined.Before.setAllToTypes(QualType());
4527
4528 Result.UserDefined.After.setAsIdentityConversion();
4529 Result.UserDefined.After.setFromType(ToType);
4530 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004531 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004532 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004533 return Result;
4534 }
4535
4536 // C++11 [over.ics.list]p5:
4537 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004538 if (ToType->isReferenceType()) {
4539 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4540 // mention initializer lists in any way. So we go by what list-
4541 // initialization would do and try to extrapolate from that.
4542
4543 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4544
4545 // If the initializer list has a single element that is reference-related
4546 // to the parameter type, we initialize the reference from that.
4547 if (From->getNumInits() == 1) {
4548 Expr *Init = From->getInit(0);
4549
4550 QualType T2 = Init->getType();
4551
4552 // If the initializer is the address of an overloaded function, try
4553 // to resolve the overloaded function. If all goes well, T2 is the
4554 // type of the resulting function.
4555 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4556 DeclAccessPair Found;
4557 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4558 Init, ToType, false, Found))
4559 T2 = Fn->getType();
4560 }
4561
4562 // Compute some basic properties of the types and the initializer.
4563 bool dummy1 = false;
4564 bool dummy2 = false;
4565 bool dummy3 = false;
4566 Sema::ReferenceCompareResult RefRelationship
4567 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4568 dummy2, dummy3);
4569
4570 if (RefRelationship >= Sema::Ref_Related)
4571 return TryReferenceInit(S, Init, ToType,
4572 /*FIXME:*/From->getLocStart(),
4573 SuppressUserConversions,
4574 /*AllowExplicit=*/false);
4575 }
4576
4577 // Otherwise, we bind the reference to a temporary created from the
4578 // initializer list.
4579 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4580 InOverloadResolution,
4581 AllowObjCWritebackConversion);
4582 if (Result.isFailure())
4583 return Result;
4584 assert(!Result.isEllipsis() &&
4585 "Sub-initialization cannot result in ellipsis conversion.");
4586
4587 // Can we even bind to a temporary?
4588 if (ToType->isRValueReferenceType() ||
4589 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4590 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4591 Result.UserDefined.After;
4592 SCS.ReferenceBinding = true;
4593 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4594 SCS.BindsToRvalue = true;
4595 SCS.BindsToFunctionLvalue = false;
4596 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4597 SCS.ObjCLifetimeConversionBinding = false;
4598 } else
4599 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4600 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004601 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004602 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004603
4604 // C++11 [over.ics.list]p6:
4605 // Otherwise, if the parameter type is not a class:
4606 if (!ToType->isRecordType()) {
4607 // - if the initializer list has one element, the implicit conversion
4608 // sequence is the one required to convert the element to the
4609 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004610 unsigned NumInits = From->getNumInits();
4611 if (NumInits == 1)
4612 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4613 SuppressUserConversions,
4614 InOverloadResolution,
4615 AllowObjCWritebackConversion);
4616 // - if the initializer list has no elements, the implicit conversion
4617 // sequence is the identity conversion.
4618 else if (NumInits == 0) {
4619 Result.setStandard();
4620 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004621 Result.Standard.setFromType(ToType);
4622 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004623 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004624 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004625 return Result;
4626 }
4627
4628 // C++11 [over.ics.list]p7:
4629 // In all cases other than those enumerated above, no conversion is possible
4630 return Result;
4631}
4632
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004633/// TryCopyInitialization - Try to copy-initialize a value of type
4634/// ToType from the expression From. Return the implicit conversion
4635/// sequence required to pass this argument, which may be a bad
4636/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004637/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004638/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004639static ImplicitConversionSequence
4640TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004641 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004642 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004643 bool AllowObjCWritebackConversion,
4644 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004645 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4646 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4647 InOverloadResolution,AllowObjCWritebackConversion);
4648
Douglas Gregorabe183d2010-04-13 16:31:36 +00004649 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004650 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004651 /*FIXME:*/From->getLocStart(),
4652 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004653 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004654
John McCall120d63c2010-08-24 20:38:10 +00004655 return TryImplicitConversion(S, From, ToType,
4656 SuppressUserConversions,
4657 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004658 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004659 /*CStyle=*/false,
4660 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004661}
4662
Anna Zaksf3546ee2011-07-28 19:46:48 +00004663static bool TryCopyInitialization(const CanQualType FromQTy,
4664 const CanQualType ToQTy,
4665 Sema &S,
4666 SourceLocation Loc,
4667 ExprValueKind FromVK) {
4668 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4669 ImplicitConversionSequence ICS =
4670 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4671
4672 return !ICS.isBad();
4673}
4674
Douglas Gregor96176b32008-11-18 23:14:02 +00004675/// TryObjectArgumentInitialization - Try to initialize the object
4676/// parameter of the given member function (@c Method) from the
4677/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004678static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004679TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004680 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004681 CXXMethodDecl *Method,
4682 CXXRecordDecl *ActingContext) {
4683 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004684 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4685 // const volatile object.
4686 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4687 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004688 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004689
4690 // Set up the conversion sequence as a "bad" conversion, to allow us
4691 // to exit early.
4692 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004693
4694 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004695 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004696 FromType = PT->getPointeeType();
4697
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004698 // When we had a pointer, it's implicitly dereferenced, so we
4699 // better have an lvalue.
4700 assert(FromClassification.isLValue());
4701 }
4702
Anders Carlssona552f7c2009-05-01 18:34:30 +00004703 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004704
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004705 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004706 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004707 // parameter is
4708 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004709 // - "lvalue reference to cv X" for functions declared without a
4710 // ref-qualifier or with the & ref-qualifier
4711 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004712 // ref-qualifier
4713 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004715 // cv-qualification on the member function declaration.
4716 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004718 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004719 // (C++ [over.match.funcs]p5). We perform a simplified version of
4720 // reference binding here, that allows class rvalues to bind to
4721 // non-constant references.
4722
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004723 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004724 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004725 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004726 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004727 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004728 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004729 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004730 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004731 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004732
4733 // Check that we have either the same type or a derived type. It
4734 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004735 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004736 ImplicitConversionKind SecondKind;
4737 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4738 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004739 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004740 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004741 else {
John McCallb1bdc622010-02-25 01:37:24 +00004742 ICS.setBad(BadConversionSequence::unrelated_class,
4743 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004744 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004745 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004746
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004747 // Check the ref-qualifier.
4748 switch (Method->getRefQualifier()) {
4749 case RQ_None:
4750 // Do nothing; we don't care about lvalueness or rvalueness.
4751 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004752
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004753 case RQ_LValue:
4754 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4755 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004756 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004757 ImplicitParamType);
4758 return ICS;
4759 }
4760 break;
4761
4762 case RQ_RValue:
4763 if (!FromClassification.isRValue()) {
4764 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004765 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004766 ImplicitParamType);
4767 return ICS;
4768 }
4769 break;
4770 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004771
Douglas Gregor96176b32008-11-18 23:14:02 +00004772 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004773 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004774 ICS.Standard.setAsIdentityConversion();
4775 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004776 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004777 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004778 ICS.Standard.ReferenceBinding = true;
4779 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004780 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004781 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004782 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4783 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4784 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004785 return ICS;
4786}
4787
4788/// PerformObjectArgumentInitialization - Perform initialization of
4789/// the implicit object parameter for the given Method with the given
4790/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004791ExprResult
4792Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004793 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004794 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004795 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004796 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004797 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004798 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004799
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004800 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004801 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004802 FromRecordType = PT->getPointeeType();
4803 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004804 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004805 } else {
4806 FromRecordType = From->getType();
4807 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004808 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004809 }
4810
John McCall701c89e2009-12-03 04:06:58 +00004811 // Note that we always use the true parent context when performing
4812 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004813 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004814 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4815 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004816 if (ICS.isBad()) {
4817 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4818 Qualifiers FromQs = FromRecordType.getQualifiers();
4819 Qualifiers ToQs = DestType.getQualifiers();
4820 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4821 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004822 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004823 diag::err_member_function_call_bad_cvr)
4824 << Method->getDeclName() << FromRecordType << (CVR - 1)
4825 << From->getSourceRange();
4826 Diag(Method->getLocation(), diag::note_previous_decl)
4827 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004828 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004829 }
4830 }
4831
Daniel Dunbar96a00142012-03-09 18:35:03 +00004832 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004833 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004834 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004835 }
Mike Stump1eb44332009-09-09 15:08:12 +00004836
John Wiegley429bb272011-04-08 18:41:53 +00004837 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4838 ExprResult FromRes =
4839 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4840 if (FromRes.isInvalid())
4841 return ExprError();
4842 From = FromRes.take();
4843 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004844
Douglas Gregor5fccd362010-03-03 23:55:11 +00004845 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004846 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004847 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004848 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004849}
4850
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004851/// TryContextuallyConvertToBool - Attempt to contextually convert the
4852/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004853static ImplicitConversionSequence
4854TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004855 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004856 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004857 // FIXME: Are these flags correct?
4858 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004859 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004860 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004861 /*CStyle=*/false,
4862 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004863}
4864
4865/// PerformContextuallyConvertToBool - Perform a contextual conversion
4866/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004867ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004868 if (checkPlaceholderForOverload(*this, From))
4869 return ExprError();
4870
John McCall120d63c2010-08-24 20:38:10 +00004871 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004872 if (!ICS.isBad())
4873 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004874
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004875 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004876 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004877 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004878 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004879 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004880}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004881
Richard Smith8ef7b202012-01-18 23:55:52 +00004882/// Check that the specified conversion is permitted in a converted constant
4883/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4884/// is acceptable.
4885static bool CheckConvertedConstantConversions(Sema &S,
4886 StandardConversionSequence &SCS) {
4887 // Since we know that the target type is an integral or unscoped enumeration
4888 // type, most conversion kinds are impossible. All possible First and Third
4889 // conversions are fine.
4890 switch (SCS.Second) {
4891 case ICK_Identity:
4892 case ICK_Integral_Promotion:
4893 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004894 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004895 return true;
4896
4897 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004898 // Conversion from an integral or unscoped enumeration type to bool is
4899 // classified as ICK_Boolean_Conversion, but it's also an integral
4900 // conversion, so it's permitted in a converted constant expression.
4901 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4902 SCS.getToType(2)->isBooleanType();
4903
Richard Smith8ef7b202012-01-18 23:55:52 +00004904 case ICK_Floating_Integral:
4905 case ICK_Complex_Real:
4906 return false;
4907
4908 case ICK_Lvalue_To_Rvalue:
4909 case ICK_Array_To_Pointer:
4910 case ICK_Function_To_Pointer:
4911 case ICK_NoReturn_Adjustment:
4912 case ICK_Qualification:
4913 case ICK_Compatible_Conversion:
4914 case ICK_Vector_Conversion:
4915 case ICK_Vector_Splat:
4916 case ICK_Derived_To_Base:
4917 case ICK_Pointer_Conversion:
4918 case ICK_Pointer_Member:
4919 case ICK_Block_Pointer_Conversion:
4920 case ICK_Writeback_Conversion:
4921 case ICK_Floating_Promotion:
4922 case ICK_Complex_Promotion:
4923 case ICK_Complex_Conversion:
4924 case ICK_Floating_Conversion:
4925 case ICK_TransparentUnionConversion:
4926 llvm_unreachable("unexpected second conversion kind");
4927
4928 case ICK_Num_Conversion_Kinds:
4929 break;
4930 }
4931
4932 llvm_unreachable("unknown conversion kind");
4933}
4934
4935/// CheckConvertedConstantExpression - Check that the expression From is a
4936/// converted constant expression of type T, perform the conversion and produce
4937/// the converted expression, per C++11 [expr.const]p3.
4938ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4939 llvm::APSInt &Value,
4940 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004941 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004942 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4943
4944 if (checkPlaceholderForOverload(*this, From))
4945 return ExprError();
4946
4947 // C++11 [expr.const]p3 with proposed wording fixes:
4948 // A converted constant expression of type T is a core constant expression,
4949 // implicitly converted to a prvalue of type T, where the converted
4950 // expression is a literal constant expression and the implicit conversion
4951 // sequence contains only user-defined conversions, lvalue-to-rvalue
4952 // conversions, integral promotions, and integral conversions other than
4953 // narrowing conversions.
4954 ImplicitConversionSequence ICS =
4955 TryImplicitConversion(From, T,
4956 /*SuppressUserConversions=*/false,
4957 /*AllowExplicit=*/false,
4958 /*InOverloadResolution=*/false,
4959 /*CStyle=*/false,
4960 /*AllowObjcWritebackConversion=*/false);
4961 StandardConversionSequence *SCS = 0;
4962 switch (ICS.getKind()) {
4963 case ImplicitConversionSequence::StandardConversion:
4964 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004965 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004966 diag::err_typecheck_converted_constant_expression_disallowed)
4967 << From->getType() << From->getSourceRange() << T;
4968 SCS = &ICS.Standard;
4969 break;
4970 case ImplicitConversionSequence::UserDefinedConversion:
4971 // We are converting from class type to an integral or enumeration type, so
4972 // the Before sequence must be trivial.
4973 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004974 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004975 diag::err_typecheck_converted_constant_expression_disallowed)
4976 << From->getType() << From->getSourceRange() << T;
4977 SCS = &ICS.UserDefined.After;
4978 break;
4979 case ImplicitConversionSequence::AmbiguousConversion:
4980 case ImplicitConversionSequence::BadConversion:
4981 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004982 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004983 diag::err_typecheck_converted_constant_expression)
4984 << From->getType() << From->getSourceRange() << T;
4985 return ExprError();
4986
4987 case ImplicitConversionSequence::EllipsisConversion:
4988 llvm_unreachable("ellipsis conversion in converted constant expression");
4989 }
4990
4991 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4992 if (Result.isInvalid())
4993 return Result;
4994
4995 // Check for a narrowing implicit conversion.
4996 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004997 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004998 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4999 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005000 case NK_Variable_Narrowing:
5001 // Implicit conversion to a narrower type, and the value is not a constant
5002 // expression. We'll diagnose this in a moment.
5003 case NK_Not_Narrowing:
5004 break;
5005
5006 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005007 Diag(From->getLocStart(),
5008 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5009 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005010 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00005011 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005012 break;
5013
5014 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005015 Diag(From->getLocStart(),
5016 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5017 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005018 << CCE << /*Constant*/0 << From->getType() << T;
5019 break;
5020 }
5021
5022 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005023 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005024 Expr::EvalResult Eval;
5025 Eval.Diag = &Notes;
5026
5027 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5028 // The expression can't be folded, so we can't keep it at this position in
5029 // the AST.
5030 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005031 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005032 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005033
5034 if (Notes.empty()) {
5035 // It's a constant expression.
5036 return Result;
5037 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005038 }
5039
5040 // It's not a constant expression. Produce an appropriate diagnostic.
5041 if (Notes.size() == 1 &&
5042 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5043 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5044 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005045 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005046 << CCE << From->getSourceRange();
5047 for (unsigned I = 0; I < Notes.size(); ++I)
5048 Diag(Notes[I].first, Notes[I].second);
5049 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005050 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005051}
5052
John McCall0bcc9bc2011-09-09 06:11:02 +00005053/// dropPointerConversions - If the given standard conversion sequence
5054/// involves any pointer conversions, remove them. This may change
5055/// the result type of the conversion sequence.
5056static void dropPointerConversion(StandardConversionSequence &SCS) {
5057 if (SCS.Second == ICK_Pointer_Conversion) {
5058 SCS.Second = ICK_Identity;
5059 SCS.Third = ICK_Identity;
5060 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5061 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005062}
John McCall120d63c2010-08-24 20:38:10 +00005063
John McCall0bcc9bc2011-09-09 06:11:02 +00005064/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5065/// convert the expression From to an Objective-C pointer type.
5066static ImplicitConversionSequence
5067TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5068 // Do an implicit conversion to 'id'.
5069 QualType Ty = S.Context.getObjCIdType();
5070 ImplicitConversionSequence ICS
5071 = TryImplicitConversion(S, From, Ty,
5072 // FIXME: Are these flags correct?
5073 /*SuppressUserConversions=*/false,
5074 /*AllowExplicit=*/true,
5075 /*InOverloadResolution=*/false,
5076 /*CStyle=*/false,
5077 /*AllowObjCWritebackConversion=*/false);
5078
5079 // Strip off any final conversions to 'id'.
5080 switch (ICS.getKind()) {
5081 case ImplicitConversionSequence::BadConversion:
5082 case ImplicitConversionSequence::AmbiguousConversion:
5083 case ImplicitConversionSequence::EllipsisConversion:
5084 break;
5085
5086 case ImplicitConversionSequence::UserDefinedConversion:
5087 dropPointerConversion(ICS.UserDefined.After);
5088 break;
5089
5090 case ImplicitConversionSequence::StandardConversion:
5091 dropPointerConversion(ICS.Standard);
5092 break;
5093 }
5094
5095 return ICS;
5096}
5097
5098/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5099/// conversion of the expression From to an Objective-C pointer type.
5100ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005101 if (checkPlaceholderForOverload(*this, From))
5102 return ExprError();
5103
John McCallc12c5bb2010-05-15 11:32:37 +00005104 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005105 ImplicitConversionSequence ICS =
5106 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005107 if (!ICS.isBad())
5108 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005109 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005110}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005111
Richard Smithf39aec12012-02-04 07:07:42 +00005112/// Determine whether the provided type is an integral type, or an enumeration
5113/// type of a permitted flavor.
5114static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5115 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5116 : T->isIntegralOrUnscopedEnumerationType();
5117}
5118
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005119/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005120/// enumeration type.
5121///
5122/// This routine will attempt to convert an expression of class type to an
5123/// integral or enumeration type, if that class type only has a single
5124/// conversion to an integral or enumeration type.
5125///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005126/// \param Loc The source location of the construct that requires the
5127/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005128///
James Dennett40ae6662012-06-22 08:52:37 +00005129/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005130///
James Dennett40ae6662012-06-22 08:52:37 +00005131/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005132///
Richard Smithf39aec12012-02-04 07:07:42 +00005133/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5134/// enumerations should be considered.
5135///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005136/// \returns The expression, converted to an integral or enumeration type if
5137/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005138ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005139Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005140 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005141 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005142 // We can't perform any more checking for type-dependent expressions.
5143 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005144 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005145
Eli Friedmanceccab92012-01-26 00:26:18 +00005146 // Process placeholders immediately.
5147 if (From->hasPlaceholderType()) {
5148 ExprResult result = CheckPlaceholderExpr(From);
5149 if (result.isInvalid()) return result;
5150 From = result.take();
5151 }
5152
Douglas Gregorc30614b2010-06-29 23:17:37 +00005153 // If the expression already has integral or enumeration type, we're golden.
5154 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005155 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005156 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005157
5158 // FIXME: Check for missing '()' if T is a function type?
5159
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005160 // 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 +00005161 // expression of integral or enumeration type.
5162 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005163 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005164 if (!Diagnoser.Suppress)
5165 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005166 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005168
Douglas Gregorc30614b2010-06-29 23:17:37 +00005169 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005170 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005171 ICEConvertDiagnoser &Diagnoser;
5172 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005173
Douglas Gregorab41fe92012-05-04 22:38:52 +00005174 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5175 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005176
5177 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005178 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005179 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005180 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005181
5182 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005183 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005184
Douglas Gregorc30614b2010-06-29 23:17:37 +00005185 // Look for a conversion to an integral or enumeration type.
5186 UnresolvedSet<4> ViableConversions;
5187 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005188 std::pair<CXXRecordDecl::conversion_iterator,
5189 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005190 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005191
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005192 bool HadMultipleCandidates
5193 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005194
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005195 for (CXXRecordDecl::conversion_iterator
5196 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005197 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005198 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5199 if (isIntegralOrEnumerationType(
5200 Conversion->getConversionType().getNonReferenceType(),
5201 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005202 if (Conversion->isExplicit())
5203 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5204 else
5205 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5206 }
Richard Smithf39aec12012-02-04 07:07:42 +00005207 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005209
Douglas Gregorc30614b2010-06-29 23:17:37 +00005210 switch (ViableConversions.size()) {
5211 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005212 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005213 DeclAccessPair Found = ExplicitConversions[0];
5214 CXXConversionDecl *Conversion
5215 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005216
Douglas Gregorc30614b2010-06-29 23:17:37 +00005217 // The user probably meant to invoke the given explicit
5218 // conversion; use it.
5219 QualType ConvTy
5220 = Conversion->getConversionType().getNonReferenceType();
5221 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005222 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223
Douglas Gregorab41fe92012-05-04 22:38:52 +00005224 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005225 << FixItHint::CreateInsertion(From->getLocStart(),
5226 "static_cast<" + TypeStr + ">(")
5227 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5228 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005229 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005230
5231 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005232 // explicit conversion function.
5233 if (isSFINAEContext())
5234 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005235
Douglas Gregorc30614b2010-06-29 23:17:37 +00005236 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005237 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5238 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005239 if (Result.isInvalid())
5240 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005241 // Record usage of conversion in an implicit cast.
5242 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5243 CK_UserDefinedConversion,
5244 Result.get(), 0,
5245 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005246 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005247
Douglas Gregorc30614b2010-06-29 23:17:37 +00005248 // We'll complain below about a non-integral condition type.
5249 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005250
Douglas Gregorc30614b2010-06-29 23:17:37 +00005251 case 1: {
5252 // Apply this conversion.
5253 DeclAccessPair Found = ViableConversions[0];
5254 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005255
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005256 CXXConversionDecl *Conversion
5257 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5258 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005259 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005260 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005261 if (isSFINAEContext())
5262 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263
Douglas Gregorab41fe92012-05-04 22:38:52 +00005264 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5265 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005266 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005267
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005268 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5269 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005270 if (Result.isInvalid())
5271 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005272 // Record usage of conversion in an implicit cast.
5273 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5274 CK_UserDefinedConversion,
5275 Result.get(), 0,
5276 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005277 break;
5278 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005279
Douglas Gregorc30614b2010-06-29 23:17:37 +00005280 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005281 if (Diagnoser.Suppress)
5282 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005283
Douglas Gregorab41fe92012-05-04 22:38:52 +00005284 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005285 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5286 CXXConversionDecl *Conv
5287 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5288 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005289 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005290 }
John McCall9ae2f072010-08-23 23:25:46 +00005291 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005292 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005293
Richard Smith282e7e62012-02-04 09:53:13 +00005294 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005295 !Diagnoser.Suppress) {
5296 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5297 << From->getSourceRange();
5298 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005299
Eli Friedmanceccab92012-01-26 00:26:18 +00005300 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005301}
5302
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005303/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005304/// candidate functions, using the given function call arguments. If
5305/// @p SuppressUserConversions, then don't allow user-defined
5306/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005307///
James Dennett699c9042012-06-15 07:13:21 +00005308/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005309/// based on an incomplete set of function arguments. This feature is used by
5310/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005311void
5312Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005313 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005314 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005315 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005316 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005317 bool PartialOverloading,
5318 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005319 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005320 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005321 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005322 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005323 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005324
Douglas Gregor88a35142008-12-22 05:46:06 +00005325 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005326 if (!isa<CXXConstructorDecl>(Method)) {
5327 // If we get here, it's because we're calling a member function
5328 // that is named without a member access expression (e.g.,
5329 // "this->f") that was either written explicitly or created
5330 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005331 // function, e.g., X::f(). We use an empty type for the implied
5332 // object argument (C++ [over.call.func]p3), and the acting context
5333 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005334 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005335 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005337 return;
5338 }
5339 // We treat a constructor like a non-member function, since its object
5340 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005341 }
5342
Douglas Gregorfd476482009-11-13 23:59:09 +00005343 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005344 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005345
Douglas Gregor7edfb692009-11-23 12:27:39 +00005346 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005347 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005348
Douglas Gregor66724ea2009-11-14 01:20:54 +00005349 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5350 // C++ [class.copy]p3:
5351 // A member function template is never instantiated to perform the copy
5352 // of a class object to an object of its class type.
5353 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005354 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005355 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005356 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5357 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005358 return;
5359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005360
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005361 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005362 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005363 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005364 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005365 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005366 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005367 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005368 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005369
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005370 unsigned NumArgsInProto = Proto->getNumArgs();
5371
5372 // (C++ 13.3.2p2): A candidate function having fewer than m
5373 // parameters is viable only if it has an ellipsis in its parameter
5374 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005375 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005376 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005377 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005378 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005379 return;
5380 }
5381
5382 // (C++ 13.3.2p2): A candidate function having more than m parameters
5383 // is viable only if the (m+1)st parameter has a default argument
5384 // (8.3.6). For the purposes of overload resolution, the
5385 // parameter list is truncated on the right, so that there are
5386 // exactly m parameters.
5387 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005388 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005389 // Not enough arguments.
5390 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005391 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005392 return;
5393 }
5394
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005395 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005396 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005397 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5398 if (CheckCUDATarget(Caller, Function)) {
5399 Candidate.Viable = false;
5400 Candidate.FailureKind = ovl_fail_bad_target;
5401 return;
5402 }
5403
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005404 // Determine the implicit conversion sequences for each of the
5405 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005406 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005407 if (ArgIdx < NumArgsInProto) {
5408 // (C++ 13.3.2p3): for F to be a viable function, there shall
5409 // exist for each argument an implicit conversion sequence
5410 // (13.3.3.1) that converts that argument to the corresponding
5411 // parameter of F.
5412 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005413 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005414 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005415 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005416 /*InOverloadResolution=*/true,
5417 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005418 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005419 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005420 if (Candidate.Conversions[ArgIdx].isBad()) {
5421 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005422 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005423 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005424 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005425 } else {
5426 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5427 // argument for which there is no corresponding parameter is
5428 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005429 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005430 }
5431 }
5432}
5433
Douglas Gregor063daf62009-03-13 18:40:31 +00005434/// \brief Add all of the function declarations in the given function set to
5435/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005436void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005437 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005438 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005439 bool SuppressUserConversions,
5440 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005441 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005442 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005444 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005445 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005446 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005447 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005448 Args.slice(1), CandidateSet,
5449 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005450 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005451 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005452 SuppressUserConversions);
5453 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005454 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005455 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5456 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005457 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005458 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005459 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005460 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005461 Args[0]->Classify(Context), Args.slice(1),
5462 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005463 else
John McCall9aa472c2010-03-19 07:35:19 +00005464 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005465 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005466 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005467 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005468 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005469}
5470
John McCall314be4e2009-11-17 07:50:12 +00005471/// AddMethodCandidate - Adds a named decl (which is some kind of
5472/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005473void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005474 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005475 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005476 Expr **Args, unsigned NumArgs,
5477 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005478 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005479 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005480 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005481
5482 if (isa<UsingShadowDecl>(Decl))
5483 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005484
John McCall314be4e2009-11-17 07:50:12 +00005485 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5486 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5487 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005488 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5489 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005490 ObjectType, ObjectClassification,
5491 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005492 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005493 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005494 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005495 ObjectType, ObjectClassification,
5496 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005497 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005498 }
5499}
5500
Douglas Gregor96176b32008-11-18 23:14:02 +00005501/// AddMethodCandidate - Adds the given C++ member function to the set
5502/// of candidate functions, using the given function call arguments
5503/// and the object argument (@c Object). For example, in a call
5504/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5505/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5506/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005507/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005508void
John McCall9aa472c2010-03-19 07:35:19 +00005509Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005510 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005511 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005512 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005513 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005514 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005515 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005516 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005517 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005518 assert(!isa<CXXConstructorDecl>(Method) &&
5519 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005520
Douglas Gregor3f396022009-09-28 04:47:19 +00005521 if (!CandidateSet.isNewCandidate(Method))
5522 return;
5523
Douglas Gregor7edfb692009-11-23 12:27:39 +00005524 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005525 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005526
Douglas Gregor96176b32008-11-18 23:14:02 +00005527 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005528 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005529 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005530 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005531 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005532 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005533 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005534
5535 unsigned NumArgsInProto = Proto->getNumArgs();
5536
5537 // (C++ 13.3.2p2): A candidate function having fewer than m
5538 // parameters is viable only if it has an ellipsis in its parameter
5539 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005540 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005541 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005542 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005543 return;
5544 }
5545
5546 // (C++ 13.3.2p2): A candidate function having more than m parameters
5547 // is viable only if the (m+1)st parameter has a default argument
5548 // (8.3.6). For the purposes of overload resolution, the
5549 // parameter list is truncated on the right, so that there are
5550 // exactly m parameters.
5551 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005552 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005553 // Not enough arguments.
5554 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005555 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005556 return;
5557 }
5558
5559 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005560
John McCall701c89e2009-12-03 04:06:58 +00005561 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005562 // The implicit object argument is ignored.
5563 Candidate.IgnoreObjectArgument = true;
5564 else {
5565 // Determine the implicit conversion sequence for the object
5566 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005567 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005568 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5569 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005570 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005571 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005572 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005573 return;
5574 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005575 }
5576
5577 // Determine the implicit conversion sequences for each of the
5578 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005579 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005580 if (ArgIdx < NumArgsInProto) {
5581 // (C++ 13.3.2p3): for F to be a viable function, there shall
5582 // exist for each argument an implicit conversion sequence
5583 // (13.3.3.1) that converts that argument to the corresponding
5584 // parameter of F.
5585 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005586 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005587 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005588 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005589 /*InOverloadResolution=*/true,
5590 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005591 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005592 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005593 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005594 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005595 break;
5596 }
5597 } else {
5598 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5599 // argument for which there is no corresponding parameter is
5600 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005601 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005602 }
5603 }
5604}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605
Douglas Gregor6b906862009-08-21 00:16:32 +00005606/// \brief Add a C++ member function template as a candidate to the candidate
5607/// set, using template argument deduction to produce an appropriate member
5608/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005609void
Douglas Gregor6b906862009-08-21 00:16:32 +00005610Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005611 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005612 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005613 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005614 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005615 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005616 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005617 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005618 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005619 if (!CandidateSet.isNewCandidate(MethodTmpl))
5620 return;
5621
Douglas Gregor6b906862009-08-21 00:16:32 +00005622 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005623 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005624 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005625 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005626 // candidate functions in the usual way.113) A given name can refer to one
5627 // or more function templates and also to a set of overloaded non-template
5628 // functions. In such a case, the candidate functions generated from each
5629 // function template are combined with the set of non-template candidate
5630 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005631 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005632 FunctionDecl *Specialization = 0;
5633 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005634 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5635 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005636 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005637 Candidate.FoundDecl = FoundDecl;
5638 Candidate.Function = MethodTmpl->getTemplatedDecl();
5639 Candidate.Viable = false;
5640 Candidate.FailureKind = ovl_fail_bad_deduction;
5641 Candidate.IsSurrogate = false;
5642 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005643 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005645 Info);
5646 return;
5647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Douglas Gregor6b906862009-08-21 00:16:32 +00005649 // Add the function template specialization produced by template argument
5650 // deduction as a candidate.
5651 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005652 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005653 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005654 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005655 ActingContext, ObjectType, ObjectClassification, Args,
5656 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005657}
5658
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005659/// \brief Add a C++ function template specialization as a candidate
5660/// in the candidate set, using template argument deduction to produce
5661/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005662void
Douglas Gregore53060f2009-06-25 22:08:12 +00005663Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005664 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005665 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005666 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005667 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005668 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005669 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5670 return;
5671
Douglas Gregore53060f2009-06-25 22:08:12 +00005672 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005673 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005674 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005675 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005676 // candidate functions in the usual way.113) A given name can refer to one
5677 // or more function templates and also to a set of overloaded non-template
5678 // functions. In such a case, the candidate functions generated from each
5679 // function template are combined with the set of non-template candidate
5680 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005681 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005682 FunctionDecl *Specialization = 0;
5683 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005684 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5685 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005686 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005687 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005688 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5689 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005690 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005691 Candidate.IsSurrogate = false;
5692 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005693 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005694 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005695 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005696 return;
5697 }
Mike Stump1eb44332009-09-09 15:08:12 +00005698
Douglas Gregore53060f2009-06-25 22:08:12 +00005699 // Add the function template specialization produced by template argument
5700 // deduction as a candidate.
5701 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005702 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005703 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005704}
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005706/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005707/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005708/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005709/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005710/// (which may or may not be the same type as the type that the
5711/// conversion function produces).
5712void
5713Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005714 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005715 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005716 Expr *From, QualType ToType,
5717 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005718 assert(!Conversion->getDescribedFunctionTemplate() &&
5719 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005720 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005721 if (!CandidateSet.isNewCandidate(Conversion))
5722 return;
5723
Douglas Gregor7edfb692009-11-23 12:27:39 +00005724 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005725 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005726
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005727 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005728 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005729 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005730 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005731 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005732 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005733 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005734 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005735 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005736 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005737 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005738
Douglas Gregorbca39322010-08-19 15:37:02 +00005739 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005740 // For conversion functions, the function is considered to be a member of
5741 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005742 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005743 //
5744 // Determine the implicit conversion sequence for the implicit
5745 // object parameter.
5746 QualType ImplicitParamType = From->getType();
5747 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5748 ImplicitParamType = FromPtrType->getPointeeType();
5749 CXXRecordDecl *ConversionContext
5750 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005752 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005753 = TryObjectArgumentInitialization(*this, From->getType(),
5754 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005755 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005756
John McCall1d318332010-01-12 00:44:57 +00005757 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005758 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005759 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005760 return;
5761 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005762
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005763 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005764 // derived to base as such conversions are given Conversion Rank. They only
5765 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5766 QualType FromCanon
5767 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5768 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5769 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5770 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005771 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005772 return;
5773 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005774
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005775 // To determine what the conversion from the result of calling the
5776 // conversion function to the type we're eventually trying to
5777 // convert to (ToType), we need to synthesize a call to the
5778 // conversion function and attempt copy initialization from it. This
5779 // makes sure that we get the right semantics with respect to
5780 // lvalues/rvalues and the type. Fortunately, we can allocate this
5781 // call on the stack and we don't need its arguments to be
5782 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005783 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005784 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005785 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5786 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005787 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005788 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005789
Richard Smith87c1f1f2011-07-13 22:53:21 +00005790 QualType ConversionType = Conversion->getConversionType();
5791 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005792 Candidate.Viable = false;
5793 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5794 return;
5795 }
5796
Richard Smith87c1f1f2011-07-13 22:53:21 +00005797 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005798
Mike Stump1eb44332009-09-09 15:08:12 +00005799 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005800 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5801 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005802 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005803 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005804 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005805 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005806 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005807 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005808 /*InOverloadResolution=*/false,
5809 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005810
John McCall1d318332010-01-12 00:44:57 +00005811 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005812 case ImplicitConversionSequence::StandardConversion:
5813 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005814
Douglas Gregorc520c842010-04-12 23:42:09 +00005815 // C++ [over.ics.user]p3:
5816 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005817 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005818 // shall have exact match rank.
5819 if (Conversion->getPrimaryTemplate() &&
5820 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5821 Candidate.Viable = false;
5822 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5823 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005824
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005825 // C++0x [dcl.init.ref]p5:
5826 // In the second case, if the reference is an rvalue reference and
5827 // the second standard conversion sequence of the user-defined
5828 // conversion sequence includes an lvalue-to-rvalue conversion, the
5829 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005830 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005831 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5832 Candidate.Viable = false;
5833 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5834 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005835 break;
5836
5837 case ImplicitConversionSequence::BadConversion:
5838 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005839 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005840 break;
5841
5842 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005843 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005844 "Can only end up with a standard conversion sequence or failure");
5845 }
5846}
5847
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005848/// \brief Adds a conversion function template specialization
5849/// candidate to the overload set, using template argument deduction
5850/// to deduce the template arguments of the conversion function
5851/// template from the type that we are converting to (C++
5852/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005853void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005854Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005855 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005856 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005857 Expr *From, QualType ToType,
5858 OverloadCandidateSet &CandidateSet) {
5859 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5860 "Only conversion function templates permitted here");
5861
Douglas Gregor3f396022009-09-28 04:47:19 +00005862 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5863 return;
5864
Craig Topper93e45992012-09-19 02:26:47 +00005865 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005866 CXXConversionDecl *Specialization = 0;
5867 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005868 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005869 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005870 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005871 Candidate.FoundDecl = FoundDecl;
5872 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5873 Candidate.Viable = false;
5874 Candidate.FailureKind = ovl_fail_bad_deduction;
5875 Candidate.IsSurrogate = false;
5876 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005877 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005878 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005879 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005880 return;
5881 }
Mike Stump1eb44332009-09-09 15:08:12 +00005882
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005883 // Add the conversion function template specialization produced by
5884 // template argument deduction as a candidate.
5885 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005886 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005887 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005888}
5889
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005890/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5891/// converts the given @c Object to a function pointer via the
5892/// conversion function @c Conversion, and then attempts to call it
5893/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5894/// the type of function that we'll eventually be calling.
5895void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005896 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005897 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005898 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005899 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005900 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005901 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005902 if (!CandidateSet.isNewCandidate(Conversion))
5903 return;
5904
Douglas Gregor7edfb692009-11-23 12:27:39 +00005905 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005906 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005907
Ahmed Charles13a140c2012-02-25 11:00:22 +00005908 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005909 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005910 Candidate.Function = 0;
5911 Candidate.Surrogate = Conversion;
5912 Candidate.Viable = true;
5913 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005914 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005915 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005916
5917 // Determine the implicit conversion sequence for the implicit
5918 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005919 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005920 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005921 Object->Classify(Context),
5922 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005923 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005924 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005925 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005926 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005927 return;
5928 }
5929
5930 // The first conversion is actually a user-defined conversion whose
5931 // first conversion is ObjectInit's standard conversion (which is
5932 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005933 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005934 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005935 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005936 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005937 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005938 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005939 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005940 = Candidate.Conversions[0].UserDefined.Before;
5941 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5942
Mike Stump1eb44332009-09-09 15:08:12 +00005943 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005944 unsigned NumArgsInProto = Proto->getNumArgs();
5945
5946 // (C++ 13.3.2p2): A candidate function having fewer than m
5947 // parameters is viable only if it has an ellipsis in its parameter
5948 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005949 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005950 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005951 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005952 return;
5953 }
5954
5955 // Function types don't have any default arguments, so just check if
5956 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005957 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005958 // Not enough arguments.
5959 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005960 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005961 return;
5962 }
5963
5964 // Determine the implicit conversion sequences for each of the
5965 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005966 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005967 if (ArgIdx < NumArgsInProto) {
5968 // (C++ 13.3.2p3): for F to be a viable function, there shall
5969 // exist for each argument an implicit conversion sequence
5970 // (13.3.3.1) that converts that argument to the corresponding
5971 // parameter of F.
5972 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005973 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005974 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005975 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005976 /*InOverloadResolution=*/false,
5977 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005978 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005979 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005980 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005981 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005982 break;
5983 }
5984 } else {
5985 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5986 // argument for which there is no corresponding parameter is
5987 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005988 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005989 }
5990 }
5991}
5992
Douglas Gregor063daf62009-03-13 18:40:31 +00005993/// \brief Add overload candidates for overloaded operators that are
5994/// member functions.
5995///
5996/// Add the overloaded operator candidates that are member functions
5997/// for the operator Op that was used in an operator expression such
5998/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5999/// CandidateSet will store the added overload candidates. (C++
6000/// [over.match.oper]).
6001void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6002 SourceLocation OpLoc,
6003 Expr **Args, unsigned NumArgs,
6004 OverloadCandidateSet& CandidateSet,
6005 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006006 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6007
6008 // C++ [over.match.oper]p3:
6009 // For a unary operator @ with an operand of a type whose
6010 // cv-unqualified version is T1, and for a binary operator @ with
6011 // a left operand of a type whose cv-unqualified version is T1 and
6012 // a right operand of a type whose cv-unqualified version is T2,
6013 // three sets of candidate functions, designated member
6014 // candidates, non-member candidates and built-in candidates, are
6015 // constructed as follows:
6016 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006017
6018 // -- If T1 is a class type, the set of member candidates is the
6019 // result of the qualified lookup of T1::operator@
6020 // (13.3.1.1.1); otherwise, the set of member candidates is
6021 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006022 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006023 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00006024 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006025 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006026
John McCalla24dc2e2009-11-17 02:14:36 +00006027 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6028 LookupQualifiedName(Operators, T1Rec->getDecl());
6029 Operators.suppressDiagnostics();
6030
Mike Stump1eb44332009-09-09 15:08:12 +00006031 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006032 OperEnd = Operators.end();
6033 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006034 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006035 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006036 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006037 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006038 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006039 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006040}
6041
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006042/// AddBuiltinCandidate - Add a candidate for a built-in
6043/// operator. ResultTy and ParamTys are the result and parameter types
6044/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006045/// arguments being passed to the candidate. IsAssignmentOperator
6046/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006047/// operator. NumContextualBoolArguments is the number of arguments
6048/// (at the beginning of the argument list) that will be contextually
6049/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006050void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006051 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006052 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006053 bool IsAssignmentOperator,
6054 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006055 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006056 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006057
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006058 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006059 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006060 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006062 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006063 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006064 Candidate.BuiltinTypes.ResultTy = ResultTy;
6065 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6066 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6067
6068 // Determine the implicit conversion sequences for each of the
6069 // arguments.
6070 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006071 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006072 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006073 // C++ [over.match.oper]p4:
6074 // For the built-in assignment operators, conversions of the
6075 // left operand are restricted as follows:
6076 // -- no temporaries are introduced to hold the left operand, and
6077 // -- no user-defined conversions are applied to the left
6078 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006079 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006080 //
6081 // We block these conversions by turning off user-defined
6082 // conversions, since that is the only way that initialization of
6083 // a reference to a non-class type can occur from something that
6084 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006085 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006086 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006087 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006088 Candidate.Conversions[ArgIdx]
6089 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006090 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006091 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006092 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006093 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006094 /*InOverloadResolution=*/false,
6095 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006096 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006097 }
John McCall1d318332010-01-12 00:44:57 +00006098 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006099 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006100 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006101 break;
6102 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006103 }
6104}
6105
6106/// BuiltinCandidateTypeSet - A set of types that will be used for the
6107/// candidate operator functions for built-in operators (C++
6108/// [over.built]). The types are separated into pointer types and
6109/// enumeration types.
6110class BuiltinCandidateTypeSet {
6111 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006112 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006113
6114 /// PointerTypes - The set of pointer types that will be used in the
6115 /// built-in candidates.
6116 TypeSet PointerTypes;
6117
Sebastian Redl78eb8742009-04-19 21:53:20 +00006118 /// MemberPointerTypes - The set of member pointer types that will be
6119 /// used in the built-in candidates.
6120 TypeSet MemberPointerTypes;
6121
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006122 /// EnumerationTypes - The set of enumeration types that will be
6123 /// used in the built-in candidates.
6124 TypeSet EnumerationTypes;
6125
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006126 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006127 /// candidates.
6128 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006129
6130 /// \brief A flag indicating non-record types are viable candidates
6131 bool HasNonRecordTypes;
6132
6133 /// \brief A flag indicating whether either arithmetic or enumeration types
6134 /// were present in the candidate set.
6135 bool HasArithmeticOrEnumeralTypes;
6136
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006137 /// \brief A flag indicating whether the nullptr type was present in the
6138 /// candidate set.
6139 bool HasNullPtrType;
6140
Douglas Gregor5842ba92009-08-24 15:23:48 +00006141 /// Sema - The semantic analysis instance where we are building the
6142 /// candidate type set.
6143 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006144
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006145 /// Context - The AST context in which we will build the type sets.
6146 ASTContext &Context;
6147
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006148 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6149 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006150 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006151
6152public:
6153 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006154 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006155
Mike Stump1eb44332009-09-09 15:08:12 +00006156 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006157 : HasNonRecordTypes(false),
6158 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006159 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006160 SemaRef(SemaRef),
6161 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006162
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006163 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006164 SourceLocation Loc,
6165 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006166 bool AllowExplicitConversions,
6167 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006168
6169 /// pointer_begin - First pointer type found;
6170 iterator pointer_begin() { return PointerTypes.begin(); }
6171
Sebastian Redl78eb8742009-04-19 21:53:20 +00006172 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006173 iterator pointer_end() { return PointerTypes.end(); }
6174
Sebastian Redl78eb8742009-04-19 21:53:20 +00006175 /// member_pointer_begin - First member pointer type found;
6176 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6177
6178 /// member_pointer_end - Past the last member pointer type found;
6179 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6180
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006181 /// enumeration_begin - First enumeration type found;
6182 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6183
Sebastian Redl78eb8742009-04-19 21:53:20 +00006184 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006185 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006186
Douglas Gregor26bcf672010-05-19 03:21:00 +00006187 iterator vector_begin() { return VectorTypes.begin(); }
6188 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006189
6190 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6191 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006192 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006193};
6194
Sebastian Redl78eb8742009-04-19 21:53:20 +00006195/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006196/// the set of pointer types along with any more-qualified variants of
6197/// that type. For example, if @p Ty is "int const *", this routine
6198/// will add "int const *", "int const volatile *", "int const
6199/// restrict *", and "int const volatile restrict *" to the set of
6200/// pointer types. Returns true if the add of @p Ty itself succeeded,
6201/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006202///
6203/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006204bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006205BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6206 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006207
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006208 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006209 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006210 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006211
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006212 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006213 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006214 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006215 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006216 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6217 PointeeTy = PTy->getPointeeType();
6218 buildObjCPtr = true;
6219 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006220 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006221 }
6222
Sebastian Redla9efada2009-11-18 20:39:26 +00006223 // Don't add qualified variants of arrays. For one, they're not allowed
6224 // (the qualifier would sink to the element type), and for another, the
6225 // only overload situation where it matters is subscript or pointer +- int,
6226 // and those shouldn't have qualifier variants anyway.
6227 if (PointeeTy->isArrayType())
6228 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006229
John McCall0953e762009-09-24 19:53:00 +00006230 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006231 bool hasVolatile = VisibleQuals.hasVolatile();
6232 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006233
John McCall0953e762009-09-24 19:53:00 +00006234 // Iterate through all strict supersets of BaseCVR.
6235 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6236 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006237 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006238 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006239
6240 // Skip over restrict if no restrict found anywhere in the types, or if
6241 // the type cannot be restrict-qualified.
6242 if ((CVR & Qualifiers::Restrict) &&
6243 (!hasRestrict ||
6244 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6245 continue;
6246
6247 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006248 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006249
6250 // Build qualified pointer type.
6251 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006252 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006253 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006254 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006255 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6256
6257 // Insert qualified pointer type.
6258 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006259 }
6260
6261 return true;
6262}
6263
Sebastian Redl78eb8742009-04-19 21:53:20 +00006264/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6265/// to the set of pointer types along with any more-qualified variants of
6266/// that type. For example, if @p Ty is "int const *", this routine
6267/// will add "int const *", "int const volatile *", "int const
6268/// restrict *", and "int const volatile restrict *" to the set of
6269/// pointer types. Returns true if the add of @p Ty itself succeeded,
6270/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006271///
6272/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006273bool
6274BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6275 QualType Ty) {
6276 // Insert this type.
6277 if (!MemberPointerTypes.insert(Ty))
6278 return false;
6279
John McCall0953e762009-09-24 19:53:00 +00006280 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6281 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006282
John McCall0953e762009-09-24 19:53:00 +00006283 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006284 // Don't add qualified variants of arrays. For one, they're not allowed
6285 // (the qualifier would sink to the element type), and for another, the
6286 // only overload situation where it matters is subscript or pointer +- int,
6287 // and those shouldn't have qualifier variants anyway.
6288 if (PointeeTy->isArrayType())
6289 return true;
John McCall0953e762009-09-24 19:53:00 +00006290 const Type *ClassTy = PointerTy->getClass();
6291
6292 // Iterate through all strict supersets of the pointee type's CVR
6293 // qualifiers.
6294 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6295 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6296 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006297
John McCall0953e762009-09-24 19:53:00 +00006298 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006299 MemberPointerTypes.insert(
6300 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006301 }
6302
6303 return true;
6304}
6305
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006306/// AddTypesConvertedFrom - Add each of the types to which the type @p
6307/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006308/// primarily interested in pointer types and enumeration types. We also
6309/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006310/// AllowUserConversions is true if we should look at the conversion
6311/// functions of a class type, and AllowExplicitConversions if we
6312/// should also include the explicit conversion functions of a class
6313/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006314void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006315BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006316 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006317 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006318 bool AllowExplicitConversions,
6319 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006320 // Only deal with canonical types.
6321 Ty = Context.getCanonicalType(Ty);
6322
6323 // Look through reference types; they aren't part of the type of an
6324 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006325 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006326 Ty = RefTy->getPointeeType();
6327
John McCall3b657512011-01-19 10:06:00 +00006328 // If we're dealing with an array type, decay to the pointer.
6329 if (Ty->isArrayType())
6330 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6331
6332 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006333 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006334
Chandler Carruth6a577462010-12-13 01:44:01 +00006335 // Flag if we ever add a non-record type.
6336 const RecordType *TyRec = Ty->getAs<RecordType>();
6337 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6338
Chandler Carruth6a577462010-12-13 01:44:01 +00006339 // Flag if we encounter an arithmetic type.
6340 HasArithmeticOrEnumeralTypes =
6341 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6342
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006343 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6344 PointerTypes.insert(Ty);
6345 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006346 // Insert our type, and its more-qualified variants, into the set
6347 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006348 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006349 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006350 } else if (Ty->isMemberPointerType()) {
6351 // Member pointers are far easier, since the pointee can't be converted.
6352 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6353 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006354 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006355 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006356 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006357 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006358 // We treat vector types as arithmetic types in many contexts as an
6359 // extension.
6360 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006361 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006362 } else if (Ty->isNullPtrType()) {
6363 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006364 } else if (AllowUserConversions && TyRec) {
6365 // No conversion functions in incomplete types.
6366 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6367 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006368
Chandler Carruth6a577462010-12-13 01:44:01 +00006369 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006370 std::pair<CXXRecordDecl::conversion_iterator,
6371 CXXRecordDecl::conversion_iterator>
6372 Conversions = ClassDecl->getVisibleConversionFunctions();
6373 for (CXXRecordDecl::conversion_iterator
6374 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006375 NamedDecl *D = I.getDecl();
6376 if (isa<UsingShadowDecl>(D))
6377 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006378
Chandler Carruth6a577462010-12-13 01:44:01 +00006379 // Skip conversion function templates; they don't tell us anything
6380 // about which builtin types we can convert to.
6381 if (isa<FunctionTemplateDecl>(D))
6382 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006383
Chandler Carruth6a577462010-12-13 01:44:01 +00006384 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6385 if (AllowExplicitConversions || !Conv->isExplicit()) {
6386 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6387 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006388 }
6389 }
6390 }
6391}
6392
Douglas Gregor19b7b152009-08-24 13:43:27 +00006393/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6394/// the volatile- and non-volatile-qualified assignment operators for the
6395/// given type to the candidate set.
6396static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6397 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006398 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006399 unsigned NumArgs,
6400 OverloadCandidateSet &CandidateSet) {
6401 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006402
Douglas Gregor19b7b152009-08-24 13:43:27 +00006403 // T& operator=(T&, T)
6404 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6405 ParamTypes[1] = T;
6406 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6407 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006408
Douglas Gregor19b7b152009-08-24 13:43:27 +00006409 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6410 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006411 ParamTypes[0]
6412 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006413 ParamTypes[1] = T;
6414 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006415 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006416 }
6417}
Mike Stump1eb44332009-09-09 15:08:12 +00006418
Sebastian Redl9994a342009-10-25 17:03:50 +00006419/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6420/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006421static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6422 Qualifiers VRQuals;
6423 const RecordType *TyRec;
6424 if (const MemberPointerType *RHSMPType =
6425 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006426 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006427 else
6428 TyRec = ArgExpr->getType()->getAs<RecordType>();
6429 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006430 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006431 VRQuals.addVolatile();
6432 VRQuals.addRestrict();
6433 return VRQuals;
6434 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006435
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006436 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006437 if (!ClassDecl->hasDefinition())
6438 return VRQuals;
6439
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006440 std::pair<CXXRecordDecl::conversion_iterator,
6441 CXXRecordDecl::conversion_iterator>
6442 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006443
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006444 for (CXXRecordDecl::conversion_iterator
6445 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006446 NamedDecl *D = I.getDecl();
6447 if (isa<UsingShadowDecl>(D))
6448 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6449 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006450 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6451 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6452 CanTy = ResTypeRef->getPointeeType();
6453 // Need to go down the pointer/mempointer chain and add qualifiers
6454 // as see them.
6455 bool done = false;
6456 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006457 if (CanTy.isRestrictQualified())
6458 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006459 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6460 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006461 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006462 CanTy->getAs<MemberPointerType>())
6463 CanTy = ResTypeMPtr->getPointeeType();
6464 else
6465 done = true;
6466 if (CanTy.isVolatileQualified())
6467 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006468 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6469 return VRQuals;
6470 }
6471 }
6472 }
6473 return VRQuals;
6474}
John McCall00071ec2010-11-13 05:51:15 +00006475
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006476namespace {
John McCall00071ec2010-11-13 05:51:15 +00006477
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006478/// \brief Helper class to manage the addition of builtin operator overload
6479/// candidates. It provides shared state and utility methods used throughout
6480/// the process, as well as a helper method to add each group of builtin
6481/// operator overloads from the standard to a candidate set.
6482class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006483 // Common instance state available to all overload candidate addition methods.
6484 Sema &S;
6485 Expr **Args;
6486 unsigned NumArgs;
6487 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006488 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006489 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006490 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006491
Chandler Carruth6d695582010-12-12 10:35:00 +00006492 // Define some constants used to index and iterate over the arithemetic types
6493 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006494 // The "promoted arithmetic types" are the arithmetic
6495 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006496 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006497 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006498 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006499 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006500 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006501 LastPromotedArithmeticType = 11;
6502 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006503
Chandler Carruth6d695582010-12-12 10:35:00 +00006504 /// \brief Get the canonical type for a given arithmetic type index.
6505 CanQualType getArithmeticType(unsigned index) {
6506 assert(index < NumArithmeticTypes);
6507 static CanQualType ASTContext::* const
6508 ArithmeticTypes[NumArithmeticTypes] = {
6509 // Start of promoted types.
6510 &ASTContext::FloatTy,
6511 &ASTContext::DoubleTy,
6512 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006513
Chandler Carruth6d695582010-12-12 10:35:00 +00006514 // Start of integral types.
6515 &ASTContext::IntTy,
6516 &ASTContext::LongTy,
6517 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006518 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006519 &ASTContext::UnsignedIntTy,
6520 &ASTContext::UnsignedLongTy,
6521 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006522 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006523 // End of promoted types.
6524
6525 &ASTContext::BoolTy,
6526 &ASTContext::CharTy,
6527 &ASTContext::WCharTy,
6528 &ASTContext::Char16Ty,
6529 &ASTContext::Char32Ty,
6530 &ASTContext::SignedCharTy,
6531 &ASTContext::ShortTy,
6532 &ASTContext::UnsignedCharTy,
6533 &ASTContext::UnsignedShortTy,
6534 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006535 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006536 };
6537 return S.Context.*ArithmeticTypes[index];
6538 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006539
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006540 /// \brief Gets the canonical type resulting from the usual arithemetic
6541 /// converions for the given arithmetic types.
6542 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6543 // Accelerator table for performing the usual arithmetic conversions.
6544 // The rules are basically:
6545 // - if either is floating-point, use the wider floating-point
6546 // - if same signedness, use the higher rank
6547 // - if same size, use unsigned of the higher rank
6548 // - use the larger type
6549 // These rules, together with the axiom that higher ranks are
6550 // never smaller, are sufficient to precompute all of these results
6551 // *except* when dealing with signed types of higher rank.
6552 // (we could precompute SLL x UI for all known platforms, but it's
6553 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006554 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006555 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006556 Dep=-1,
6557 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006558 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006559 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006560 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006561/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6562/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6563/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6564/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6565/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6566/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6567/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6568/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6569/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6570/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6571/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006572 };
6573
6574 assert(L < LastPromotedArithmeticType);
6575 assert(R < LastPromotedArithmeticType);
6576 int Idx = ConversionsTable[L][R];
6577
6578 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006579 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006580
6581 // Slow path: we need to compare widths.
6582 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006583 CanQualType LT = getArithmeticType(L),
6584 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006585 unsigned LW = S.Context.getIntWidth(LT),
6586 RW = S.Context.getIntWidth(RT);
6587
6588 // If they're different widths, use the signed type.
6589 if (LW > RW) return LT;
6590 else if (LW < RW) return RT;
6591
6592 // Otherwise, use the unsigned type of the signed type's rank.
6593 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6594 assert(L == SLL || R == SLL);
6595 return S.Context.UnsignedLongLongTy;
6596 }
6597
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006598 /// \brief Helper method to factor out the common pattern of adding overloads
6599 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006600 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006601 bool HasVolatile,
6602 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006603 QualType ParamTypes[2] = {
6604 S.Context.getLValueReferenceType(CandidateTy),
6605 S.Context.IntTy
6606 };
6607
6608 // Non-volatile version.
6609 if (NumArgs == 1)
6610 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6611 else
6612 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6613
6614 // Use a heuristic to reduce number of builtin candidates in the set:
6615 // add volatile version only if there are conversions to a volatile type.
6616 if (HasVolatile) {
6617 ParamTypes[0] =
6618 S.Context.getLValueReferenceType(
6619 S.Context.getVolatileType(CandidateTy));
6620 if (NumArgs == 1)
6621 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6622 else
6623 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6624 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006625
6626 // Add restrict version only if there are conversions to a restrict type
6627 // and our candidate type is a non-restrict-qualified pointer.
6628 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6629 !CandidateTy.isRestrictQualified()) {
6630 ParamTypes[0]
6631 = S.Context.getLValueReferenceType(
6632 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6633 if (NumArgs == 1)
6634 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6635 else
6636 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6637
6638 if (HasVolatile) {
6639 ParamTypes[0]
6640 = S.Context.getLValueReferenceType(
6641 S.Context.getCVRQualifiedType(CandidateTy,
6642 (Qualifiers::Volatile |
6643 Qualifiers::Restrict)));
6644 if (NumArgs == 1)
6645 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6646 CandidateSet);
6647 else
6648 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6649 }
6650 }
6651
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006652 }
6653
6654public:
6655 BuiltinOperatorOverloadBuilder(
6656 Sema &S, Expr **Args, unsigned NumArgs,
6657 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006658 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006659 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006660 OverloadCandidateSet &CandidateSet)
6661 : S(S), Args(Args), NumArgs(NumArgs),
6662 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006663 HasArithmeticOrEnumeralCandidateType(
6664 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006665 CandidateTypes(CandidateTypes),
6666 CandidateSet(CandidateSet) {
6667 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006668 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006669 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006670 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006671 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006672 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006673 assert(getArithmeticType(FirstPromotedArithmeticType)
6674 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006675 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006676 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006677 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006678 "Invalid last promoted arithmetic type");
6679 }
6680
6681 // C++ [over.built]p3:
6682 //
6683 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6684 // is either volatile or empty, there exist candidate operator
6685 // functions of the form
6686 //
6687 // VQ T& operator++(VQ T&);
6688 // T operator++(VQ T&, int);
6689 //
6690 // C++ [over.built]p4:
6691 //
6692 // For every pair (T, VQ), where T is an arithmetic type other
6693 // than bool, and VQ is either volatile or empty, there exist
6694 // candidate operator functions of the form
6695 //
6696 // VQ T& operator--(VQ T&);
6697 // T operator--(VQ T&, int);
6698 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006699 if (!HasArithmeticOrEnumeralCandidateType)
6700 return;
6701
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006702 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6703 Arith < NumArithmeticTypes; ++Arith) {
6704 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006705 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006706 VisibleTypeConversionsQuals.hasVolatile(),
6707 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006708 }
6709 }
6710
6711 // C++ [over.built]p5:
6712 //
6713 // For every pair (T, VQ), where T is a cv-qualified or
6714 // cv-unqualified object type, and VQ is either volatile or
6715 // empty, there exist candidate operator functions of the form
6716 //
6717 // T*VQ& operator++(T*VQ&);
6718 // T*VQ& operator--(T*VQ&);
6719 // T* operator++(T*VQ&, int);
6720 // T* operator--(T*VQ&, int);
6721 void addPlusPlusMinusMinusPointerOverloads() {
6722 for (BuiltinCandidateTypeSet::iterator
6723 Ptr = CandidateTypes[0].pointer_begin(),
6724 PtrEnd = CandidateTypes[0].pointer_end();
6725 Ptr != PtrEnd; ++Ptr) {
6726 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006727 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006728 continue;
6729
6730 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006731 (!(*Ptr).isVolatileQualified() &&
6732 VisibleTypeConversionsQuals.hasVolatile()),
6733 (!(*Ptr).isRestrictQualified() &&
6734 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006735 }
6736 }
6737
6738 // C++ [over.built]p6:
6739 // For every cv-qualified or cv-unqualified object type T, there
6740 // exist candidate operator functions of the form
6741 //
6742 // T& operator*(T*);
6743 //
6744 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006745 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006746 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006747 // T& operator*(T*);
6748 void addUnaryStarPointerOverloads() {
6749 for (BuiltinCandidateTypeSet::iterator
6750 Ptr = CandidateTypes[0].pointer_begin(),
6751 PtrEnd = CandidateTypes[0].pointer_end();
6752 Ptr != PtrEnd; ++Ptr) {
6753 QualType ParamTy = *Ptr;
6754 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006755 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6756 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006757
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006758 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6759 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6760 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006761
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006762 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6763 &ParamTy, Args, 1, CandidateSet);
6764 }
6765 }
6766
6767 // C++ [over.built]p9:
6768 // For every promoted arithmetic type T, there exist candidate
6769 // operator functions of the form
6770 //
6771 // T operator+(T);
6772 // T operator-(T);
6773 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006774 if (!HasArithmeticOrEnumeralCandidateType)
6775 return;
6776
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006777 for (unsigned Arith = FirstPromotedArithmeticType;
6778 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006779 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006780 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6781 }
6782
6783 // Extension: We also add these operators for vector types.
6784 for (BuiltinCandidateTypeSet::iterator
6785 Vec = CandidateTypes[0].vector_begin(),
6786 VecEnd = CandidateTypes[0].vector_end();
6787 Vec != VecEnd; ++Vec) {
6788 QualType VecTy = *Vec;
6789 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6790 }
6791 }
6792
6793 // C++ [over.built]p8:
6794 // For every type T, there exist candidate operator functions of
6795 // the form
6796 //
6797 // T* operator+(T*);
6798 void addUnaryPlusPointerOverloads() {
6799 for (BuiltinCandidateTypeSet::iterator
6800 Ptr = CandidateTypes[0].pointer_begin(),
6801 PtrEnd = CandidateTypes[0].pointer_end();
6802 Ptr != PtrEnd; ++Ptr) {
6803 QualType ParamTy = *Ptr;
6804 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6805 }
6806 }
6807
6808 // C++ [over.built]p10:
6809 // For every promoted integral type T, there exist candidate
6810 // operator functions of the form
6811 //
6812 // T operator~(T);
6813 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006814 if (!HasArithmeticOrEnumeralCandidateType)
6815 return;
6816
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006817 for (unsigned Int = FirstPromotedIntegralType;
6818 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006819 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006820 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6821 }
6822
6823 // Extension: We also add this operator for vector types.
6824 for (BuiltinCandidateTypeSet::iterator
6825 Vec = CandidateTypes[0].vector_begin(),
6826 VecEnd = CandidateTypes[0].vector_end();
6827 Vec != VecEnd; ++Vec) {
6828 QualType VecTy = *Vec;
6829 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6830 }
6831 }
6832
6833 // C++ [over.match.oper]p16:
6834 // For every pointer to member type T, there exist candidate operator
6835 // functions of the form
6836 //
6837 // bool operator==(T,T);
6838 // bool operator!=(T,T);
6839 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6840 /// Set of (canonical) types that we've already handled.
6841 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6842
6843 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6844 for (BuiltinCandidateTypeSet::iterator
6845 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6846 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6847 MemPtr != MemPtrEnd;
6848 ++MemPtr) {
6849 // Don't add the same builtin candidate twice.
6850 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6851 continue;
6852
6853 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6854 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6855 CandidateSet);
6856 }
6857 }
6858 }
6859
6860 // C++ [over.built]p15:
6861 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006862 // For every T, where T is an enumeration type, a pointer type, or
6863 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006864 //
6865 // bool operator<(T, T);
6866 // bool operator>(T, T);
6867 // bool operator<=(T, T);
6868 // bool operator>=(T, T);
6869 // bool operator==(T, T);
6870 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006871 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006872 // C++ [over.match.oper]p3:
6873 // [...]the built-in candidates include all of the candidate operator
6874 // functions defined in 13.6 that, compared to the given operator, [...]
6875 // do not have the same parameter-type-list as any non-template non-member
6876 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006877 //
Eli Friedman97c67392012-09-18 21:52:24 +00006878 // Note that in practice, this only affects enumeration types because there
6879 // aren't any built-in candidates of record type, and a user-defined operator
6880 // must have an operand of record or enumeration type. Also, the only other
6881 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006882 // cannot be overloaded for enumeration types, so this is the only place
6883 // where we must suppress candidates like this.
6884 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6885 UserDefinedBinaryOperators;
6886
6887 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6888 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6889 CandidateTypes[ArgIdx].enumeration_end()) {
6890 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6891 CEnd = CandidateSet.end();
6892 C != CEnd; ++C) {
6893 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6894 continue;
6895
Eli Friedman97c67392012-09-18 21:52:24 +00006896 if (C->Function->isFunctionTemplateSpecialization())
6897 continue;
6898
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006899 QualType FirstParamType =
6900 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6901 QualType SecondParamType =
6902 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6903
6904 // Skip if either parameter isn't of enumeral type.
6905 if (!FirstParamType->isEnumeralType() ||
6906 !SecondParamType->isEnumeralType())
6907 continue;
6908
6909 // Add this operator to the set of known user-defined operators.
6910 UserDefinedBinaryOperators.insert(
6911 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6912 S.Context.getCanonicalType(SecondParamType)));
6913 }
6914 }
6915 }
6916
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006917 /// Set of (canonical) types that we've already handled.
6918 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6919
6920 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6921 for (BuiltinCandidateTypeSet::iterator
6922 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6923 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6924 Ptr != PtrEnd; ++Ptr) {
6925 // Don't add the same builtin candidate twice.
6926 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6927 continue;
6928
6929 QualType ParamTypes[2] = { *Ptr, *Ptr };
6930 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6931 CandidateSet);
6932 }
6933 for (BuiltinCandidateTypeSet::iterator
6934 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6935 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6936 Enum != EnumEnd; ++Enum) {
6937 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6938
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006939 // Don't add the same builtin candidate twice, or if a user defined
6940 // candidate exists.
6941 if (!AddedTypes.insert(CanonType) ||
6942 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6943 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006944 continue;
6945
6946 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006947 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6948 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006949 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006950
6951 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6952 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6953 if (AddedTypes.insert(NullPtrTy) &&
6954 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6955 NullPtrTy))) {
6956 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6957 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6958 CandidateSet);
6959 }
6960 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006961 }
6962 }
6963
6964 // C++ [over.built]p13:
6965 //
6966 // For every cv-qualified or cv-unqualified object type T
6967 // there exist candidate operator functions of the form
6968 //
6969 // T* operator+(T*, ptrdiff_t);
6970 // T& operator[](T*, ptrdiff_t); [BELOW]
6971 // T* operator-(T*, ptrdiff_t);
6972 // T* operator+(ptrdiff_t, T*);
6973 // T& operator[](ptrdiff_t, T*); [BELOW]
6974 //
6975 // C++ [over.built]p14:
6976 //
6977 // For every T, where T is a pointer to object type, there
6978 // exist candidate operator functions of the form
6979 //
6980 // ptrdiff_t operator-(T, T);
6981 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6982 /// Set of (canonical) types that we've already handled.
6983 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6984
6985 for (int Arg = 0; Arg < 2; ++Arg) {
6986 QualType AsymetricParamTypes[2] = {
6987 S.Context.getPointerDiffType(),
6988 S.Context.getPointerDiffType(),
6989 };
6990 for (BuiltinCandidateTypeSet::iterator
6991 Ptr = CandidateTypes[Arg].pointer_begin(),
6992 PtrEnd = CandidateTypes[Arg].pointer_end();
6993 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006994 QualType PointeeTy = (*Ptr)->getPointeeType();
6995 if (!PointeeTy->isObjectType())
6996 continue;
6997
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006998 AsymetricParamTypes[Arg] = *Ptr;
6999 if (Arg == 0 || Op == OO_Plus) {
7000 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7001 // T* operator+(ptrdiff_t, T*);
7002 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
7003 CandidateSet);
7004 }
7005 if (Op == OO_Minus) {
7006 // ptrdiff_t operator-(T, T);
7007 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7008 continue;
7009
7010 QualType ParamTypes[2] = { *Ptr, *Ptr };
7011 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7012 Args, 2, CandidateSet);
7013 }
7014 }
7015 }
7016 }
7017
7018 // C++ [over.built]p12:
7019 //
7020 // For every pair of promoted arithmetic types L and R, there
7021 // exist candidate operator functions of the form
7022 //
7023 // LR operator*(L, R);
7024 // LR operator/(L, R);
7025 // LR operator+(L, R);
7026 // LR operator-(L, R);
7027 // bool operator<(L, R);
7028 // bool operator>(L, R);
7029 // bool operator<=(L, R);
7030 // bool operator>=(L, R);
7031 // bool operator==(L, R);
7032 // bool operator!=(L, R);
7033 //
7034 // where LR is the result of the usual arithmetic conversions
7035 // between types L and R.
7036 //
7037 // C++ [over.built]p24:
7038 //
7039 // For every pair of promoted arithmetic types L and R, there exist
7040 // candidate operator functions of the form
7041 //
7042 // LR operator?(bool, L, R);
7043 //
7044 // where LR is the result of the usual arithmetic conversions
7045 // between types L and R.
7046 // Our candidates ignore the first parameter.
7047 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007048 if (!HasArithmeticOrEnumeralCandidateType)
7049 return;
7050
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007051 for (unsigned Left = FirstPromotedArithmeticType;
7052 Left < LastPromotedArithmeticType; ++Left) {
7053 for (unsigned Right = FirstPromotedArithmeticType;
7054 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007055 QualType LandR[2] = { getArithmeticType(Left),
7056 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007057 QualType Result =
7058 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007059 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007060 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7061 }
7062 }
7063
7064 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7065 // conditional operator for vector types.
7066 for (BuiltinCandidateTypeSet::iterator
7067 Vec1 = CandidateTypes[0].vector_begin(),
7068 Vec1End = CandidateTypes[0].vector_end();
7069 Vec1 != Vec1End; ++Vec1) {
7070 for (BuiltinCandidateTypeSet::iterator
7071 Vec2 = CandidateTypes[1].vector_begin(),
7072 Vec2End = CandidateTypes[1].vector_end();
7073 Vec2 != Vec2End; ++Vec2) {
7074 QualType LandR[2] = { *Vec1, *Vec2 };
7075 QualType Result = S.Context.BoolTy;
7076 if (!isComparison) {
7077 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7078 Result = *Vec1;
7079 else
7080 Result = *Vec2;
7081 }
7082
7083 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7084 }
7085 }
7086 }
7087
7088 // C++ [over.built]p17:
7089 //
7090 // For every pair of promoted integral types L and R, there
7091 // exist candidate operator functions of the form
7092 //
7093 // LR operator%(L, R);
7094 // LR operator&(L, R);
7095 // LR operator^(L, R);
7096 // LR operator|(L, R);
7097 // L operator<<(L, R);
7098 // L operator>>(L, R);
7099 //
7100 // where LR is the result of the usual arithmetic conversions
7101 // between types L and R.
7102 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007103 if (!HasArithmeticOrEnumeralCandidateType)
7104 return;
7105
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007106 for (unsigned Left = FirstPromotedIntegralType;
7107 Left < LastPromotedIntegralType; ++Left) {
7108 for (unsigned Right = FirstPromotedIntegralType;
7109 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007110 QualType LandR[2] = { getArithmeticType(Left),
7111 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007112 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7113 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007114 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007115 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7116 }
7117 }
7118 }
7119
7120 // C++ [over.built]p20:
7121 //
7122 // For every pair (T, VQ), where T is an enumeration or
7123 // pointer to member type and VQ is either volatile or
7124 // empty, there exist candidate operator functions of the form
7125 //
7126 // VQ T& operator=(VQ T&, T);
7127 void addAssignmentMemberPointerOrEnumeralOverloads() {
7128 /// Set of (canonical) types that we've already handled.
7129 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7130
7131 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7132 for (BuiltinCandidateTypeSet::iterator
7133 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7134 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7135 Enum != EnumEnd; ++Enum) {
7136 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7137 continue;
7138
7139 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7140 CandidateSet);
7141 }
7142
7143 for (BuiltinCandidateTypeSet::iterator
7144 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7145 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7146 MemPtr != MemPtrEnd; ++MemPtr) {
7147 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7148 continue;
7149
7150 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7151 CandidateSet);
7152 }
7153 }
7154 }
7155
7156 // C++ [over.built]p19:
7157 //
7158 // For every pair (T, VQ), where T is any type and VQ is either
7159 // volatile or empty, there exist candidate operator functions
7160 // of the form
7161 //
7162 // T*VQ& operator=(T*VQ&, T*);
7163 //
7164 // C++ [over.built]p21:
7165 //
7166 // For every pair (T, VQ), where T is a cv-qualified or
7167 // cv-unqualified object type and VQ is either volatile or
7168 // empty, there exist candidate operator functions of the form
7169 //
7170 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7171 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7172 void addAssignmentPointerOverloads(bool isEqualOp) {
7173 /// Set of (canonical) types that we've already handled.
7174 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7175
7176 for (BuiltinCandidateTypeSet::iterator
7177 Ptr = CandidateTypes[0].pointer_begin(),
7178 PtrEnd = CandidateTypes[0].pointer_end();
7179 Ptr != PtrEnd; ++Ptr) {
7180 // If this is operator=, keep track of the builtin candidates we added.
7181 if (isEqualOp)
7182 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007183 else if (!(*Ptr)->getPointeeType()->isObjectType())
7184 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007185
7186 // non-volatile version
7187 QualType ParamTypes[2] = {
7188 S.Context.getLValueReferenceType(*Ptr),
7189 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7190 };
7191 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7192 /*IsAssigmentOperator=*/ isEqualOp);
7193
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007194 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7195 VisibleTypeConversionsQuals.hasVolatile();
7196 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007197 // volatile version
7198 ParamTypes[0] =
7199 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7200 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7201 /*IsAssigmentOperator=*/isEqualOp);
7202 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007203
7204 if (!(*Ptr).isRestrictQualified() &&
7205 VisibleTypeConversionsQuals.hasRestrict()) {
7206 // restrict version
7207 ParamTypes[0]
7208 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7209 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7210 /*IsAssigmentOperator=*/isEqualOp);
7211
7212 if (NeedVolatile) {
7213 // volatile restrict version
7214 ParamTypes[0]
7215 = S.Context.getLValueReferenceType(
7216 S.Context.getCVRQualifiedType(*Ptr,
7217 (Qualifiers::Volatile |
7218 Qualifiers::Restrict)));
7219 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7220 CandidateSet,
7221 /*IsAssigmentOperator=*/isEqualOp);
7222 }
7223 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007224 }
7225
7226 if (isEqualOp) {
7227 for (BuiltinCandidateTypeSet::iterator
7228 Ptr = CandidateTypes[1].pointer_begin(),
7229 PtrEnd = CandidateTypes[1].pointer_end();
7230 Ptr != PtrEnd; ++Ptr) {
7231 // Make sure we don't add the same candidate twice.
7232 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7233 continue;
7234
Chandler Carruth6df868e2010-12-12 08:17:55 +00007235 QualType ParamTypes[2] = {
7236 S.Context.getLValueReferenceType(*Ptr),
7237 *Ptr,
7238 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007239
7240 // non-volatile version
7241 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7242 /*IsAssigmentOperator=*/true);
7243
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007244 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7245 VisibleTypeConversionsQuals.hasVolatile();
7246 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007247 // volatile version
7248 ParamTypes[0] =
7249 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007250 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7251 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007252 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007253
7254 if (!(*Ptr).isRestrictQualified() &&
7255 VisibleTypeConversionsQuals.hasRestrict()) {
7256 // restrict version
7257 ParamTypes[0]
7258 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7260 CandidateSet, /*IsAssigmentOperator=*/true);
7261
7262 if (NeedVolatile) {
7263 // volatile restrict version
7264 ParamTypes[0]
7265 = S.Context.getLValueReferenceType(
7266 S.Context.getCVRQualifiedType(*Ptr,
7267 (Qualifiers::Volatile |
7268 Qualifiers::Restrict)));
7269 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7270 CandidateSet, /*IsAssigmentOperator=*/true);
7271
7272 }
7273 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007274 }
7275 }
7276 }
7277
7278 // C++ [over.built]p18:
7279 //
7280 // For every triple (L, VQ, R), where L is an arithmetic type,
7281 // VQ is either volatile or empty, and R is a promoted
7282 // arithmetic type, there exist candidate operator functions of
7283 // the form
7284 //
7285 // VQ L& operator=(VQ L&, R);
7286 // VQ L& operator*=(VQ L&, R);
7287 // VQ L& operator/=(VQ L&, R);
7288 // VQ L& operator+=(VQ L&, R);
7289 // VQ L& operator-=(VQ L&, R);
7290 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007291 if (!HasArithmeticOrEnumeralCandidateType)
7292 return;
7293
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007294 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7295 for (unsigned Right = FirstPromotedArithmeticType;
7296 Right < LastPromotedArithmeticType; ++Right) {
7297 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007298 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007299
7300 // Add this built-in operator as a candidate (VQ is empty).
7301 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007302 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007303 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7304 /*IsAssigmentOperator=*/isEqualOp);
7305
7306 // Add this built-in operator as a candidate (VQ is 'volatile').
7307 if (VisibleTypeConversionsQuals.hasVolatile()) {
7308 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007309 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007310 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7312 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007313 /*IsAssigmentOperator=*/isEqualOp);
7314 }
7315 }
7316 }
7317
7318 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7319 for (BuiltinCandidateTypeSet::iterator
7320 Vec1 = CandidateTypes[0].vector_begin(),
7321 Vec1End = CandidateTypes[0].vector_end();
7322 Vec1 != Vec1End; ++Vec1) {
7323 for (BuiltinCandidateTypeSet::iterator
7324 Vec2 = CandidateTypes[1].vector_begin(),
7325 Vec2End = CandidateTypes[1].vector_end();
7326 Vec2 != Vec2End; ++Vec2) {
7327 QualType ParamTypes[2];
7328 ParamTypes[1] = *Vec2;
7329 // Add this built-in operator as a candidate (VQ is empty).
7330 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7331 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7332 /*IsAssigmentOperator=*/isEqualOp);
7333
7334 // Add this built-in operator as a candidate (VQ is 'volatile').
7335 if (VisibleTypeConversionsQuals.hasVolatile()) {
7336 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7337 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007338 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7339 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007340 /*IsAssigmentOperator=*/isEqualOp);
7341 }
7342 }
7343 }
7344 }
7345
7346 // C++ [over.built]p22:
7347 //
7348 // For every triple (L, VQ, R), where L is an integral type, VQ
7349 // is either volatile or empty, and R is a promoted integral
7350 // type, there exist candidate operator functions of the form
7351 //
7352 // VQ L& operator%=(VQ L&, R);
7353 // VQ L& operator<<=(VQ L&, R);
7354 // VQ L& operator>>=(VQ L&, R);
7355 // VQ L& operator&=(VQ L&, R);
7356 // VQ L& operator^=(VQ L&, R);
7357 // VQ L& operator|=(VQ L&, R);
7358 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007359 if (!HasArithmeticOrEnumeralCandidateType)
7360 return;
7361
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007362 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7363 for (unsigned Right = FirstPromotedIntegralType;
7364 Right < LastPromotedIntegralType; ++Right) {
7365 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007366 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007367
7368 // Add this built-in operator as a candidate (VQ is empty).
7369 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007370 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007371 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7372 if (VisibleTypeConversionsQuals.hasVolatile()) {
7373 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007374 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007375 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7376 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7377 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7378 CandidateSet);
7379 }
7380 }
7381 }
7382 }
7383
7384 // C++ [over.operator]p23:
7385 //
7386 // There also exist candidate operator functions of the form
7387 //
7388 // bool operator!(bool);
7389 // bool operator&&(bool, bool);
7390 // bool operator||(bool, bool);
7391 void addExclaimOverload() {
7392 QualType ParamTy = S.Context.BoolTy;
7393 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7394 /*IsAssignmentOperator=*/false,
7395 /*NumContextualBoolArguments=*/1);
7396 }
7397 void addAmpAmpOrPipePipeOverload() {
7398 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7399 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7400 /*IsAssignmentOperator=*/false,
7401 /*NumContextualBoolArguments=*/2);
7402 }
7403
7404 // C++ [over.built]p13:
7405 //
7406 // For every cv-qualified or cv-unqualified object type T there
7407 // exist candidate operator functions of the form
7408 //
7409 // T* operator+(T*, ptrdiff_t); [ABOVE]
7410 // T& operator[](T*, ptrdiff_t);
7411 // T* operator-(T*, ptrdiff_t); [ABOVE]
7412 // T* operator+(ptrdiff_t, T*); [ABOVE]
7413 // T& operator[](ptrdiff_t, T*);
7414 void addSubscriptOverloads() {
7415 for (BuiltinCandidateTypeSet::iterator
7416 Ptr = CandidateTypes[0].pointer_begin(),
7417 PtrEnd = CandidateTypes[0].pointer_end();
7418 Ptr != PtrEnd; ++Ptr) {
7419 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7420 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007421 if (!PointeeType->isObjectType())
7422 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007423
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007424 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7425
7426 // T& operator[](T*, ptrdiff_t)
7427 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7428 }
7429
7430 for (BuiltinCandidateTypeSet::iterator
7431 Ptr = CandidateTypes[1].pointer_begin(),
7432 PtrEnd = CandidateTypes[1].pointer_end();
7433 Ptr != PtrEnd; ++Ptr) {
7434 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7435 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007436 if (!PointeeType->isObjectType())
7437 continue;
7438
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007439 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7440
7441 // T& operator[](ptrdiff_t, T*)
7442 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7443 }
7444 }
7445
7446 // C++ [over.built]p11:
7447 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7448 // C1 is the same type as C2 or is a derived class of C2, T is an object
7449 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7450 // there exist candidate operator functions of the form
7451 //
7452 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7453 //
7454 // where CV12 is the union of CV1 and CV2.
7455 void addArrowStarOverloads() {
7456 for (BuiltinCandidateTypeSet::iterator
7457 Ptr = CandidateTypes[0].pointer_begin(),
7458 PtrEnd = CandidateTypes[0].pointer_end();
7459 Ptr != PtrEnd; ++Ptr) {
7460 QualType C1Ty = (*Ptr);
7461 QualType C1;
7462 QualifierCollector Q1;
7463 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7464 if (!isa<RecordType>(C1))
7465 continue;
7466 // heuristic to reduce number of builtin candidates in the set.
7467 // Add volatile/restrict version only if there are conversions to a
7468 // volatile/restrict type.
7469 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7470 continue;
7471 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7472 continue;
7473 for (BuiltinCandidateTypeSet::iterator
7474 MemPtr = CandidateTypes[1].member_pointer_begin(),
7475 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7476 MemPtr != MemPtrEnd; ++MemPtr) {
7477 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7478 QualType C2 = QualType(mptr->getClass(), 0);
7479 C2 = C2.getUnqualifiedType();
7480 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7481 break;
7482 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7483 // build CV12 T&
7484 QualType T = mptr->getPointeeType();
7485 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7486 T.isVolatileQualified())
7487 continue;
7488 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7489 T.isRestrictQualified())
7490 continue;
7491 T = Q1.apply(S.Context, T);
7492 QualType ResultTy = S.Context.getLValueReferenceType(T);
7493 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7494 }
7495 }
7496 }
7497
7498 // Note that we don't consider the first argument, since it has been
7499 // contextually converted to bool long ago. The candidates below are
7500 // therefore added as binary.
7501 //
7502 // C++ [over.built]p25:
7503 // For every type T, where T is a pointer, pointer-to-member, or scoped
7504 // enumeration type, there exist candidate operator functions of the form
7505 //
7506 // T operator?(bool, T, T);
7507 //
7508 void addConditionalOperatorOverloads() {
7509 /// Set of (canonical) types that we've already handled.
7510 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7511
7512 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7513 for (BuiltinCandidateTypeSet::iterator
7514 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7515 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7516 Ptr != PtrEnd; ++Ptr) {
7517 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7518 continue;
7519
7520 QualType ParamTypes[2] = { *Ptr, *Ptr };
7521 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7522 }
7523
7524 for (BuiltinCandidateTypeSet::iterator
7525 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7526 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7527 MemPtr != MemPtrEnd; ++MemPtr) {
7528 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7529 continue;
7530
7531 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7532 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7533 }
7534
Richard Smith80ad52f2013-01-02 11:42:31 +00007535 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007536 for (BuiltinCandidateTypeSet::iterator
7537 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7538 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7539 Enum != EnumEnd; ++Enum) {
7540 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7541 continue;
7542
7543 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7544 continue;
7545
7546 QualType ParamTypes[2] = { *Enum, *Enum };
7547 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7548 }
7549 }
7550 }
7551 }
7552};
7553
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007554} // end anonymous namespace
7555
7556/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7557/// operator overloads to the candidate set (C++ [over.built]), based
7558/// on the operator @p Op and the arguments given. For example, if the
7559/// operator is a binary '+', this routine might add "int
7560/// operator+(int, int)" to cover integer addition.
7561void
7562Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7563 SourceLocation OpLoc,
7564 Expr **Args, unsigned NumArgs,
7565 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007566 // Find all of the types that the arguments can convert to, but only
7567 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007568 // that make use of these types. Also record whether we encounter non-record
7569 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007570 Qualifiers VisibleTypeConversionsQuals;
7571 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007572 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7573 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007574
7575 bool HasNonRecordCandidateType = false;
7576 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007577 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007578 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7579 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7580 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7581 OpLoc,
7582 true,
7583 (Op == OO_Exclaim ||
7584 Op == OO_AmpAmp ||
7585 Op == OO_PipePipe),
7586 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007587 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7588 CandidateTypes[ArgIdx].hasNonRecordTypes();
7589 HasArithmeticOrEnumeralCandidateType =
7590 HasArithmeticOrEnumeralCandidateType ||
7591 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007592 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007593
Chandler Carruth6a577462010-12-13 01:44:01 +00007594 // Exit early when no non-record types have been added to the candidate set
7595 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007596 //
7597 // We can't exit early for !, ||, or &&, since there we have always have
7598 // 'bool' overloads.
7599 if (!HasNonRecordCandidateType &&
7600 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007601 return;
7602
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007603 // Setup an object to manage the common state for building overloads.
7604 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7605 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007606 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007607 CandidateTypes, CandidateSet);
7608
7609 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007610 switch (Op) {
7611 case OO_None:
7612 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007613 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007614
Chandler Carruthabb71842010-12-12 08:51:33 +00007615 case OO_New:
7616 case OO_Delete:
7617 case OO_Array_New:
7618 case OO_Array_Delete:
7619 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007620 llvm_unreachable(
7621 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007622
7623 case OO_Comma:
7624 case OO_Arrow:
7625 // C++ [over.match.oper]p3:
7626 // -- For the operator ',', the unary operator '&', or the
7627 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007628 break;
7629
7630 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007631 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007633 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007634
7635 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007636 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007637 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007638 } else {
7639 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7640 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7641 }
Douglas Gregor74253732008-11-19 15:42:04 +00007642 break;
7643
Chandler Carruthabb71842010-12-12 08:51:33 +00007644 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007645 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007646 OpBuilder.addUnaryStarPointerOverloads();
7647 else
7648 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7649 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007650
Chandler Carruthabb71842010-12-12 08:51:33 +00007651 case OO_Slash:
7652 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007653 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007654
7655 case OO_PlusPlus:
7656 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007657 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7658 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007659 break;
7660
Douglas Gregor19b7b152009-08-24 13:43:27 +00007661 case OO_EqualEqual:
7662 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007663 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007664 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007665
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007666 case OO_Less:
7667 case OO_Greater:
7668 case OO_LessEqual:
7669 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007670 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007671 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7672 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007673
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007674 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007675 case OO_Caret:
7676 case OO_Pipe:
7677 case OO_LessLess:
7678 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007679 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007680 break;
7681
Chandler Carruthabb71842010-12-12 08:51:33 +00007682 case OO_Amp: // '&' is either unary or binary
7683 if (NumArgs == 1)
7684 // C++ [over.match.oper]p3:
7685 // -- For the operator ',', the unary operator '&', or the
7686 // operator '->', the built-in candidates set is empty.
7687 break;
7688
7689 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7690 break;
7691
7692 case OO_Tilde:
7693 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7694 break;
7695
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007696 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007697 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007698 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007699
7700 case OO_PlusEqual:
7701 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007702 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007703 // Fall through.
7704
7705 case OO_StarEqual:
7706 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007707 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007708 break;
7709
7710 case OO_PercentEqual:
7711 case OO_LessLessEqual:
7712 case OO_GreaterGreaterEqual:
7713 case OO_AmpEqual:
7714 case OO_CaretEqual:
7715 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007716 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007717 break;
7718
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007719 case OO_Exclaim:
7720 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007721 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007722
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007723 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007724 case OO_PipePipe:
7725 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007726 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007727
7728 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007729 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007730 break;
7731
7732 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007733 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007734 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007735
7736 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007737 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007738 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7739 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007740 }
7741}
7742
Douglas Gregorfa047642009-02-04 00:32:51 +00007743/// \brief Add function candidates found via argument-dependent lookup
7744/// to the set of overloading candidates.
7745///
7746/// This routine performs argument-dependent name lookup based on the
7747/// given function name (which may also be an operator name) and adds
7748/// all of the overload candidates found by ADL to the overload
7749/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007750void
Douglas Gregorfa047642009-02-04 00:32:51 +00007751Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007752 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007753 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007754 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007755 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007756 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007757 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007758
John McCalla113e722010-01-26 06:04:06 +00007759 // FIXME: This approach for uniquing ADL results (and removing
7760 // redundant candidates from the set) relies on pointer-equality,
7761 // which means we need to key off the canonical decl. However,
7762 // always going back to the canonical decl might not get us the
7763 // right set of default arguments. What default arguments are
7764 // we supposed to consider on ADL candidates, anyway?
7765
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007766 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007767 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007768
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007769 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007770 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7771 CandEnd = CandidateSet.end();
7772 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007773 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007774 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007775 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007776 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007777 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007778
7779 // For each of the ADL candidates we found, add it to the overload
7780 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007781 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007782 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007783 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007784 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007785 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007786
Ahmed Charles13a140c2012-02-25 11:00:22 +00007787 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7788 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007789 } else
John McCall6e266892010-01-26 03:27:55 +00007790 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007791 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007792 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007793 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007794}
7795
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007796/// isBetterOverloadCandidate - Determines whether the first overload
7797/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007798bool
John McCall120d63c2010-08-24 20:38:10 +00007799isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007800 const OverloadCandidate &Cand1,
7801 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007802 SourceLocation Loc,
7803 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007804 // Define viable functions to be better candidates than non-viable
7805 // functions.
7806 if (!Cand2.Viable)
7807 return Cand1.Viable;
7808 else if (!Cand1.Viable)
7809 return false;
7810
Douglas Gregor88a35142008-12-22 05:46:06 +00007811 // C++ [over.match.best]p1:
7812 //
7813 // -- if F is a static member function, ICS1(F) is defined such
7814 // that ICS1(F) is neither better nor worse than ICS1(G) for
7815 // any function G, and, symmetrically, ICS1(G) is neither
7816 // better nor worse than ICS1(F).
7817 unsigned StartArg = 0;
7818 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7819 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007820
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007821 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007822 // A viable function F1 is defined to be a better function than another
7823 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007824 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007825 unsigned NumArgs = Cand1.NumConversions;
7826 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007827 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007828 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007829 switch (CompareImplicitConversionSequences(S,
7830 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007831 Cand2.Conversions[ArgIdx])) {
7832 case ImplicitConversionSequence::Better:
7833 // Cand1 has a better conversion sequence.
7834 HasBetterConversion = true;
7835 break;
7836
7837 case ImplicitConversionSequence::Worse:
7838 // Cand1 can't be better than Cand2.
7839 return false;
7840
7841 case ImplicitConversionSequence::Indistinguishable:
7842 // Do nothing.
7843 break;
7844 }
7845 }
7846
Mike Stump1eb44332009-09-09 15:08:12 +00007847 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007848 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007849 if (HasBetterConversion)
7850 return true;
7851
Mike Stump1eb44332009-09-09 15:08:12 +00007852 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007853 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007854 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007855 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7856 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007857
7858 // -- F1 and F2 are function template specializations, and the function
7859 // template for F1 is more specialized than the template for F2
7860 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007861 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007862 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007863 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007864 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007865 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7866 Cand2.Function->getPrimaryTemplate(),
7867 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007868 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007869 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007870 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007871 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007873
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007874 // -- the context is an initialization by user-defined conversion
7875 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7876 // from the return type of F1 to the destination type (i.e.,
7877 // the type of the entity being initialized) is a better
7878 // conversion sequence than the standard conversion sequence
7879 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007880 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007881 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007882 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007883 // First check whether we prefer one of the conversion functions over the
7884 // other. This only distinguishes the results in non-standard, extension
7885 // cases such as the conversion from a lambda closure type to a function
7886 // pointer or block.
7887 ImplicitConversionSequence::CompareKind FuncResult
7888 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7889 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7890 return FuncResult;
7891
John McCall120d63c2010-08-24 20:38:10 +00007892 switch (CompareStandardConversionSequences(S,
7893 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007894 Cand2.FinalConversion)) {
7895 case ImplicitConversionSequence::Better:
7896 // Cand1 has a better conversion sequence.
7897 return true;
7898
7899 case ImplicitConversionSequence::Worse:
7900 // Cand1 can't be better than Cand2.
7901 return false;
7902
7903 case ImplicitConversionSequence::Indistinguishable:
7904 // Do nothing
7905 break;
7906 }
7907 }
7908
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007909 return false;
7910}
7911
Mike Stump1eb44332009-09-09 15:08:12 +00007912/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007913/// within an overload candidate set.
7914///
James Dennettefce31f2012-06-22 08:10:18 +00007915/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007916/// which overload resolution occurs.
7917///
James Dennettefce31f2012-06-22 08:10:18 +00007918/// \param Best If overload resolution was successful or found a deleted
7919/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007920///
7921/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007922OverloadingResult
7923OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007924 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007925 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007926 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007927 Best = end();
7928 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7929 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007930 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007931 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007932 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007933 }
7934
7935 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007936 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007937 return OR_No_Viable_Function;
7938
7939 // Make sure that this function is better than every other viable
7940 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007941 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007942 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007943 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007944 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007945 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007946 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007947 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007948 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007949 }
Mike Stump1eb44332009-09-09 15:08:12 +00007950
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007951 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007952 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007953 (Best->Function->isDeleted() ||
7954 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007955 return OR_Deleted;
7956
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007957 return OR_Success;
7958}
7959
John McCall3c80f572010-01-12 02:15:36 +00007960namespace {
7961
7962enum OverloadCandidateKind {
7963 oc_function,
7964 oc_method,
7965 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007966 oc_function_template,
7967 oc_method_template,
7968 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007969 oc_implicit_default_constructor,
7970 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007971 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007972 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007973 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007974 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007975};
7976
John McCall220ccbf2010-01-13 00:25:19 +00007977OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7978 FunctionDecl *Fn,
7979 std::string &Description) {
7980 bool isTemplate = false;
7981
7982 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7983 isTemplate = true;
7984 Description = S.getTemplateArgumentBindingsText(
7985 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7986 }
John McCallb1622a12010-01-06 09:43:14 +00007987
7988 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007989 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007990 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007991
Sebastian Redlf677ea32011-02-05 19:23:19 +00007992 if (Ctor->getInheritedConstructor())
7993 return oc_implicit_inherited_constructor;
7994
Sean Hunt82713172011-05-25 23:16:36 +00007995 if (Ctor->isDefaultConstructor())
7996 return oc_implicit_default_constructor;
7997
7998 if (Ctor->isMoveConstructor())
7999 return oc_implicit_move_constructor;
8000
8001 assert(Ctor->isCopyConstructor() &&
8002 "unexpected sort of implicit constructor");
8003 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008004 }
8005
8006 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8007 // This actually gets spelled 'candidate function' for now, but
8008 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008009 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008010 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008011
Sean Hunt82713172011-05-25 23:16:36 +00008012 if (Meth->isMoveAssignmentOperator())
8013 return oc_implicit_move_assignment;
8014
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008015 if (Meth->isCopyAssignmentOperator())
8016 return oc_implicit_copy_assignment;
8017
8018 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8019 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008020 }
8021
John McCall220ccbf2010-01-13 00:25:19 +00008022 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008023}
8024
Sebastian Redlf677ea32011-02-05 19:23:19 +00008025void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8026 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8027 if (!Ctor) return;
8028
8029 Ctor = Ctor->getInheritedConstructor();
8030 if (!Ctor) return;
8031
8032 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8033}
8034
John McCall3c80f572010-01-12 02:15:36 +00008035} // end anonymous namespace
8036
8037// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008038void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008039 std::string FnDesc;
8040 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008041 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8042 << (unsigned) K << FnDesc;
8043 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8044 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008045 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008046}
8047
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008048//Notes the location of all overload candidates designated through
8049// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008050void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008051 assert(OverloadedExpr->getType() == Context.OverloadTy);
8052
8053 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8054 OverloadExpr *OvlExpr = Ovl.Expression;
8055
8056 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8057 IEnd = OvlExpr->decls_end();
8058 I != IEnd; ++I) {
8059 if (FunctionTemplateDecl *FunTmpl =
8060 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008061 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008062 } else if (FunctionDecl *Fun
8063 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008064 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008065 }
8066 }
8067}
8068
John McCall1d318332010-01-12 00:44:57 +00008069/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8070/// "lead" diagnostic; it will be given two arguments, the source and
8071/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008072void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8073 Sema &S,
8074 SourceLocation CaretLoc,
8075 const PartialDiagnostic &PDiag) const {
8076 S.Diag(CaretLoc, PDiag)
8077 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008078 // FIXME: The note limiting machinery is borrowed from
8079 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8080 // refactoring here.
8081 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8082 unsigned CandsShown = 0;
8083 AmbiguousConversionSequence::const_iterator I, E;
8084 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8085 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8086 break;
8087 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008088 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008089 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008090 if (I != E)
8091 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008092}
8093
John McCall1d318332010-01-12 00:44:57 +00008094namespace {
8095
John McCalladbb8f82010-01-13 09:16:55 +00008096void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8097 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8098 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008099 assert(Cand->Function && "for now, candidate must be a function");
8100 FunctionDecl *Fn = Cand->Function;
8101
8102 // There's a conversion slot for the object argument if this is a
8103 // non-constructor method. Note that 'I' corresponds the
8104 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008105 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008106 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008107 if (I == 0)
8108 isObjectArgument = true;
8109 else
8110 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008111 }
8112
John McCall220ccbf2010-01-13 00:25:19 +00008113 std::string FnDesc;
8114 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8115
John McCalladbb8f82010-01-13 09:16:55 +00008116 Expr *FromExpr = Conv.Bad.FromExpr;
8117 QualType FromTy = Conv.Bad.getFromType();
8118 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008119
John McCall5920dbb2010-02-02 02:42:52 +00008120 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008121 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008122 Expr *E = FromExpr->IgnoreParens();
8123 if (isa<UnaryOperator>(E))
8124 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008125 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008126
8127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8128 << (unsigned) FnKind << FnDesc
8129 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8130 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008131 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008132 return;
8133 }
8134
John McCall258b2032010-01-23 08:10:49 +00008135 // Do some hand-waving analysis to see if the non-viability is due
8136 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008137 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8138 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8139 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8140 CToTy = RT->getPointeeType();
8141 else {
8142 // TODO: detect and diagnose the full richness of const mismatches.
8143 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8144 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8145 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8146 }
8147
8148 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8149 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008150 Qualifiers FromQs = CFromTy.getQualifiers();
8151 Qualifiers ToQs = CToTy.getQualifiers();
8152
8153 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8155 << (unsigned) FnKind << FnDesc
8156 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8157 << FromTy
8158 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8159 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008160 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008161 return;
8162 }
8163
John McCallf85e1932011-06-15 23:02:42 +00008164 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008166 << (unsigned) FnKind << FnDesc
8167 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8168 << FromTy
8169 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8170 << (unsigned) isObjectArgument << I+1;
8171 MaybeEmitInheritedConstructorNote(S, Fn);
8172 return;
8173 }
8174
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008175 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8177 << (unsigned) FnKind << FnDesc
8178 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8179 << FromTy
8180 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8181 << (unsigned) isObjectArgument << I+1;
8182 MaybeEmitInheritedConstructorNote(S, Fn);
8183 return;
8184 }
8185
John McCall651f3ee2010-01-14 03:28:57 +00008186 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8187 assert(CVR && "unexpected qualifiers mismatch");
8188
8189 if (isObjectArgument) {
8190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8191 << (unsigned) FnKind << FnDesc
8192 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8193 << FromTy << (CVR - 1);
8194 } else {
8195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8196 << (unsigned) FnKind << FnDesc
8197 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8198 << FromTy << (CVR - 1) << I+1;
8199 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008200 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008201 return;
8202 }
8203
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008204 // Special diagnostic for failure to convert an initializer list, since
8205 // telling the user that it has type void is not useful.
8206 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8207 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8208 << (unsigned) FnKind << FnDesc
8209 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8210 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8211 MaybeEmitInheritedConstructorNote(S, Fn);
8212 return;
8213 }
8214
John McCall258b2032010-01-23 08:10:49 +00008215 // Diagnose references or pointers to incomplete types differently,
8216 // since it's far from impossible that the incompleteness triggered
8217 // the failure.
8218 QualType TempFromTy = FromTy.getNonReferenceType();
8219 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8220 TempFromTy = PTy->getPointeeType();
8221 if (TempFromTy->isIncompleteType()) {
8222 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8223 << (unsigned) FnKind << FnDesc
8224 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8225 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008226 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008227 return;
8228 }
8229
Douglas Gregor85789812010-06-30 23:01:39 +00008230 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008231 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008232 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8233 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8234 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8235 FromPtrTy->getPointeeType()) &&
8236 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8237 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008238 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008239 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008240 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008241 }
8242 } else if (const ObjCObjectPointerType *FromPtrTy
8243 = FromTy->getAs<ObjCObjectPointerType>()) {
8244 if (const ObjCObjectPointerType *ToPtrTy
8245 = ToTy->getAs<ObjCObjectPointerType>())
8246 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8247 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8248 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8249 FromPtrTy->getPointeeType()) &&
8250 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008251 BaseToDerivedConversion = 2;
8252 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008253 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8254 !FromTy->isIncompleteType() &&
8255 !ToRefTy->getPointeeType()->isIncompleteType() &&
8256 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8257 BaseToDerivedConversion = 3;
8258 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8259 ToTy.getNonReferenceType().getCanonicalType() ==
8260 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008261 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8262 << (unsigned) FnKind << FnDesc
8263 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8264 << (unsigned) isObjectArgument << I + 1;
8265 MaybeEmitInheritedConstructorNote(S, Fn);
8266 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008267 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008269
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008270 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008271 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008272 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008273 << (unsigned) FnKind << FnDesc
8274 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008275 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008276 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008277 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008278 return;
8279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008280
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008281 if (isa<ObjCObjectPointerType>(CFromTy) &&
8282 isa<PointerType>(CToTy)) {
8283 Qualifiers FromQs = CFromTy.getQualifiers();
8284 Qualifiers ToQs = CToTy.getQualifiers();
8285 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8287 << (unsigned) FnKind << FnDesc
8288 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8289 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8290 MaybeEmitInheritedConstructorNote(S, Fn);
8291 return;
8292 }
8293 }
8294
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008295 // Emit the generic diagnostic and, optionally, add the hints to it.
8296 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8297 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008298 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008299 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8300 << (unsigned) (Cand->Fix.Kind);
8301
8302 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008303 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8304 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008305 FDiag << *HI;
8306 S.Diag(Fn->getLocation(), FDiag);
8307
Sebastian Redlf677ea32011-02-05 19:23:19 +00008308 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008309}
8310
8311void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8312 unsigned NumFormalArgs) {
8313 // TODO: treat calls to a missing default constructor as a special case
8314
8315 FunctionDecl *Fn = Cand->Function;
8316 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8317
8318 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008319
Douglas Gregor439d3c32011-05-05 00:13:13 +00008320 // With invalid overloaded operators, it's possible that we think we
8321 // have an arity mismatch when it fact it looks like we have the
8322 // right number of arguments, because only overloaded operators have
8323 // the weird behavior of overloading member and non-member functions.
8324 // Just don't report anything.
8325 if (Fn->isInvalidDecl() &&
8326 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8327 return;
8328
John McCalladbb8f82010-01-13 09:16:55 +00008329 // at least / at most / exactly
8330 unsigned mode, modeCount;
8331 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008332 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8333 (Cand->FailureKind == ovl_fail_bad_deduction &&
8334 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008335 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008336 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008337 mode = 0; // "at least"
8338 else
8339 mode = 2; // "exactly"
8340 modeCount = MinParams;
8341 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008342 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8343 (Cand->FailureKind == ovl_fail_bad_deduction &&
8344 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008345 if (MinParams != FnTy->getNumArgs())
8346 mode = 1; // "at most"
8347 else
8348 mode = 2; // "exactly"
8349 modeCount = FnTy->getNumArgs();
8350 }
8351
8352 std::string Description;
8353 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8354
Richard Smithf7b80562012-05-11 05:16:41 +00008355 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8356 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8357 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8358 << Fn->getParamDecl(0) << NumFormalArgs;
8359 else
8360 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8361 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8362 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008363 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008364}
8365
John McCall342fec42010-02-01 18:53:26 +00008366/// Diagnose a failed template-argument deduction.
8367void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008368 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008369 FunctionDecl *Fn = Cand->Function; // pattern
8370
Douglas Gregora9333192010-05-08 17:41:32 +00008371 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008372 NamedDecl *ParamD;
8373 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8374 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8375 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008376 switch (Cand->DeductionFailure.Result) {
8377 case Sema::TDK_Success:
8378 llvm_unreachable("TDK_success while diagnosing bad deduction");
8379
8380 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008381 assert(ParamD && "no parameter found for incomplete deduction result");
8382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8383 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008384 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008385 return;
8386 }
8387
John McCall57e97782010-08-05 09:05:08 +00008388 case Sema::TDK_Underqualified: {
8389 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8390 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8391
8392 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8393
8394 // Param will have been canonicalized, but it should just be a
8395 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008396 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008397 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008398 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008399 assert(S.Context.hasSameType(Param, NonCanonParam));
8400
8401 // Arg has also been canonicalized, but there's nothing we can do
8402 // about that. It also doesn't matter as much, because it won't
8403 // have any template parameters in it (because deduction isn't
8404 // done on dependent types).
8405 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8406
8407 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8408 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008409 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008410 return;
8411 }
8412
8413 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008414 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008415 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008416 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008417 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008418 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008419 which = 1;
8420 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008421 which = 2;
8422 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008423
Douglas Gregora9333192010-05-08 17:41:32 +00008424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008425 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008426 << *Cand->DeductionFailure.getFirstArg()
8427 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008428 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008429 return;
8430 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008431
Douglas Gregorf1a84452010-05-08 19:15:54 +00008432 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008433 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008434 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008435 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008436 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8437 << ParamD->getDeclName();
8438 else {
8439 int index = 0;
8440 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8441 index = TTP->getIndex();
8442 else if (NonTypeTemplateParmDecl *NTTP
8443 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8444 index = NTTP->getIndex();
8445 else
8446 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008447 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008448 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8449 << (index + 1);
8450 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008451 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008452 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008453
Douglas Gregora18592e2010-05-08 18:13:28 +00008454 case Sema::TDK_TooManyArguments:
8455 case Sema::TDK_TooFewArguments:
8456 DiagnoseArityMismatch(S, Cand, NumArgs);
8457 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008458
8459 case Sema::TDK_InstantiationDepth:
8460 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008461 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008462 return;
8463
8464 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008465 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008466 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008467 if (TemplateArgumentList *Args =
8468 Cand->DeductionFailure.getTemplateArgumentList()) {
8469 TemplateArgString = " ";
8470 TemplateArgString += S.getTemplateArgumentBindingsText(
8471 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8472 }
8473
Richard Smith4493c0a2012-05-09 05:17:00 +00008474 // If this candidate was disabled by enable_if, say so.
8475 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8476 if (PDiag && PDiag->second.getDiagID() ==
8477 diag::err_typename_nested_not_found_enable_if) {
8478 // FIXME: Use the source range of the condition, and the fully-qualified
8479 // name of the enable_if template. These are both present in PDiag.
8480 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8481 << "'enable_if'" << TemplateArgString;
8482 return;
8483 }
8484
Richard Smithb8590f32012-05-07 09:03:25 +00008485 // Format the SFINAE diagnostic into the argument string.
8486 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8487 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008488 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008489 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008490 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008491 SFINAEArgString = ": ";
8492 R = SourceRange(PDiag->first, PDiag->first);
8493 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8494 }
8495
Douglas Gregorec20f462010-05-08 20:07:26 +00008496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008497 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008498 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008499 return;
8500 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008501
Richard Smith0efa62f2013-01-31 04:03:12 +00008502 case Sema::TDK_FailedOverloadResolution: {
8503 OverloadExpr::FindResult R =
8504 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8505 S.Diag(Fn->getLocation(),
8506 diag::note_ovl_candidate_failed_overload_resolution)
8507 << R.Expression->getName();
8508 return;
8509 }
8510
Richard Smith29805ca2013-01-31 05:19:49 +00008511 case Sema::TDK_NonDeducedMismatch:
8512 // FIXME: Provide a source location to indicate what we couldn't match.
8513 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8514 << *Cand->DeductionFailure.getFirstArg()
8515 << *Cand->DeductionFailure.getSecondArg();
8516 return;
8517
John McCall342fec42010-02-01 18:53:26 +00008518 // TODO: diagnose these individually, then kill off
8519 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008520 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008521 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008522 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008523 return;
8524 }
8525}
8526
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008527/// CUDA: diagnose an invalid call across targets.
8528void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8529 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8530 FunctionDecl *Callee = Cand->Function;
8531
8532 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8533 CalleeTarget = S.IdentifyCUDATarget(Callee);
8534
8535 std::string FnDesc;
8536 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8537
8538 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8539 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8540}
8541
John McCall342fec42010-02-01 18:53:26 +00008542/// Generates a 'note' diagnostic for an overload candidate. We've
8543/// already generated a primary error at the call site.
8544///
8545/// It really does need to be a single diagnostic with its caret
8546/// pointed at the candidate declaration. Yes, this creates some
8547/// major challenges of technical writing. Yes, this makes pointing
8548/// out problems with specific arguments quite awkward. It's still
8549/// better than generating twenty screens of text for every failed
8550/// overload.
8551///
8552/// It would be great to be able to express per-candidate problems
8553/// more richly for those diagnostic clients that cared, but we'd
8554/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008555void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008556 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008557 FunctionDecl *Fn = Cand->Function;
8558
John McCall81201622010-01-08 04:41:39 +00008559 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008560 if (Cand->Viable && (Fn->isDeleted() ||
8561 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008562 std::string FnDesc;
8563 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008564
8565 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008566 << FnKind << FnDesc
8567 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008568 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008569 return;
John McCall81201622010-01-08 04:41:39 +00008570 }
8571
John McCall220ccbf2010-01-13 00:25:19 +00008572 // We don't really have anything else to say about viable candidates.
8573 if (Cand->Viable) {
8574 S.NoteOverloadCandidate(Fn);
8575 return;
8576 }
John McCall1d318332010-01-12 00:44:57 +00008577
John McCalladbb8f82010-01-13 09:16:55 +00008578 switch (Cand->FailureKind) {
8579 case ovl_fail_too_many_arguments:
8580 case ovl_fail_too_few_arguments:
8581 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008582
John McCalladbb8f82010-01-13 09:16:55 +00008583 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008584 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008585
John McCall717e8912010-01-23 05:17:32 +00008586 case ovl_fail_trivial_conversion:
8587 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008588 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008589 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008590
John McCallb1bdc622010-02-25 01:37:24 +00008591 case ovl_fail_bad_conversion: {
8592 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008593 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008594 if (Cand->Conversions[I].isBad())
8595 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008596
John McCalladbb8f82010-01-13 09:16:55 +00008597 // FIXME: this currently happens when we're called from SemaInit
8598 // when user-conversion overload fails. Figure out how to handle
8599 // those conditions and diagnose them well.
8600 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008601 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008602
8603 case ovl_fail_bad_target:
8604 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008605 }
John McCalla1d7d622010-01-08 00:58:21 +00008606}
8607
8608void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8609 // Desugar the type of the surrogate down to a function type,
8610 // retaining as many typedefs as possible while still showing
8611 // the function type (and, therefore, its parameter types).
8612 QualType FnType = Cand->Surrogate->getConversionType();
8613 bool isLValueReference = false;
8614 bool isRValueReference = false;
8615 bool isPointer = false;
8616 if (const LValueReferenceType *FnTypeRef =
8617 FnType->getAs<LValueReferenceType>()) {
8618 FnType = FnTypeRef->getPointeeType();
8619 isLValueReference = true;
8620 } else if (const RValueReferenceType *FnTypeRef =
8621 FnType->getAs<RValueReferenceType>()) {
8622 FnType = FnTypeRef->getPointeeType();
8623 isRValueReference = true;
8624 }
8625 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8626 FnType = FnTypePtr->getPointeeType();
8627 isPointer = true;
8628 }
8629 // Desugar down to a function type.
8630 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8631 // Reconstruct the pointer/reference as appropriate.
8632 if (isPointer) FnType = S.Context.getPointerType(FnType);
8633 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8634 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8635
8636 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8637 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008638 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008639}
8640
8641void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008642 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008643 SourceLocation OpLoc,
8644 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008645 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008646 std::string TypeStr("operator");
8647 TypeStr += Opc;
8648 TypeStr += "(";
8649 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008650 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008651 TypeStr += ")";
8652 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8653 } else {
8654 TypeStr += ", ";
8655 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8656 TypeStr += ")";
8657 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8658 }
8659}
8660
8661void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8662 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008663 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008664 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8665 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008666 if (ICS.isBad()) break; // all meaningless after first invalid
8667 if (!ICS.isAmbiguous()) continue;
8668
John McCall120d63c2010-08-24 20:38:10 +00008669 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008670 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008671 }
8672}
8673
John McCall1b77e732010-01-15 23:32:50 +00008674SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8675 if (Cand->Function)
8676 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008677 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008678 return Cand->Surrogate->getLocation();
8679 return SourceLocation();
8680}
8681
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008682static unsigned
8683RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008684 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008685 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008686 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008687
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008688 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008689 case Sema::TDK_Incomplete:
8690 return 1;
8691
8692 case Sema::TDK_Underqualified:
8693 case Sema::TDK_Inconsistent:
8694 return 2;
8695
8696 case Sema::TDK_SubstitutionFailure:
8697 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008698 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008699 return 3;
8700
8701 case Sema::TDK_InstantiationDepth:
8702 case Sema::TDK_FailedOverloadResolution:
8703 return 4;
8704
8705 case Sema::TDK_InvalidExplicitArguments:
8706 return 5;
8707
8708 case Sema::TDK_TooManyArguments:
8709 case Sema::TDK_TooFewArguments:
8710 return 6;
8711 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008712 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008713}
8714
John McCallbf65c0b2010-01-12 00:48:53 +00008715struct CompareOverloadCandidatesForDisplay {
8716 Sema &S;
8717 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008718
8719 bool operator()(const OverloadCandidate *L,
8720 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008721 // Fast-path this check.
8722 if (L == R) return false;
8723
John McCall81201622010-01-08 04:41:39 +00008724 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008725 if (L->Viable) {
8726 if (!R->Viable) return true;
8727
8728 // TODO: introduce a tri-valued comparison for overload
8729 // candidates. Would be more worthwhile if we had a sort
8730 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008731 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8732 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008733 } else if (R->Viable)
8734 return false;
John McCall81201622010-01-08 04:41:39 +00008735
John McCall1b77e732010-01-15 23:32:50 +00008736 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008737
John McCall1b77e732010-01-15 23:32:50 +00008738 // Criteria by which we can sort non-viable candidates:
8739 if (!L->Viable) {
8740 // 1. Arity mismatches come after other candidates.
8741 if (L->FailureKind == ovl_fail_too_many_arguments ||
8742 L->FailureKind == ovl_fail_too_few_arguments)
8743 return false;
8744 if (R->FailureKind == ovl_fail_too_many_arguments ||
8745 R->FailureKind == ovl_fail_too_few_arguments)
8746 return true;
John McCall81201622010-01-08 04:41:39 +00008747
John McCall717e8912010-01-23 05:17:32 +00008748 // 2. Bad conversions come first and are ordered by the number
8749 // of bad conversions and quality of good conversions.
8750 if (L->FailureKind == ovl_fail_bad_conversion) {
8751 if (R->FailureKind != ovl_fail_bad_conversion)
8752 return true;
8753
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008754 // The conversion that can be fixed with a smaller number of changes,
8755 // comes first.
8756 unsigned numLFixes = L->Fix.NumConversionsFixed;
8757 unsigned numRFixes = R->Fix.NumConversionsFixed;
8758 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8759 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008760 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008761 if (numLFixes < numRFixes)
8762 return true;
8763 else
8764 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008765 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008766
John McCall717e8912010-01-23 05:17:32 +00008767 // If there's any ordering between the defined conversions...
8768 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008769 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008770
8771 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008772 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008773 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008774 switch (CompareImplicitConversionSequences(S,
8775 L->Conversions[I],
8776 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008777 case ImplicitConversionSequence::Better:
8778 leftBetter++;
8779 break;
8780
8781 case ImplicitConversionSequence::Worse:
8782 leftBetter--;
8783 break;
8784
8785 case ImplicitConversionSequence::Indistinguishable:
8786 break;
8787 }
8788 }
8789 if (leftBetter > 0) return true;
8790 if (leftBetter < 0) return false;
8791
8792 } else if (R->FailureKind == ovl_fail_bad_conversion)
8793 return false;
8794
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008795 if (L->FailureKind == ovl_fail_bad_deduction) {
8796 if (R->FailureKind != ovl_fail_bad_deduction)
8797 return true;
8798
8799 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8800 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008801 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008802 } else if (R->FailureKind == ovl_fail_bad_deduction)
8803 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008804
John McCall1b77e732010-01-15 23:32:50 +00008805 // TODO: others?
8806 }
8807
8808 // Sort everything else by location.
8809 SourceLocation LLoc = GetLocationForCandidate(L);
8810 SourceLocation RLoc = GetLocationForCandidate(R);
8811
8812 // Put candidates without locations (e.g. builtins) at the end.
8813 if (LLoc.isInvalid()) return false;
8814 if (RLoc.isInvalid()) return true;
8815
8816 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008817 }
8818};
8819
John McCall717e8912010-01-23 05:17:32 +00008820/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008821/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008822void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008823 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008824 assert(!Cand->Viable);
8825
8826 // Don't do anything on failures other than bad conversion.
8827 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8828
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008829 // We only want the FixIts if all the arguments can be corrected.
8830 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008831 // Use a implicit copy initialization to check conversion fixes.
8832 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008833
John McCall717e8912010-01-23 05:17:32 +00008834 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008835 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008836 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008837 while (true) {
8838 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8839 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008840 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008841 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008842 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008843 }
John McCall717e8912010-01-23 05:17:32 +00008844 }
8845
8846 if (ConvIdx == ConvCount)
8847 return;
8848
John McCallb1bdc622010-02-25 01:37:24 +00008849 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8850 "remaining conversion is initialized?");
8851
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008852 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008853 // operation somehow.
8854 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008855
8856 const FunctionProtoType* Proto;
8857 unsigned ArgIdx = ConvIdx;
8858
8859 if (Cand->IsSurrogate) {
8860 QualType ConvType
8861 = Cand->Surrogate->getConversionType().getNonReferenceType();
8862 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8863 ConvType = ConvPtrType->getPointeeType();
8864 Proto = ConvType->getAs<FunctionProtoType>();
8865 ArgIdx--;
8866 } else if (Cand->Function) {
8867 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8868 if (isa<CXXMethodDecl>(Cand->Function) &&
8869 !isa<CXXConstructorDecl>(Cand->Function))
8870 ArgIdx--;
8871 } else {
8872 // Builtin binary operator with a bad first conversion.
8873 assert(ConvCount <= 3);
8874 for (; ConvIdx != ConvCount; ++ConvIdx)
8875 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008876 = TryCopyInitialization(S, Args[ConvIdx],
8877 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008878 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008879 /*InOverloadResolution*/ true,
8880 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008881 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008882 return;
8883 }
8884
8885 // Fill in the rest of the conversions.
8886 unsigned NumArgsInProto = Proto->getNumArgs();
8887 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008888 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008889 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008890 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008891 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008892 /*InOverloadResolution=*/true,
8893 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008894 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008895 // Store the FixIt in the candidate if it exists.
8896 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008897 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008898 }
John McCall717e8912010-01-23 05:17:32 +00008899 else
8900 Cand->Conversions[ConvIdx].setEllipsis();
8901 }
8902}
8903
John McCalla1d7d622010-01-08 00:58:21 +00008904} // end anonymous namespace
8905
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008906/// PrintOverloadCandidates - When overload resolution fails, prints
8907/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008908/// set.
John McCall120d63c2010-08-24 20:38:10 +00008909void OverloadCandidateSet::NoteCandidates(Sema &S,
8910 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008911 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008912 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008913 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008914 // Sort the candidates by viability and position. Sorting directly would
8915 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008916 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008917 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8918 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008919 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008920 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008921 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008922 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008923 if (Cand->Function || Cand->IsSurrogate)
8924 Cands.push_back(Cand);
8925 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8926 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008927 }
8928 }
8929
John McCallbf65c0b2010-01-12 00:48:53 +00008930 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008931 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008932
John McCall1d318332010-01-12 00:44:57 +00008933 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008934
Chris Lattner5f9e2722011-07-23 10:55:15 +00008935 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008936 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008937 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008938 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8939 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008940
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008941 // Set an arbitrary limit on the number of candidate functions we'll spam
8942 // the user with. FIXME: This limit should depend on details of the
8943 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008944 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008945 break;
8946 }
8947 ++CandsShown;
8948
John McCalla1d7d622010-01-08 00:58:21 +00008949 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008950 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008951 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008952 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008953 else {
8954 assert(Cand->Viable &&
8955 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008956 // Generally we only see ambiguities including viable builtin
8957 // operators if overload resolution got screwed up by an
8958 // ambiguous user-defined conversion.
8959 //
8960 // FIXME: It's quite possible for different conversions to see
8961 // different ambiguities, though.
8962 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008963 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008964 ReportedAmbiguousConversions = true;
8965 }
John McCalla1d7d622010-01-08 00:58:21 +00008966
John McCall1d318332010-01-12 00:44:57 +00008967 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008968 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008969 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008970 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008971
8972 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008973 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008974}
8975
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008976// [PossiblyAFunctionType] --> [Return]
8977// NonFunctionType --> NonFunctionType
8978// R (A) --> R(A)
8979// R (*)(A) --> R (A)
8980// R (&)(A) --> R (A)
8981// R (S::*)(A) --> R (A)
8982QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8983 QualType Ret = PossiblyAFunctionType;
8984 if (const PointerType *ToTypePtr =
8985 PossiblyAFunctionType->getAs<PointerType>())
8986 Ret = ToTypePtr->getPointeeType();
8987 else if (const ReferenceType *ToTypeRef =
8988 PossiblyAFunctionType->getAs<ReferenceType>())
8989 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008990 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008991 PossiblyAFunctionType->getAs<MemberPointerType>())
8992 Ret = MemTypePtr->getPointeeType();
8993 Ret =
8994 Context.getCanonicalType(Ret).getUnqualifiedType();
8995 return Ret;
8996}
Douglas Gregor904eed32008-11-10 20:40:00 +00008997
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008998// A helper class to help with address of function resolution
8999// - allows us to avoid passing around all those ugly parameters
9000class AddressOfFunctionResolver
9001{
9002 Sema& S;
9003 Expr* SourceExpr;
9004 const QualType& TargetType;
9005 QualType TargetFunctionType; // Extracted function type from target type
9006
9007 bool Complain;
9008 //DeclAccessPair& ResultFunctionAccessPair;
9009 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009010
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009011 bool TargetTypeIsNonStaticMemberFunction;
9012 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009013
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009014 OverloadExpr::FindResult OvlExprInfo;
9015 OverloadExpr *OvlExpr;
9016 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009017 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009018
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009019public:
9020 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9021 const QualType& TargetType, bool Complain)
9022 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9023 Complain(Complain), Context(S.getASTContext()),
9024 TargetTypeIsNonStaticMemberFunction(
9025 !!TargetType->getAs<MemberPointerType>()),
9026 FoundNonTemplateFunction(false),
9027 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9028 OvlExpr(OvlExprInfo.Expression)
9029 {
9030 ExtractUnqualifiedFunctionTypeFromTargetType();
9031
9032 if (!TargetFunctionType->isFunctionType()) {
9033 if (OvlExpr->hasExplicitTemplateArgs()) {
9034 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009035 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009036 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009037
9038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9039 if (!Method->isStatic()) {
9040 // If the target type is a non-function type and the function
9041 // found is a non-static member function, pretend as if that was
9042 // the target, it's the only possible type to end up with.
9043 TargetTypeIsNonStaticMemberFunction = true;
9044
9045 // And skip adding the function if its not in the proper form.
9046 // We'll diagnose this due to an empty set of functions.
9047 if (!OvlExprInfo.HasFormOfMemberPointer)
9048 return;
9049 }
9050 }
9051
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009052 Matches.push_back(std::make_pair(dap,Fn));
9053 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009054 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009055 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009056 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009057
9058 if (OvlExpr->hasExplicitTemplateArgs())
9059 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009060
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009061 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9062 // C++ [over.over]p4:
9063 // If more than one function is selected, [...]
9064 if (Matches.size() > 1) {
9065 if (FoundNonTemplateFunction)
9066 EliminateAllTemplateMatches();
9067 else
9068 EliminateAllExceptMostSpecializedTemplate();
9069 }
9070 }
9071 }
9072
9073private:
9074 bool isTargetTypeAFunction() const {
9075 return TargetFunctionType->isFunctionType();
9076 }
9077
9078 // [ToType] [Return]
9079
9080 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9081 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9082 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9083 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9084 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9085 }
9086
9087 // return true if any matching specializations were found
9088 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9089 const DeclAccessPair& CurAccessFunPair) {
9090 if (CXXMethodDecl *Method
9091 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9092 // Skip non-static function templates when converting to pointer, and
9093 // static when converting to member pointer.
9094 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9095 return false;
9096 }
9097 else if (TargetTypeIsNonStaticMemberFunction)
9098 return false;
9099
9100 // C++ [over.over]p2:
9101 // If the name is a function template, template argument deduction is
9102 // done (14.8.2.2), and if the argument deduction succeeds, the
9103 // resulting template argument list is used to generate a single
9104 // function template specialization, which is added to the set of
9105 // overloaded functions considered.
9106 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009107 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009108 if (Sema::TemplateDeductionResult Result
9109 = S.DeduceTemplateArguments(FunctionTemplate,
9110 &OvlExplicitTemplateArgs,
9111 TargetFunctionType, Specialization,
9112 Info)) {
9113 // FIXME: make a note of the failed deduction for diagnostics.
9114 (void)Result;
9115 return false;
9116 }
9117
9118 // Template argument deduction ensures that we have an exact match.
9119 // This function template specicalization works.
9120 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9121 assert(TargetFunctionType
9122 == Context.getCanonicalType(Specialization->getType()));
9123 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9124 return true;
9125 }
9126
9127 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9128 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009129 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009130 // Skip non-static functions when converting to pointer, and static
9131 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009132 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9133 return false;
9134 }
9135 else if (TargetTypeIsNonStaticMemberFunction)
9136 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009137
Chandler Carruthbd647292009-12-29 06:17:27 +00009138 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009139 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009140 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9141 if (S.CheckCUDATarget(Caller, FunDecl))
9142 return false;
9143
Douglas Gregor43c79c22009-12-09 00:47:37 +00009144 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009145 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9146 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009147 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9148 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009149 Matches.push_back(std::make_pair(CurAccessFunPair,
9150 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009151 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009152 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009153 }
Mike Stump1eb44332009-09-09 15:08:12 +00009154 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009155
9156 return false;
9157 }
9158
9159 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9160 bool Ret = false;
9161
9162 // If the overload expression doesn't have the form of a pointer to
9163 // member, don't try to convert it to a pointer-to-member type.
9164 if (IsInvalidFormOfPointerToMemberFunction())
9165 return false;
9166
9167 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9168 E = OvlExpr->decls_end();
9169 I != E; ++I) {
9170 // Look through any using declarations to find the underlying function.
9171 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9172
9173 // C++ [over.over]p3:
9174 // Non-member functions and static member functions match
9175 // targets of type "pointer-to-function" or "reference-to-function."
9176 // Nonstatic member functions match targets of
9177 // type "pointer-to-member-function."
9178 // Note that according to DR 247, the containing class does not matter.
9179 if (FunctionTemplateDecl *FunctionTemplate
9180 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9181 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9182 Ret = true;
9183 }
9184 // If we have explicit template arguments supplied, skip non-templates.
9185 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9186 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9187 Ret = true;
9188 }
9189 assert(Ret || Matches.empty());
9190 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009191 }
9192
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009193 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009194 // [...] and any given function template specialization F1 is
9195 // eliminated if the set contains a second function template
9196 // specialization whose function template is more specialized
9197 // than the function template of F1 according to the partial
9198 // ordering rules of 14.5.5.2.
9199
9200 // The algorithm specified above is quadratic. We instead use a
9201 // two-pass algorithm (similar to the one used to identify the
9202 // best viable function in an overload set) that identifies the
9203 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009204
9205 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9206 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9207 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009208
John McCallc373d482010-01-27 01:50:18 +00009209 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009210 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9211 TPOC_Other, 0, SourceExpr->getLocStart(),
9212 S.PDiag(),
9213 S.PDiag(diag::err_addr_ovl_ambiguous)
9214 << Matches[0].second->getDeclName(),
9215 S.PDiag(diag::note_ovl_candidate)
9216 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009217 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009218
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009219 if (Result != MatchesCopy.end()) {
9220 // Make it the first and only element
9221 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9222 Matches[0].second = cast<FunctionDecl>(*Result);
9223 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009224 }
9225 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009226
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009227 void EliminateAllTemplateMatches() {
9228 // [...] any function template specializations in the set are
9229 // eliminated if the set also contains a non-template function, [...]
9230 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9231 if (Matches[I].second->getPrimaryTemplate() == 0)
9232 ++I;
9233 else {
9234 Matches[I] = Matches[--N];
9235 Matches.set_size(N);
9236 }
9237 }
9238 }
9239
9240public:
9241 void ComplainNoMatchesFound() const {
9242 assert(Matches.empty());
9243 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9244 << OvlExpr->getName() << TargetFunctionType
9245 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009246 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009247 }
9248
9249 bool IsInvalidFormOfPointerToMemberFunction() const {
9250 return TargetTypeIsNonStaticMemberFunction &&
9251 !OvlExprInfo.HasFormOfMemberPointer;
9252 }
9253
9254 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9255 // TODO: Should we condition this on whether any functions might
9256 // have matched, or is it more appropriate to do that in callers?
9257 // TODO: a fixit wouldn't hurt.
9258 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9259 << TargetType << OvlExpr->getSourceRange();
9260 }
9261
9262 void ComplainOfInvalidConversion() const {
9263 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9264 << OvlExpr->getName() << TargetType;
9265 }
9266
9267 void ComplainMultipleMatchesFound() const {
9268 assert(Matches.size() > 1);
9269 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9270 << OvlExpr->getName()
9271 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009272 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009273 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009274
9275 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9276
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009277 int getNumMatches() const { return Matches.size(); }
9278
9279 FunctionDecl* getMatchingFunctionDecl() const {
9280 if (Matches.size() != 1) return 0;
9281 return Matches[0].second;
9282 }
9283
9284 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9285 if (Matches.size() != 1) return 0;
9286 return &Matches[0].first;
9287 }
9288};
9289
9290/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9291/// an overloaded function (C++ [over.over]), where @p From is an
9292/// expression with overloaded function type and @p ToType is the type
9293/// we're trying to resolve to. For example:
9294///
9295/// @code
9296/// int f(double);
9297/// int f(int);
9298///
9299/// int (*pfd)(double) = f; // selects f(double)
9300/// @endcode
9301///
9302/// This routine returns the resulting FunctionDecl if it could be
9303/// resolved, and NULL otherwise. When @p Complain is true, this
9304/// routine will emit diagnostics if there is an error.
9305FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009306Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9307 QualType TargetType,
9308 bool Complain,
9309 DeclAccessPair &FoundResult,
9310 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009311 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009312
9313 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9314 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009315 int NumMatches = Resolver.getNumMatches();
9316 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009317 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009318 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9319 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9320 else
9321 Resolver.ComplainNoMatchesFound();
9322 }
9323 else if (NumMatches > 1 && Complain)
9324 Resolver.ComplainMultipleMatchesFound();
9325 else if (NumMatches == 1) {
9326 Fn = Resolver.getMatchingFunctionDecl();
9327 assert(Fn);
9328 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009329 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009330 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009331 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009332
9333 if (pHadMultipleCandidates)
9334 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009335 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009336}
9337
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009338/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009339/// resolve that overloaded function expression down to a single function.
9340///
9341/// This routine can only resolve template-ids that refer to a single function
9342/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009343/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009344/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009345FunctionDecl *
9346Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9347 bool Complain,
9348 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009349 // C++ [over.over]p1:
9350 // [...] [Note: any redundant set of parentheses surrounding the
9351 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009352 // C++ [over.over]p1:
9353 // [...] The overloaded function name can be preceded by the &
9354 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009355
Douglas Gregor4b52e252009-12-21 23:17:24 +00009356 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009357 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009358 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009359
9360 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009361 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009362
Douglas Gregor4b52e252009-12-21 23:17:24 +00009363 // Look through all of the overloaded functions, searching for one
9364 // whose type matches exactly.
9365 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009366 for (UnresolvedSetIterator I = ovl->decls_begin(),
9367 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009368 // C++0x [temp.arg.explicit]p3:
9369 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009370 // where deduction is not done, if a template argument list is
9371 // specified and it, along with any default template arguments,
9372 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009373 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009374 FunctionTemplateDecl *FunctionTemplate
9375 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009376
Douglas Gregor4b52e252009-12-21 23:17:24 +00009377 // C++ [over.over]p2:
9378 // If the name is a function template, template argument deduction is
9379 // done (14.8.2.2), and if the argument deduction succeeds, the
9380 // resulting template argument list is used to generate a single
9381 // function template specialization, which is added to the set of
9382 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009383 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009384 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009385 if (TemplateDeductionResult Result
9386 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9387 Specialization, Info)) {
9388 // FIXME: make a note of the failed deduction for diagnostics.
9389 (void)Result;
9390 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009391 }
9392
John McCall864c0412011-04-26 20:42:42 +00009393 assert(Specialization && "no specialization and no error?");
9394
Douglas Gregor4b52e252009-12-21 23:17:24 +00009395 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009396 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009397 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009398 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9399 << ovl->getName();
9400 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009401 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009402 return 0;
John McCall864c0412011-04-26 20:42:42 +00009403 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009404
John McCall864c0412011-04-26 20:42:42 +00009405 Matched = Specialization;
9406 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009408
Douglas Gregor4b52e252009-12-21 23:17:24 +00009409 return Matched;
9410}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009411
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009412
9413
9414
John McCall6dbba4f2011-10-11 23:14:30 +00009415// Resolve and fix an overloaded expression that can be resolved
9416// because it identifies a single function template specialization.
9417//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009418// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009419//
9420// Return true if it was logically possible to so resolve the
9421// expression, regardless of whether or not it succeeded. Always
9422// returns true if 'complain' is set.
9423bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9424 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9425 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009426 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009427 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009428 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009429
John McCall6dbba4f2011-10-11 23:14:30 +00009430 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009431
John McCall864c0412011-04-26 20:42:42 +00009432 DeclAccessPair found;
9433 ExprResult SingleFunctionExpression;
9434 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9435 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009436 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009437 SrcExpr = ExprError();
9438 return true;
9439 }
John McCall864c0412011-04-26 20:42:42 +00009440
9441 // It is only correct to resolve to an instance method if we're
9442 // resolving a form that's permitted to be a pointer to member.
9443 // Otherwise we'll end up making a bound member expression, which
9444 // is illegal in all the contexts we resolve like this.
9445 if (!ovl.HasFormOfMemberPointer &&
9446 isa<CXXMethodDecl>(fn) &&
9447 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009448 if (!complain) return false;
9449
9450 Diag(ovl.Expression->getExprLoc(),
9451 diag::err_bound_member_function)
9452 << 0 << ovl.Expression->getSourceRange();
9453
9454 // TODO: I believe we only end up here if there's a mix of
9455 // static and non-static candidates (otherwise the expression
9456 // would have 'bound member' type, not 'overload' type).
9457 // Ideally we would note which candidate was chosen and why
9458 // the static candidates were rejected.
9459 SrcExpr = ExprError();
9460 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009461 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009462
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009463 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009464 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009465 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009466
9467 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009468 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009469 SingleFunctionExpression =
9470 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009471 if (SingleFunctionExpression.isInvalid()) {
9472 SrcExpr = ExprError();
9473 return true;
9474 }
9475 }
John McCall864c0412011-04-26 20:42:42 +00009476 }
9477
9478 if (!SingleFunctionExpression.isUsable()) {
9479 if (complain) {
9480 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9481 << ovl.Expression->getName()
9482 << DestTypeForComplaining
9483 << OpRangeForComplaining
9484 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009485 NoteAllOverloadCandidates(SrcExpr.get());
9486
9487 SrcExpr = ExprError();
9488 return true;
9489 }
9490
9491 return false;
John McCall864c0412011-04-26 20:42:42 +00009492 }
9493
John McCall6dbba4f2011-10-11 23:14:30 +00009494 SrcExpr = SingleFunctionExpression;
9495 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009496}
9497
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009498/// \brief Add a single candidate to the overload set.
9499static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009500 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009501 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009502 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009503 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009504 bool PartialOverloading,
9505 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009506 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009507 if (isa<UsingShadowDecl>(Callee))
9508 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9509
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009510 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009511 if (ExplicitTemplateArgs) {
9512 assert(!KnownValid && "Explicit template arguments?");
9513 return;
9514 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009515 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9516 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009517 return;
John McCallba135432009-11-21 08:51:07 +00009518 }
9519
9520 if (FunctionTemplateDecl *FuncTemplate
9521 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009522 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009523 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009524 return;
9525 }
9526
Richard Smith2ced0442011-06-26 22:19:54 +00009527 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009528}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009529
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009530/// \brief Add the overload candidates named by callee and/or found by argument
9531/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009532void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009533 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009534 OverloadCandidateSet &CandidateSet,
9535 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009536
9537#ifndef NDEBUG
9538 // Verify that ArgumentDependentLookup is consistent with the rules
9539 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009540 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009541 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9542 // and let Y be the lookup set produced by argument dependent
9543 // lookup (defined as follows). If X contains
9544 //
9545 // -- a declaration of a class member, or
9546 //
9547 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009548 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009549 //
9550 // -- a declaration that is neither a function or a function
9551 // template
9552 //
9553 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009554
John McCall3b4294e2009-12-16 12:17:52 +00009555 if (ULE->requiresADL()) {
9556 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9557 E = ULE->decls_end(); I != E; ++I) {
9558 assert(!(*I)->getDeclContext()->isRecord());
9559 assert(isa<UsingShadowDecl>(*I) ||
9560 !(*I)->getDeclContext()->isFunctionOrMethod());
9561 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009562 }
9563 }
9564#endif
9565
John McCall3b4294e2009-12-16 12:17:52 +00009566 // It would be nice to avoid this copy.
9567 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009568 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009569 if (ULE->hasExplicitTemplateArgs()) {
9570 ULE->copyTemplateArgumentsInto(TABuffer);
9571 ExplicitTemplateArgs = &TABuffer;
9572 }
9573
9574 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9575 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009576 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9577 CandidateSet, PartialOverloading,
9578 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009579
John McCall3b4294e2009-12-16 12:17:52 +00009580 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009581 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009582 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009583 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009584 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009585}
John McCall578b69b2009-12-16 08:11:27 +00009586
Richard Smithf50e88a2011-06-05 22:42:48 +00009587/// Attempt to recover from an ill-formed use of a non-dependent name in a
9588/// template, where the non-dependent name was declared after the template
9589/// was defined. This is common in code written for a compilers which do not
9590/// correctly implement two-stage name lookup.
9591///
9592/// Returns true if a viable candidate was found and a diagnostic was issued.
9593static bool
9594DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9595 const CXXScopeSpec &SS, LookupResult &R,
9596 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009597 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009598 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9599 return false;
9600
9601 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009602 if (DC->isTransparentContext())
9603 continue;
9604
Richard Smithf50e88a2011-06-05 22:42:48 +00009605 SemaRef.LookupQualifiedName(R, DC);
9606
9607 if (!R.empty()) {
9608 R.suppressDiagnostics();
9609
9610 if (isa<CXXRecordDecl>(DC)) {
9611 // Don't diagnose names we find in classes; we get much better
9612 // diagnostics for these from DiagnoseEmptyLookup.
9613 R.clear();
9614 return false;
9615 }
9616
9617 OverloadCandidateSet Candidates(FnLoc);
9618 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9619 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009620 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009621 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009622
9623 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009624 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009625 // No viable functions. Don't bother the user with notes for functions
9626 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009627 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009628 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009629 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009630
9631 // Find the namespaces where ADL would have looked, and suggest
9632 // declaring the function there instead.
9633 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9634 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009635 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009636 AssociatedNamespaces,
9637 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009638 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009639 DeclContext *Std = SemaRef.getStdNamespace();
9640 for (Sema::AssociatedNamespaceSet::iterator
9641 it = AssociatedNamespaces.begin(),
9642 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009643 // Never suggest declaring a function within namespace 'std'.
9644 if (Std && Std->Encloses(*it))
9645 continue;
9646
9647 // Never suggest declaring a function within a namespace with a reserved
9648 // name, like __gnu_cxx.
9649 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9650 if (NS &&
9651 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9652 continue;
9653
9654 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009655 }
9656
9657 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9658 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009659 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009660 SemaRef.Diag(Best->Function->getLocation(),
9661 diag::note_not_found_by_two_phase_lookup)
9662 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009663 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009664 SemaRef.Diag(Best->Function->getLocation(),
9665 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009666 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009667 } else {
9668 // FIXME: It would be useful to list the associated namespaces here,
9669 // but the diagnostics infrastructure doesn't provide a way to produce
9670 // a localized representation of a list of items.
9671 SemaRef.Diag(Best->Function->getLocation(),
9672 diag::note_not_found_by_two_phase_lookup)
9673 << R.getLookupName() << 2;
9674 }
9675
9676 // Try to recover by calling this function.
9677 return true;
9678 }
9679
9680 R.clear();
9681 }
9682
9683 return false;
9684}
9685
9686/// Attempt to recover from ill-formed use of a non-dependent operator in a
9687/// template, where the non-dependent operator was declared after the template
9688/// was defined.
9689///
9690/// Returns true if a viable candidate was found and a diagnostic was issued.
9691static bool
9692DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9693 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009694 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009695 DeclarationName OpName =
9696 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9697 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9698 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009699 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009700}
9701
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009702namespace {
9703// Callback to limit the allowed keywords and to only accept typo corrections
9704// that are keywords or whose decls refer to functions (or template functions)
9705// that accept the given number of arguments.
9706class RecoveryCallCCC : public CorrectionCandidateCallback {
9707 public:
9708 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9709 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009710 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009711 WantRemainingKeywords = false;
9712 }
9713
9714 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9715 if (!candidate.getCorrectionDecl())
9716 return candidate.isKeyword();
9717
9718 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9719 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9720 FunctionDecl *FD = 0;
9721 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9722 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9723 FD = FTD->getTemplatedDecl();
9724 if (!HasExplicitTemplateArgs && !FD) {
9725 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9726 // If the Decl is neither a function nor a template function,
9727 // determine if it is a pointer or reference to a function. If so,
9728 // check against the number of arguments expected for the pointee.
9729 QualType ValType = cast<ValueDecl>(ND)->getType();
9730 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9731 ValType = ValType->getPointeeType();
9732 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9733 if (FPT->getNumArgs() == NumArgs)
9734 return true;
9735 }
9736 }
9737 if (FD && FD->getNumParams() >= NumArgs &&
9738 FD->getMinRequiredArguments() <= NumArgs)
9739 return true;
9740 }
9741 return false;
9742 }
9743
9744 private:
9745 unsigned NumArgs;
9746 bool HasExplicitTemplateArgs;
9747};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009748
9749// Callback that effectively disabled typo correction
9750class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9751 public:
9752 NoTypoCorrectionCCC() {
9753 WantTypeSpecifiers = false;
9754 WantExpressionKeywords = false;
9755 WantCXXNamedCasts = false;
9756 WantRemainingKeywords = false;
9757 }
9758
9759 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9760 return false;
9761 }
9762};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009763
9764class BuildRecoveryCallExprRAII {
9765 Sema &SemaRef;
9766public:
9767 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9768 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9769 SemaRef.IsBuildingRecoveryCallExpr = true;
9770 }
9771
9772 ~BuildRecoveryCallExprRAII() {
9773 SemaRef.IsBuildingRecoveryCallExpr = false;
9774 }
9775};
9776
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009777}
9778
John McCall578b69b2009-12-16 08:11:27 +00009779/// Attempts to recover from a call where no functions were found.
9780///
9781/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009782static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009783BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009784 UnresolvedLookupExpr *ULE,
9785 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009786 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009787 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009788 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009789 // Do not try to recover if it is already building a recovery call.
9790 // This stops infinite loops for template instantiations like
9791 //
9792 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9793 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9794 //
9795 if (SemaRef.IsBuildingRecoveryCallExpr)
9796 return ExprError();
9797 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009798
9799 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009800 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009801 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009802
John McCall3b4294e2009-12-16 12:17:52 +00009803 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009804 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009805 if (ULE->hasExplicitTemplateArgs()) {
9806 ULE->copyTemplateArgumentsInto(TABuffer);
9807 ExplicitTemplateArgs = &TABuffer;
9808 }
9809
John McCall578b69b2009-12-16 08:11:27 +00009810 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9811 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009812 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009813 NoTypoCorrectionCCC RejectAll;
9814 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9815 (CorrectionCandidateCallback*)&Validator :
9816 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009817 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009818 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009819 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009820 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009821 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009822 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009823
John McCall3b4294e2009-12-16 12:17:52 +00009824 assert(!R.empty() && "lookup results empty despite recovery");
9825
9826 // Build an implicit member call if appropriate. Just drop the
9827 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009828 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009829 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009830 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9831 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009832 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009833 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009834 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009835 else
9836 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9837
9838 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009839 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009840
9841 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009842 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009843 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009844 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009845 MultiExprArg(Args.data(), Args.size()),
9846 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009847}
Douglas Gregord7a95972010-06-08 17:35:15 +00009848
Sam Panzere1715b62012-08-21 00:52:01 +00009849/// \brief Constructs and populates an OverloadedCandidateSet from
9850/// the given function.
9851/// \returns true when an the ExprResult output parameter has been set.
9852bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9853 UnresolvedLookupExpr *ULE,
9854 Expr **Args, unsigned NumArgs,
9855 SourceLocation RParenLoc,
9856 OverloadCandidateSet *CandidateSet,
9857 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009858#ifndef NDEBUG
9859 if (ULE->requiresADL()) {
9860 // To do ADL, we must have found an unqualified name.
9861 assert(!ULE->getQualifier() && "qualified name with ADL");
9862
9863 // We don't perform ADL for implicit declarations of builtins.
9864 // Verify that this was correctly set up.
9865 FunctionDecl *F;
9866 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9867 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9868 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009869 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009870
John McCall3b4294e2009-12-16 12:17:52 +00009871 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009872 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009873 }
John McCall3b4294e2009-12-16 12:17:52 +00009874#endif
9875
John McCall5acb0c92011-10-17 18:40:02 +00009876 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009877 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9878 *Result = ExprError();
9879 return true;
9880 }
Douglas Gregor17330012009-02-04 15:01:18 +00009881
John McCall3b4294e2009-12-16 12:17:52 +00009882 // Add the functions denoted by the callee to the set of candidate
9883 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009884 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009885 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009886
9887 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009888 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9889 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009890 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009891 // In Microsoft mode, if we are inside a template class member function then
9892 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009893 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009894 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009895 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009896 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009897 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9898 llvm::makeArrayRef(Args, NumArgs),
9899 Context.DependentTy, VK_RValue,
9900 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009901 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009902 *Result = Owned(CE);
9903 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009904 }
Sam Panzere1715b62012-08-21 00:52:01 +00009905 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009906 }
John McCall578b69b2009-12-16 08:11:27 +00009907
John McCall5acb0c92011-10-17 18:40:02 +00009908 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009909 return false;
9910}
John McCall5acb0c92011-10-17 18:40:02 +00009911
Sam Panzere1715b62012-08-21 00:52:01 +00009912/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9913/// the completed call expression. If overload resolution fails, emits
9914/// diagnostics and returns ExprError()
9915static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9916 UnresolvedLookupExpr *ULE,
9917 SourceLocation LParenLoc,
9918 Expr **Args, unsigned NumArgs,
9919 SourceLocation RParenLoc,
9920 Expr *ExecConfig,
9921 OverloadCandidateSet *CandidateSet,
9922 OverloadCandidateSet::iterator *Best,
9923 OverloadingResult OverloadResult,
9924 bool AllowTypoCorrection) {
9925 if (CandidateSet->empty())
9926 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9927 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9928 RParenLoc, /*EmptyLookup=*/true,
9929 AllowTypoCorrection);
9930
9931 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009932 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009933 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +00009934 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9935 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9936 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9937 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9938 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009939 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009940
Richard Smithf50e88a2011-06-05 22:42:48 +00009941 case OR_No_Viable_Function: {
9942 // Try to recover by looking for viable functions which the user might
9943 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009944 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009945 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9946 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009947 /*EmptyLookup=*/false,
9948 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009949 if (!Recovery.isInvalid())
9950 return Recovery;
9951
Sam Panzere1715b62012-08-21 00:52:01 +00009952 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009953 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009954 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009955 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9956 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009957 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009958 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009959
9960 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009961 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009962 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009963 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9964 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009965 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009966
Sam Panzere1715b62012-08-21 00:52:01 +00009967 case OR_Deleted: {
9968 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9969 << (*Best)->Function->isDeleted()
9970 << ULE->getName()
9971 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9972 << Fn->getSourceRange();
9973 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9974 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009975
Sam Panzere1715b62012-08-21 00:52:01 +00009976 // We emitted an error for the unvailable/deleted function call but keep
9977 // the call in the AST.
9978 FunctionDecl *FDecl = (*Best)->Function;
9979 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9980 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9981 RParenLoc, ExecConfig);
9982 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009983 }
9984
Douglas Gregorff331c12010-07-25 18:17:45 +00009985 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009986 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009987}
9988
Sam Panzere1715b62012-08-21 00:52:01 +00009989/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9990/// (which eventually refers to the declaration Func) and the call
9991/// arguments Args/NumArgs, attempt to resolve the function call down
9992/// to a specific function. If overload resolution succeeds, returns
9993/// the call expression produced by overload resolution.
9994/// Otherwise, emits diagnostics and returns ExprError.
9995ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9996 UnresolvedLookupExpr *ULE,
9997 SourceLocation LParenLoc,
9998 Expr **Args, unsigned NumArgs,
9999 SourceLocation RParenLoc,
10000 Expr *ExecConfig,
10001 bool AllowTypoCorrection) {
10002 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10003 ExprResult result;
10004
10005 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
10006 &CandidateSet, &result))
10007 return result;
10008
10009 OverloadCandidateSet::iterator Best;
10010 OverloadingResult OverloadResult =
10011 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10012
10013 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
10014 RParenLoc, ExecConfig, &CandidateSet,
10015 &Best, OverloadResult,
10016 AllowTypoCorrection);
10017}
10018
John McCall6e266892010-01-26 03:27:55 +000010019static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010020 return Functions.size() > 1 ||
10021 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10022}
10023
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010024/// \brief Create a unary operation that may resolve to an overloaded
10025/// operator.
10026///
10027/// \param OpLoc The location of the operator itself (e.g., '*').
10028///
10029/// \param OpcIn The UnaryOperator::Opcode that describes this
10030/// operator.
10031///
James Dennett40ae6662012-06-22 08:52:37 +000010032/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010033/// considered by overload resolution. The caller needs to build this
10034/// set based on the context using, e.g.,
10035/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10036/// set should not contain any member functions; those will be added
10037/// by CreateOverloadedUnaryOp().
10038///
James Dennett8da16872012-06-22 10:32:46 +000010039/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010040ExprResult
John McCall6e266892010-01-26 03:27:55 +000010041Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10042 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010043 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010044 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010045
10046 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10047 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10048 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010049 // TODO: provide better source location info.
10050 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010051
John McCall5acb0c92011-10-17 18:40:02 +000010052 if (checkPlaceholderForOverload(*this, Input))
10053 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010054
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010055 Expr *Args[2] = { Input, 0 };
10056 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010057
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010058 // For post-increment and post-decrement, add the implicit '0' as
10059 // the second argument, so that we know this is a post-increment or
10060 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010061 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010062 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010063 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10064 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010065 NumArgs = 2;
10066 }
10067
10068 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010069 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010070 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010071 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010072 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010073 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010074 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010075
John McCallc373d482010-01-27 01:50:18 +000010076 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010077 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010078 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010079 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010080 /*ADL*/ true, IsOverloaded(Fns),
10081 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010082 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010083 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010084 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010085 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010086 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010087 }
10088
10089 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010090 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010091
10092 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010093 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10094 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010095
10096 // Add operator candidates that are member functions.
10097 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10098
John McCall6e266892010-01-26 03:27:55 +000010099 // Add candidates from ADL.
10100 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010101 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010102 /*ExplicitTemplateArgs*/ 0,
10103 CandidateSet);
10104
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010105 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010106 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010107
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010108 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10109
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010110 // Perform overload resolution.
10111 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010112 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010113 case OR_Success: {
10114 // We found a built-in operator or an overloaded operator.
10115 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010116
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010117 if (FnDecl) {
10118 // We matched an overloaded operator. Build a call to that
10119 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010120
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010121 // Convert the arguments.
10122 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010123 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010124
John Wiegley429bb272011-04-08 18:41:53 +000010125 ExprResult InputRes =
10126 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10127 Best->FoundDecl, Method);
10128 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010129 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010130 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010131 } else {
10132 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010133 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010134 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010135 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010136 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010137 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010138 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010139 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010140 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010141 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010142 }
10143
John McCallf89e55a2010-11-18 06:31:45 +000010144 // Determine the result type.
10145 QualType ResultTy = FnDecl->getResultType();
10146 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10147 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010148
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010149 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010150 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010151 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010152 if (FnExpr.isInvalid())
10153 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010154
Eli Friedman4c3b8962009-11-18 03:58:17 +000010155 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010156 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010157 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010158 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010159 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010160
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010161 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010162 FnDecl))
10163 return ExprError();
10164
John McCall9ae2f072010-08-23 23:25:46 +000010165 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010166 } else {
10167 // We matched a built-in operator. Convert the arguments, then
10168 // break out so that we will build the appropriate built-in
10169 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010170 ExprResult InputRes =
10171 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10172 Best->Conversions[0], AA_Passing);
10173 if (InputRes.isInvalid())
10174 return ExprError();
10175 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010176 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010177 }
John Wiegley429bb272011-04-08 18:41:53 +000010178 }
10179
10180 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010181 // This is an erroneous use of an operator which can be overloaded by
10182 // a non-member function. Check for non-member operators which were
10183 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010184 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10185 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010186 // FIXME: Recover by calling the found function.
10187 return ExprError();
10188
John Wiegley429bb272011-04-08 18:41:53 +000010189 // No viable function; fall through to handling this as a
10190 // built-in operator, which will produce an error message for us.
10191 break;
10192
10193 case OR_Ambiguous:
10194 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10195 << UnaryOperator::getOpcodeStr(Opc)
10196 << Input->getType()
10197 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010198 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10199 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010200 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10201 return ExprError();
10202
10203 case OR_Deleted:
10204 Diag(OpLoc, diag::err_ovl_deleted_oper)
10205 << Best->Function->isDeleted()
10206 << UnaryOperator::getOpcodeStr(Opc)
10207 << getDeletedOrUnavailableSuffix(Best->Function)
10208 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010209 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10210 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010211 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010212 return ExprError();
10213 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010214
10215 // Either we found no viable overloaded operator or we matched a
10216 // built-in operator. In either case, fall through to trying to
10217 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010218 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010219}
10220
Douglas Gregor063daf62009-03-13 18:40:31 +000010221/// \brief Create a binary operation that may resolve to an overloaded
10222/// operator.
10223///
10224/// \param OpLoc The location of the operator itself (e.g., '+').
10225///
10226/// \param OpcIn The BinaryOperator::Opcode that describes this
10227/// operator.
10228///
James Dennett40ae6662012-06-22 08:52:37 +000010229/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010230/// considered by overload resolution. The caller needs to build this
10231/// set based on the context using, e.g.,
10232/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10233/// set should not contain any member functions; those will be added
10234/// by CreateOverloadedBinOp().
10235///
10236/// \param LHS Left-hand argument.
10237/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010238ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010239Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010240 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010241 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010242 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010243 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010244 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010245
10246 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10247 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10248 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10249
10250 // If either side is type-dependent, create an appropriate dependent
10251 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010252 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010253 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010254 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010255 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010256 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010257 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010258 Context.DependentTy,
10259 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010260 OpLoc,
10261 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010262
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010263 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10264 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010265 VK_LValue,
10266 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010267 Context.DependentTy,
10268 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010269 OpLoc,
10270 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010271 }
John McCall6e266892010-01-26 03:27:55 +000010272
10273 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010274 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010275 // TODO: provide better source location info in DNLoc component.
10276 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010277 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010278 = UnresolvedLookupExpr::Create(Context, NamingClass,
10279 NestedNameSpecifierLoc(), OpNameInfo,
10280 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010281 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010282 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10283 Context.DependentTy, VK_RValue,
10284 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010285 }
10286
John McCall5acb0c92011-10-17 18:40:02 +000010287 // Always do placeholder-like conversions on the RHS.
10288 if (checkPlaceholderForOverload(*this, Args[1]))
10289 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010290
John McCall3c3b7f92011-10-25 17:37:35 +000010291 // Do placeholder-like conversion on the LHS; note that we should
10292 // not get here with a PseudoObject LHS.
10293 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010294 if (checkPlaceholderForOverload(*this, Args[0]))
10295 return ExprError();
10296
Sebastian Redl275c2b42009-11-18 23:10:33 +000010297 // If this is the assignment operator, we only perform overload resolution
10298 // if the left-hand side is a class or enumeration type. This is actually
10299 // a hack. The standard requires that we do overload resolution between the
10300 // various built-in candidates, but as DR507 points out, this can lead to
10301 // problems. So we do it this way, which pretty much follows what GCC does.
10302 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010303 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010304 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010305
John McCall0e800c92010-12-04 08:14:53 +000010306 // If this is the .* operator, which is not overloadable, just
10307 // create a built-in binary operator.
10308 if (Opc == BO_PtrMemD)
10309 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10310
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010311 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010312 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010313
10314 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010315 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010316
10317 // Add operator candidates that are member functions.
10318 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10319
John McCall6e266892010-01-26 03:27:55 +000010320 // Add candidates from ADL.
10321 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010322 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010323 /*ExplicitTemplateArgs*/ 0,
10324 CandidateSet);
10325
Douglas Gregor063daf62009-03-13 18:40:31 +000010326 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010327 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010328
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010329 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10330
Douglas Gregor063daf62009-03-13 18:40:31 +000010331 // Perform overload resolution.
10332 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010333 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010334 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010335 // We found a built-in operator or an overloaded operator.
10336 FunctionDecl *FnDecl = Best->Function;
10337
10338 if (FnDecl) {
10339 // We matched an overloaded operator. Build a call to that
10340 // operator.
10341
10342 // Convert the arguments.
10343 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010344 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010345 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010346
Chandler Carruth6df868e2010-12-12 08:17:55 +000010347 ExprResult Arg1 =
10348 PerformCopyInitialization(
10349 InitializedEntity::InitializeParameter(Context,
10350 FnDecl->getParamDecl(0)),
10351 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010352 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010353 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010354
John Wiegley429bb272011-04-08 18:41:53 +000010355 ExprResult Arg0 =
10356 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10357 Best->FoundDecl, Method);
10358 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010359 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010360 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010361 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010362 } else {
10363 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010364 ExprResult Arg0 = PerformCopyInitialization(
10365 InitializedEntity::InitializeParameter(Context,
10366 FnDecl->getParamDecl(0)),
10367 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010368 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010369 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010370
Chandler Carruth6df868e2010-12-12 08:17:55 +000010371 ExprResult Arg1 =
10372 PerformCopyInitialization(
10373 InitializedEntity::InitializeParameter(Context,
10374 FnDecl->getParamDecl(1)),
10375 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010376 if (Arg1.isInvalid())
10377 return ExprError();
10378 Args[0] = LHS = Arg0.takeAs<Expr>();
10379 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010380 }
10381
John McCallf89e55a2010-11-18 06:31:45 +000010382 // Determine the result type.
10383 QualType ResultTy = FnDecl->getResultType();
10384 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10385 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010386
10387 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010388 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010389 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010390 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010391 if (FnExpr.isInvalid())
10392 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010393
John McCall9ae2f072010-08-23 23:25:46 +000010394 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010395 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010396 Args, ResultTy, VK, OpLoc,
10397 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010398
10399 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010400 FnDecl))
10401 return ExprError();
10402
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010403 ArrayRef<const Expr *> ArgsArray(Args, 2);
10404 // Cut off the implicit 'this'.
10405 if (isa<CXXMethodDecl>(FnDecl))
10406 ArgsArray = ArgsArray.slice(1);
10407 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10408 TheCall->getSourceRange(), VariadicDoesNotApply);
10409
John McCall9ae2f072010-08-23 23:25:46 +000010410 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010411 } else {
10412 // We matched a built-in operator. Convert the arguments, then
10413 // break out so that we will build the appropriate built-in
10414 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010415 ExprResult ArgsRes0 =
10416 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10417 Best->Conversions[0], AA_Passing);
10418 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010419 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010420 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010421
John Wiegley429bb272011-04-08 18:41:53 +000010422 ExprResult ArgsRes1 =
10423 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10424 Best->Conversions[1], AA_Passing);
10425 if (ArgsRes1.isInvalid())
10426 return ExprError();
10427 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010428 break;
10429 }
10430 }
10431
Douglas Gregor33074752009-09-30 21:46:01 +000010432 case OR_No_Viable_Function: {
10433 // C++ [over.match.oper]p9:
10434 // If the operator is the operator , [...] and there are no
10435 // viable functions, then the operator is assumed to be the
10436 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010437 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010438 break;
10439
Chandler Carruth6df868e2010-12-12 08:17:55 +000010440 // For class as left operand for assignment or compound assigment
10441 // operator do not fall through to handling in built-in, but report that
10442 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010443 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010444 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010445 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010446 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10447 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010448 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010449 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010450 // This is an erroneous use of an operator which can be overloaded by
10451 // a non-member function. Check for non-member operators which were
10452 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010453 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010454 // FIXME: Recover by calling the found function.
10455 return ExprError();
10456
Douglas Gregor33074752009-09-30 21:46:01 +000010457 // No viable function; try to create a built-in operation, which will
10458 // produce an error. Then, show the non-viable candidates.
10459 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010460 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010461 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010462 "C++ binary operator overloading is missing candidates!");
10463 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010464 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010465 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010466 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010467 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010468
10469 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010470 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010471 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010472 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010473 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010474 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010475 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010476 return ExprError();
10477
10478 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010479 if (isImplicitlyDeleted(Best->Function)) {
10480 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10481 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010482 << Context.getRecordType(Method->getParent())
10483 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010484
Richard Smith0f46e642012-12-28 12:23:24 +000010485 // The user probably meant to call this special member. Just
10486 // explain why it's deleted.
10487 NoteDeletedFunction(Method);
10488 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010489 } else {
10490 Diag(OpLoc, diag::err_ovl_deleted_oper)
10491 << Best->Function->isDeleted()
10492 << BinaryOperator::getOpcodeStr(Opc)
10493 << getDeletedOrUnavailableSuffix(Best->Function)
10494 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10495 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010496 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010497 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010498 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010499 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010500
Douglas Gregor33074752009-09-30 21:46:01 +000010501 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010502 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010503}
10504
John McCall60d7b3a2010-08-24 06:29:42 +000010505ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010506Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10507 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010508 Expr *Base, Expr *Idx) {
10509 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010510 DeclarationName OpName =
10511 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10512
10513 // If either side is type-dependent, create an appropriate dependent
10514 // expression.
10515 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10516
John McCallc373d482010-01-27 01:50:18 +000010517 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010518 // CHECKME: no 'operator' keyword?
10519 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10520 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010521 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010522 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010523 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010524 /*ADL*/ true, /*Overloaded*/ false,
10525 UnresolvedSetIterator(),
10526 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010527 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010528
Sebastian Redlf322ed62009-10-29 20:17:01 +000010529 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010530 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010531 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010532 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010533 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010534 }
10535
John McCall5acb0c92011-10-17 18:40:02 +000010536 // Handle placeholders on both operands.
10537 if (checkPlaceholderForOverload(*this, Args[0]))
10538 return ExprError();
10539 if (checkPlaceholderForOverload(*this, Args[1]))
10540 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010541
Sebastian Redlf322ed62009-10-29 20:17:01 +000010542 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010543 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010544
10545 // Subscript can only be overloaded as a member function.
10546
10547 // Add operator candidates that are member functions.
10548 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10549
10550 // Add builtin operator candidates.
10551 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10552
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010553 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10554
Sebastian Redlf322ed62009-10-29 20:17:01 +000010555 // Perform overload resolution.
10556 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010557 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010558 case OR_Success: {
10559 // We found a built-in operator or an overloaded operator.
10560 FunctionDecl *FnDecl = Best->Function;
10561
10562 if (FnDecl) {
10563 // We matched an overloaded operator. Build a call to that
10564 // operator.
10565
John McCall9aa472c2010-03-19 07:35:19 +000010566 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010567
Sebastian Redlf322ed62009-10-29 20:17:01 +000010568 // Convert the arguments.
10569 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010570 ExprResult Arg0 =
10571 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10572 Best->FoundDecl, Method);
10573 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010574 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010575 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010576
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010577 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010578 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010579 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010580 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010581 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010582 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010583 Owned(Args[1]));
10584 if (InputInit.isInvalid())
10585 return ExprError();
10586
10587 Args[1] = InputInit.takeAs<Expr>();
10588
Sebastian Redlf322ed62009-10-29 20:17:01 +000010589 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010590 QualType ResultTy = FnDecl->getResultType();
10591 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10592 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010593
10594 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010595 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10596 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010597 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010598 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010599 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010600 OpLocInfo.getLoc(),
10601 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010602 if (FnExpr.isInvalid())
10603 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010604
John McCall9ae2f072010-08-23 23:25:46 +000010605 CXXOperatorCallExpr *TheCall =
10606 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010607 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010608 ResultTy, VK, RLoc,
10609 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010610
John McCall9ae2f072010-08-23 23:25:46 +000010611 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010612 FnDecl))
10613 return ExprError();
10614
John McCall9ae2f072010-08-23 23:25:46 +000010615 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010616 } else {
10617 // We matched a built-in operator. Convert the arguments, then
10618 // break out so that we will build the appropriate built-in
10619 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010620 ExprResult ArgsRes0 =
10621 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10622 Best->Conversions[0], AA_Passing);
10623 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010624 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010625 Args[0] = ArgsRes0.take();
10626
10627 ExprResult ArgsRes1 =
10628 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10629 Best->Conversions[1], AA_Passing);
10630 if (ArgsRes1.isInvalid())
10631 return ExprError();
10632 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010633
10634 break;
10635 }
10636 }
10637
10638 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010639 if (CandidateSet.empty())
10640 Diag(LLoc, diag::err_ovl_no_oper)
10641 << Args[0]->getType() << /*subscript*/ 0
10642 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10643 else
10644 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10645 << Args[0]->getType()
10646 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010647 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010648 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010649 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010650 }
10651
10652 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010653 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010654 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010655 << Args[0]->getType() << Args[1]->getType()
10656 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010657 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010658 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010659 return ExprError();
10660
10661 case OR_Deleted:
10662 Diag(LLoc, diag::err_ovl_deleted_oper)
10663 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010664 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010665 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010666 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010667 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010668 return ExprError();
10669 }
10670
10671 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010672 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010673}
10674
Douglas Gregor88a35142008-12-22 05:46:06 +000010675/// BuildCallToMemberFunction - Build a call to a member
10676/// function. MemExpr is the expression that refers to the member
10677/// function (and includes the object parameter), Args/NumArgs are the
10678/// arguments to the function call (not including the object
10679/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010680/// expression refers to a non-static member function or an overloaded
10681/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010682ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010683Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10684 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010685 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010686 assert(MemExprE->getType() == Context.BoundMemberTy ||
10687 MemExprE->getType() == Context.OverloadTy);
10688
Douglas Gregor88a35142008-12-22 05:46:06 +000010689 // Dig out the member expression. This holds both the object
10690 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010691 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010692
John McCall864c0412011-04-26 20:42:42 +000010693 // Determine whether this is a call to a pointer-to-member function.
10694 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10695 assert(op->getType() == Context.BoundMemberTy);
10696 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10697
10698 QualType fnType =
10699 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10700
10701 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10702 QualType resultType = proto->getCallResultType(Context);
10703 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10704
10705 // Check that the object type isn't more qualified than the
10706 // member function we're calling.
10707 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10708
10709 QualType objectType = op->getLHS()->getType();
10710 if (op->getOpcode() == BO_PtrMemI)
10711 objectType = objectType->castAs<PointerType>()->getPointeeType();
10712 Qualifiers objectQuals = objectType.getQualifiers();
10713
10714 Qualifiers difference = objectQuals - funcQuals;
10715 difference.removeObjCGCAttr();
10716 difference.removeAddressSpace();
10717 if (difference) {
10718 std::string qualsString = difference.getAsString();
10719 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10720 << fnType.getUnqualifiedType()
10721 << qualsString
10722 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10723 }
10724
10725 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010726 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10727 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010728 resultType, valueKind, RParenLoc);
10729
10730 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010731 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010732 call, 0))
10733 return ExprError();
10734
10735 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10736 return ExprError();
10737
10738 return MaybeBindToTemporary(call);
10739 }
10740
John McCall5acb0c92011-10-17 18:40:02 +000010741 UnbridgedCastsSet UnbridgedCasts;
10742 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10743 return ExprError();
10744
John McCall129e2df2009-11-30 22:42:35 +000010745 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010746 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010747 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010748 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010749 if (isa<MemberExpr>(NakedMemExpr)) {
10750 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010751 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010752 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010753 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010754 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010755 } else {
10756 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010757 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010758
John McCall701c89e2009-12-03 04:06:58 +000010759 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010760 Expr::Classification ObjectClassification
10761 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10762 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010763
Douglas Gregor88a35142008-12-22 05:46:06 +000010764 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010765 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010766
John McCallaa81e162009-12-01 22:10:20 +000010767 // FIXME: avoid copy.
10768 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10769 if (UnresExpr->hasExplicitTemplateArgs()) {
10770 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10771 TemplateArgs = &TemplateArgsBuffer;
10772 }
10773
John McCall129e2df2009-11-30 22:42:35 +000010774 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10775 E = UnresExpr->decls_end(); I != E; ++I) {
10776
John McCall701c89e2009-12-03 04:06:58 +000010777 NamedDecl *Func = *I;
10778 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10779 if (isa<UsingShadowDecl>(Func))
10780 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10781
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010782
Francois Pichetdbee3412011-01-18 05:04:39 +000010783 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010784 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010785 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10786 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010787 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010788 // If explicit template arguments were provided, we can't call a
10789 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010790 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010791 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010792
John McCall9aa472c2010-03-19 07:35:19 +000010793 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010794 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010795 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010796 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010797 } else {
John McCall129e2df2009-11-30 22:42:35 +000010798 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010799 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010800 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010801 llvm::makeArrayRef(Args, NumArgs),
10802 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010803 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010804 }
Douglas Gregordec06662009-08-21 18:42:58 +000010805 }
Mike Stump1eb44332009-09-09 15:08:12 +000010806
John McCall129e2df2009-11-30 22:42:35 +000010807 DeclarationName DeclName = UnresExpr->getMemberName();
10808
John McCall5acb0c92011-10-17 18:40:02 +000010809 UnbridgedCasts.restore();
10810
Douglas Gregor88a35142008-12-22 05:46:06 +000010811 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010812 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010813 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010814 case OR_Success:
10815 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010816 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010817 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010818 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010819 break;
10820
10821 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010822 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010823 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010824 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010825 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10826 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010827 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010828 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010829
10830 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010831 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010832 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010833 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10834 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010835 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010836 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010837
10838 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010839 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010840 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010841 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010842 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010843 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010844 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10845 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010846 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010847 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010848 }
10849
John McCall6bb80172010-03-30 21:47:33 +000010850 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010851
John McCallaa81e162009-12-01 22:10:20 +000010852 // If overload resolution picked a static member, build a
10853 // non-member call based on that function.
10854 if (Method->isStatic()) {
10855 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10856 Args, NumArgs, RParenLoc);
10857 }
10858
John McCall129e2df2009-11-30 22:42:35 +000010859 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010860 }
10861
John McCallf89e55a2010-11-18 06:31:45 +000010862 QualType ResultType = Method->getResultType();
10863 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10864 ResultType = ResultType.getNonLValueExprType(Context);
10865
Douglas Gregor88a35142008-12-22 05:46:06 +000010866 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010867 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010868 new (Context) CXXMemberCallExpr(Context, MemExprE,
10869 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010870 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010871
Anders Carlssoneed3e692009-10-10 00:06:20 +000010872 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010873 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010874 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010875 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010876
Douglas Gregor88a35142008-12-22 05:46:06 +000010877 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010878 // We only need to do this if there was actually an overload; otherwise
10879 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010880 if (!Method->isStatic()) {
10881 ExprResult ObjectArg =
10882 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10883 FoundDecl, Method);
10884 if (ObjectArg.isInvalid())
10885 return ExprError();
10886 MemExpr->setBase(ObjectArg.take());
10887 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010888
10889 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010890 const FunctionProtoType *Proto =
10891 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010892 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010893 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010894 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010895
Eli Friedmane61eb042012-02-18 04:48:30 +000010896 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10897
Richard Smith831421f2012-06-25 20:30:08 +000010898 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010899 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010900
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010901 if ((isa<CXXConstructorDecl>(CurContext) ||
10902 isa<CXXDestructorDecl>(CurContext)) &&
10903 TheCall->getMethodDecl()->isPure()) {
10904 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10905
Chandler Carruthae198062011-06-27 08:31:58 +000010906 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010907 Diag(MemExpr->getLocStart(),
10908 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10909 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10910 << MD->getParent()->getDeclName();
10911
10912 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010913 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010914 }
John McCall9ae2f072010-08-23 23:25:46 +000010915 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010916}
10917
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010918/// BuildCallToObjectOfClassType - Build a call to an object of class
10919/// type (C++ [over.call.object]), which can end up invoking an
10920/// overloaded function call operator (@c operator()) or performing a
10921/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010922ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010923Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010924 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010925 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010926 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010927 if (checkPlaceholderForOverload(*this, Obj))
10928 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010929 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010930
10931 UnbridgedCastsSet UnbridgedCasts;
10932 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10933 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010934
John Wiegley429bb272011-04-08 18:41:53 +000010935 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10936 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010937
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010938 // C++ [over.call.object]p1:
10939 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010940 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010941 // candidate functions includes at least the function call
10942 // operators of T. The function call operators of T are obtained by
10943 // ordinary lookup of the name operator() in the context of
10944 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010945 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010946 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010947
John Wiegley429bb272011-04-08 18:41:53 +000010948 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010949 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010950 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010951
John McCalla24dc2e2009-11-17 02:14:36 +000010952 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10953 LookupQualifiedName(R, Record->getDecl());
10954 R.suppressDiagnostics();
10955
Douglas Gregor593564b2009-11-15 07:48:03 +000010956 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010957 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010958 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10959 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010960 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010961 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010962
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010963 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010964 // In addition, for each (non-explicit in C++0x) conversion function
10965 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010966 //
10967 // operator conversion-type-id () cv-qualifier;
10968 //
10969 // where cv-qualifier is the same cv-qualification as, or a
10970 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010971 // denotes the type "pointer to function of (P1,...,Pn) returning
10972 // R", or the type "reference to pointer to function of
10973 // (P1,...,Pn) returning R", or the type "reference to function
10974 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010975 // is also considered as a candidate function. Similarly,
10976 // surrogate call functions are added to the set of candidate
10977 // functions for each conversion function declared in an
10978 // accessible base class provided the function is not hidden
10979 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010980 std::pair<CXXRecordDecl::conversion_iterator,
10981 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010982 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010983 for (CXXRecordDecl::conversion_iterator
10984 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010985 NamedDecl *D = *I;
10986 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10987 if (isa<UsingShadowDecl>(D))
10988 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010989
Douglas Gregor4a27d702009-10-21 06:18:39 +000010990 // Skip over templated conversion functions; they aren't
10991 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010992 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010993 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010994
John McCall701c89e2009-12-03 04:06:58 +000010995 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010996 if (!Conv->isExplicit()) {
10997 // Strip the reference type (if any) and then the pointer type (if
10998 // any) to get down to what might be a function type.
10999 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11000 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11001 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011002
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011003 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11004 {
11005 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000011006 Object.get(), llvm::makeArrayRef(Args, NumArgs),
11007 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011008 }
11009 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011010 }
Mike Stump1eb44332009-09-09 15:08:12 +000011011
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011012 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11013
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011014 // Perform overload resolution.
11015 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011016 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011017 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011018 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011019 // Overload resolution succeeded; we'll build the appropriate call
11020 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011021 break;
11022
11023 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011024 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011025 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011026 << Object.get()->getType() << /*call*/ 1
11027 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011028 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011029 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011030 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011031 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011032 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11033 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011034 break;
11035
11036 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011037 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011038 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011039 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011040 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11041 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011042 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011043
11044 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011045 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011046 diag::err_ovl_deleted_object_call)
11047 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011048 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011049 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011050 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011051 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11052 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011053 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011054 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011055
Douglas Gregorff331c12010-07-25 18:17:45 +000011056 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011057 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011058
John McCall5acb0c92011-10-17 18:40:02 +000011059 UnbridgedCasts.restore();
11060
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011061 if (Best->Function == 0) {
11062 // Since there is no function declaration, this is one of the
11063 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011064 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011065 = cast<CXXConversionDecl>(
11066 Best->Conversions[0].UserDefined.ConversionFunction);
11067
John Wiegley429bb272011-04-08 18:41:53 +000011068 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011069 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011070
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011071 // We selected one of the surrogate functions that converts the
11072 // object parameter to a function pointer. Perform the conversion
11073 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011074
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011075 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011076 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011077 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11078 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011079 if (Call.isInvalid())
11080 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011081 // Record usage of conversion in an implicit cast.
11082 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11083 CK_UserDefinedConversion,
11084 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011085
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011086 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011087 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011088 }
11089
John Wiegley429bb272011-04-08 18:41:53 +000011090 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011091
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011092 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11093 // that calls this method, using Object for the implicit object
11094 // parameter and passing along the remaining arguments.
11095 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011096
11097 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011098 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011099 return ExprError();
11100
Chandler Carruth6df868e2010-12-12 08:17:55 +000011101 const FunctionProtoType *Proto =
11102 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011103
11104 unsigned NumArgsInProto = Proto->getNumArgs();
11105 unsigned NumArgsToCheck = NumArgs;
11106
11107 // Build the full argument list for the method call (the
11108 // implicit object parameter is placed at the beginning of the
11109 // list).
11110 Expr **MethodArgs;
11111 if (NumArgs < NumArgsInProto) {
11112 NumArgsToCheck = NumArgsInProto;
11113 MethodArgs = new Expr*[NumArgsInProto + 1];
11114 } else {
11115 MethodArgs = new Expr*[NumArgs + 1];
11116 }
John Wiegley429bb272011-04-08 18:41:53 +000011117 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011118 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11119 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011120
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011121 DeclarationNameInfo OpLocInfo(
11122 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11123 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011124 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011125 HadMultipleCandidates,
11126 OpLocInfo.getLoc(),
11127 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011128 if (NewFn.isInvalid())
11129 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011130
11131 // Once we've built TheCall, all of the expressions are properly
11132 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011133 QualType ResultTy = Method->getResultType();
11134 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11135 ResultTy = ResultTy.getNonLValueExprType(Context);
11136
John McCall9ae2f072010-08-23 23:25:46 +000011137 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011138 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011139 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011140 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011141 delete [] MethodArgs;
11142
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011143 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011144 Method))
11145 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011146
Douglas Gregor518fda12009-01-13 05:10:00 +000011147 // We may have default arguments. If so, we need to allocate more
11148 // slots in the call for them.
11149 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011150 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011151 else if (NumArgs > NumArgsInProto)
11152 NumArgsToCheck = NumArgsInProto;
11153
Chris Lattner312531a2009-04-12 08:11:20 +000011154 bool IsError = false;
11155
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011156 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011157 ExprResult ObjRes =
11158 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11159 Best->FoundDecl, Method);
11160 if (ObjRes.isInvalid())
11161 IsError = true;
11162 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011163 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011164 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011165
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011166 // Check the argument types.
11167 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011168 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011169 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011170 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011171
Douglas Gregor518fda12009-01-13 05:10:00 +000011172 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011173
John McCall60d7b3a2010-08-24 06:29:42 +000011174 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011175 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011176 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011177 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011178 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011179
Anders Carlsson3faa4862010-01-29 18:43:53 +000011180 IsError |= InputInit.isInvalid();
11181 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011182 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011183 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011184 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11185 if (DefArg.isInvalid()) {
11186 IsError = true;
11187 break;
11188 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011189
Douglas Gregord47c47d2009-11-09 19:27:57 +000011190 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011191 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011192
11193 TheCall->setArg(i + 1, Arg);
11194 }
11195
11196 // If this is a variadic call, handle args passed through "...".
11197 if (Proto->isVariadic()) {
11198 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011199 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011200 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11201 IsError |= Arg.isInvalid();
11202 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011203 }
11204 }
11205
Chris Lattner312531a2009-04-12 08:11:20 +000011206 if (IsError) return true;
11207
Eli Friedmane61eb042012-02-18 04:48:30 +000011208 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11209
Richard Smith831421f2012-06-25 20:30:08 +000011210 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011211 return true;
11212
John McCall182f7092010-08-24 06:09:16 +000011213 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011214}
11215
Douglas Gregor8ba10742008-11-20 16:27:02 +000011216/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011217/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011218/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011219ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011220Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011221 assert(Base->getType()->isRecordType() &&
11222 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011223
John McCall5acb0c92011-10-17 18:40:02 +000011224 if (checkPlaceholderForOverload(*this, Base))
11225 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011226
John McCall5769d612010-02-08 23:07:23 +000011227 SourceLocation Loc = Base->getExprLoc();
11228
Douglas Gregor8ba10742008-11-20 16:27:02 +000011229 // C++ [over.ref]p1:
11230 //
11231 // [...] An expression x->m is interpreted as (x.operator->())->m
11232 // for a class object x of type T if T::operator->() exists and if
11233 // the operator is selected as the best match function by the
11234 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011235 DeclarationName OpName =
11236 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011237 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011238 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011239
John McCall5769d612010-02-08 23:07:23 +000011240 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011241 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011242 return ExprError();
11243
John McCalla24dc2e2009-11-17 02:14:36 +000011244 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11245 LookupQualifiedName(R, BaseRecord->getDecl());
11246 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011247
11248 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011249 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011250 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11251 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011252 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011253
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011254 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11255
Douglas Gregor8ba10742008-11-20 16:27:02 +000011256 // Perform overload resolution.
11257 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011258 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011259 case OR_Success:
11260 // Overload resolution succeeded; we'll build the call below.
11261 break;
11262
11263 case OR_No_Viable_Function:
11264 if (CandidateSet.empty())
11265 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011266 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011267 else
11268 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011269 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011270 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011271 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011272
11273 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011274 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11275 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011276 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011277 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011278
11279 case OR_Deleted:
11280 Diag(OpLoc, diag::err_ovl_deleted_oper)
11281 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011282 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011283 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011284 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011285 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011286 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011287 }
11288
John McCall9aa472c2010-03-19 07:35:19 +000011289 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11290
Douglas Gregor8ba10742008-11-20 16:27:02 +000011291 // Convert the object parameter.
11292 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011293 ExprResult BaseResult =
11294 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11295 Best->FoundDecl, Method);
11296 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011297 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011298 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011299
Douglas Gregor8ba10742008-11-20 16:27:02 +000011300 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011301 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011302 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011303 if (FnExpr.isInvalid())
11304 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011305
John McCallf89e55a2010-11-18 06:31:45 +000011306 QualType ResultTy = Method->getResultType();
11307 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11308 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011309 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011310 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011311 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011312
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011313 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011314 Method))
11315 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011316
11317 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011318}
11319
Richard Smith36f5cfe2012-03-09 08:00:36 +000011320/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11321/// a literal operator described by the provided lookup results.
11322ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11323 DeclarationNameInfo &SuffixInfo,
11324 ArrayRef<Expr*> Args,
11325 SourceLocation LitEndLoc,
11326 TemplateArgumentListInfo *TemplateArgs) {
11327 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011328
Richard Smith36f5cfe2012-03-09 08:00:36 +000011329 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11330 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11331 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011332
Richard Smith36f5cfe2012-03-09 08:00:36 +000011333 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11334
Richard Smith36f5cfe2012-03-09 08:00:36 +000011335 // Perform overload resolution. This will usually be trivial, but might need
11336 // to perform substitutions for a literal operator template.
11337 OverloadCandidateSet::iterator Best;
11338 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11339 case OR_Success:
11340 case OR_Deleted:
11341 break;
11342
11343 case OR_No_Viable_Function:
11344 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11345 << R.getLookupName();
11346 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11347 return ExprError();
11348
11349 case OR_Ambiguous:
11350 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11351 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11352 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011353 }
11354
Richard Smith36f5cfe2012-03-09 08:00:36 +000011355 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011356 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11357 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011358 SuffixInfo.getLoc(),
11359 SuffixInfo.getInfo());
11360 if (Fn.isInvalid())
11361 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011362
11363 // Check the argument types. This should almost always be a no-op, except
11364 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011365 Expr *ConvArgs[2];
11366 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11367 ExprResult InputInit = PerformCopyInitialization(
11368 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11369 SourceLocation(), Args[ArgIdx]);
11370 if (InputInit.isInvalid())
11371 return true;
11372 ConvArgs[ArgIdx] = InputInit.take();
11373 }
11374
Richard Smith9fcce652012-03-07 08:35:16 +000011375 QualType ResultTy = FD->getResultType();
11376 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11377 ResultTy = ResultTy.getNonLValueExprType(Context);
11378
Richard Smith9fcce652012-03-07 08:35:16 +000011379 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011380 new (Context) UserDefinedLiteral(Context, Fn.take(),
11381 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011382 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11383
11384 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11385 return ExprError();
11386
Richard Smith831421f2012-06-25 20:30:08 +000011387 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011388 return ExprError();
11389
11390 return MaybeBindToTemporary(UDL);
11391}
11392
Sam Panzere1715b62012-08-21 00:52:01 +000011393/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11394/// given LookupResult is non-empty, it is assumed to describe a member which
11395/// will be invoked. Otherwise, the function will be found via argument
11396/// dependent lookup.
11397/// CallExpr is set to a valid expression and FRS_Success returned on success,
11398/// otherwise CallExpr is set to ExprError() and some non-success value
11399/// is returned.
11400Sema::ForRangeStatus
11401Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11402 SourceLocation RangeLoc, VarDecl *Decl,
11403 BeginEndFunction BEF,
11404 const DeclarationNameInfo &NameInfo,
11405 LookupResult &MemberLookup,
11406 OverloadCandidateSet *CandidateSet,
11407 Expr *Range, ExprResult *CallExpr) {
11408 CandidateSet->clear();
11409 if (!MemberLookup.empty()) {
11410 ExprResult MemberRef =
11411 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11412 /*IsPtr=*/false, CXXScopeSpec(),
11413 /*TemplateKWLoc=*/SourceLocation(),
11414 /*FirstQualifierInScope=*/0,
11415 MemberLookup,
11416 /*TemplateArgs=*/0);
11417 if (MemberRef.isInvalid()) {
11418 *CallExpr = ExprError();
11419 Diag(Range->getLocStart(), diag::note_in_for_range)
11420 << RangeLoc << BEF << Range->getType();
11421 return FRS_DiagnosticIssued;
11422 }
11423 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11424 if (CallExpr->isInvalid()) {
11425 *CallExpr = ExprError();
11426 Diag(Range->getLocStart(), diag::note_in_for_range)
11427 << RangeLoc << BEF << Range->getType();
11428 return FRS_DiagnosticIssued;
11429 }
11430 } else {
11431 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011432 UnresolvedLookupExpr *Fn =
11433 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11434 NestedNameSpecifierLoc(), NameInfo,
11435 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011436 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011437
11438 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11439 CandidateSet, CallExpr);
11440 if (CandidateSet->empty() || CandidateSetError) {
11441 *CallExpr = ExprError();
11442 return FRS_NoViableFunction;
11443 }
11444 OverloadCandidateSet::iterator Best;
11445 OverloadingResult OverloadResult =
11446 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11447
11448 if (OverloadResult == OR_No_Viable_Function) {
11449 *CallExpr = ExprError();
11450 return FRS_NoViableFunction;
11451 }
11452 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11453 Loc, 0, CandidateSet, &Best,
11454 OverloadResult,
11455 /*AllowTypoCorrection=*/false);
11456 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11457 *CallExpr = ExprError();
11458 Diag(Range->getLocStart(), diag::note_in_for_range)
11459 << RangeLoc << BEF << Range->getType();
11460 return FRS_DiagnosticIssued;
11461 }
11462 }
11463 return FRS_Success;
11464}
11465
11466
Douglas Gregor904eed32008-11-10 20:40:00 +000011467/// FixOverloadedFunctionReference - E is an expression that refers to
11468/// a C++ overloaded function (possibly with some parentheses and
11469/// perhaps a '&' around it). We have resolved the overloaded function
11470/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011471/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011472Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011473 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011474 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011475 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11476 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011477 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011478 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011479
Douglas Gregor699ee522009-11-20 19:42:02 +000011480 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011481 }
11482
Douglas Gregor699ee522009-11-20 19:42:02 +000011483 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011484 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11485 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011486 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011487 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011488 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011489 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011490 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011491 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011492
11493 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011494 ICE->getCastKind(),
11495 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011496 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011497 }
11498
Douglas Gregor699ee522009-11-20 19:42:02 +000011499 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011500 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011501 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11503 if (Method->isStatic()) {
11504 // Do nothing: static member functions aren't any different
11505 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011506 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011507 // Fix the sub expression, which really has to be an
11508 // UnresolvedLookupExpr holding an overloaded member function
11509 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011510 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11511 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011512 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011513 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011514
John McCallba135432009-11-21 08:51:07 +000011515 assert(isa<DeclRefExpr>(SubExpr)
11516 && "fixed to something other than a decl ref");
11517 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11518 && "fixed to a member ref with no nested name qualifier");
11519
11520 // We have taken the address of a pointer to member
11521 // function. Perform the computation here so that we get the
11522 // appropriate pointer to member type.
11523 QualType ClassType
11524 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11525 QualType MemPtrType
11526 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11527
John McCallf89e55a2010-11-18 06:31:45 +000011528 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11529 VK_RValue, OK_Ordinary,
11530 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011531 }
11532 }
John McCall6bb80172010-03-30 21:47:33 +000011533 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11534 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011535 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011536 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011537
John McCall2de56d12010-08-25 11:45:40 +000011538 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011539 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011540 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011541 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011542 }
John McCallba135432009-11-21 08:51:07 +000011543
11544 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011545 // FIXME: avoid copy.
11546 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011547 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011548 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11549 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011550 }
11551
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011552 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11553 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011554 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011555 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011556 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011557 ULE->getNameLoc(),
11558 Fn->getType(),
11559 VK_LValue,
11560 Found.getDecl(),
11561 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011562 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011563 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11564 return DRE;
John McCallba135432009-11-21 08:51:07 +000011565 }
11566
John McCall129e2df2009-11-30 22:42:35 +000011567 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011568 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011569 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11570 if (MemExpr->hasExplicitTemplateArgs()) {
11571 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11572 TemplateArgs = &TemplateArgsBuffer;
11573 }
John McCalld5532b62009-11-23 01:53:49 +000011574
John McCallaa81e162009-12-01 22:10:20 +000011575 Expr *Base;
11576
John McCallf89e55a2010-11-18 06:31:45 +000011577 // If we're filling in a static method where we used to have an
11578 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011579 if (MemExpr->isImplicitAccess()) {
11580 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011581 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11582 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011583 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011584 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011585 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011586 MemExpr->getMemberLoc(),
11587 Fn->getType(),
11588 VK_LValue,
11589 Found.getDecl(),
11590 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011591 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011592 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11593 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011594 } else {
11595 SourceLocation Loc = MemExpr->getMemberLoc();
11596 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011597 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011598 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011599 Base = new (Context) CXXThisExpr(Loc,
11600 MemExpr->getBaseType(),
11601 /*isImplicit=*/true);
11602 }
John McCallaa81e162009-12-01 22:10:20 +000011603 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011604 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011605
John McCallf5307512011-04-27 00:36:17 +000011606 ExprValueKind valueKind;
11607 QualType type;
11608 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11609 valueKind = VK_LValue;
11610 type = Fn->getType();
11611 } else {
11612 valueKind = VK_RValue;
11613 type = Context.BoundMemberTy;
11614 }
11615
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011616 MemberExpr *ME = MemberExpr::Create(Context, Base,
11617 MemExpr->isArrow(),
11618 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011619 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011620 Fn,
11621 Found,
11622 MemExpr->getMemberNameInfo(),
11623 TemplateArgs,
11624 type, valueKind, OK_Ordinary);
11625 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011626 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011627 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011628 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011629
John McCall3fa5cae2010-10-26 07:05:15 +000011630 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011631}
11632
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011633ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011634 DeclAccessPair Found,
11635 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011636 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011637}
11638
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011639} // end namespace clang